_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q5400
DateController.syncCommand
train
public function syncCommand($url = 'http://www.baidu.com') { $timestamp = $this->_getRemoteTimestamp($url); if ($timestamp === false) { return $this->console->error(['fetch remote timestamp failed: `:url`', 'url' => $url]); } else { $this->_updateDate($timestamp); $this->console->write(date('Y-m-d H:i:s')); return 0; } }
php
{ "resource": "" }
q5401
DateController.remoteCommand
train
public function remoteCommand($url = 'http://www.baidu.com') { $timestamp = $this->_getRemoteTimestamp($url); if ($timestamp === false) { return $this->console->error(['fetch remote timestamp failed: `:url`', 'url' => $url]); } else { $this->console->writeLn(date('Y-m-d H:i:s', $timestamp)); return 0; } }
php
{ "resource": "" }
q5402
DateController.diffCommand
train
public function diffCommand($url = 'http://www.baidu.com') { $remote_ts = $this->_getRemoteTimestamp($url); $local_ts = time(); if ($remote_ts === false) { return $this->console->error(['fetch remote timestamp failed: `:url`', 'url' => $url]); } else { $this->console->writeLn(' local: ' . date('Y-m-d H:i:s', $local_ts)); $this->console->writeLn('remote: ' . date('Y-m-d H:i:s', $remote_ts)); $this->console->writeLn(' diff: ' . ($local_ts - $remote_ts)); return 0; } }
php
{ "resource": "" }
q5403
PluploadHandler._getRequestFile
train
private function _getRequestFile() { $data = [ 'name' => $this->_fileName, 'size' => $this->_fileSize, 'tmp_name' => $this->_filePath ]; return new \Mmi\Http\RequestFile($data); }
php
{ "resource": "" }
q5404
TvheadendCommand.askQuestion
train
protected function askQuestion($question, $choices, $default) { // Ask until we get a valid response do { echo $question.' '.$choices.': '; $handle = fopen("php://stdin", "r"); $line = fgets($handle); $response = trim($line); // Use default when no response is given if (empty($response)) $response = $default; } while (!in_array($response, explode('/', $choices))); return $response; }
php
{ "resource": "" }
q5405
ApiKeyController.requestApiKeyAction
train
public function requestApiKeyAction(Request $request) { /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $credentials = []; if ($request->request->has('login')) { $credentials[$this->getPropertyName(ClassMetadata::LOGIN_PROPERTY)] = $request->request->get('login'); } if ($request->request->has('password')) { $credentials[$this->getPropertyName(ClassMetadata::PASSWORD_PROPERTY)] = $request->request->get('password'); } [$user, $exception] = $this->processAuthentication($credentials); /** @var OnAssembleResponseEvent $result */ $result = $dispatcher->dispatch( Ma27ApiKeyAuthenticationEvents::ASSEMBLE_RESPONSE, new OnAssembleResponseEvent($user, $exception) ); if (!$response = $result->getResponse()) { throw new HttpException( Response::HTTP_INTERNAL_SERVER_ERROR, 'Cannot assemble the response!', $exception ); } return $response; }
php
{ "resource": "" }
q5406
ApiKeyController.removeSessionAction
train
public function removeSessionAction(Request $request) { /** @var \Doctrine\Common\Persistence\ObjectManager $om */ $om = $this->get($this->container->getParameter('ma27_api_key_authentication.object_manager')); if (!$header = (string) $request->headers->get($this->container->getParameter('ma27_api_key_authentication.key_header'))) { return new JsonResponse(['message' => 'Missing api key header!'], 400); } $user = $om ->getRepository($this->container->getParameter('ma27_api_key_authentication.model_name')) ->findOneBy([ $this->getPropertyName(ClassMetadata::API_KEY_PROPERTY) => $header, ]); $this->get('ma27_api_key_authentication.auth_handler')->removeSession($user); return new JsonResponse([], 204); }
php
{ "resource": "" }
q5407
ApiKeyController.processAuthentication
train
private function processAuthentication(array $credentials) { /** @var \Ma27\ApiKeyAuthenticationBundle\Service\Auth\AuthenticationHandlerInterface $authenticationHandler */ $authenticationHandler = $this->get('ma27_api_key_authentication.auth_handler'); /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */ $dispatcher = $this->get('event_dispatcher'); try { $user = $authenticationHandler->authenticate($credentials); } catch (CredentialException $ex) { $userOrNull = $user ?? null; $dispatcher->dispatch( Ma27ApiKeyAuthenticationEvents::CREDENTIAL_EXCEPTION_THROWN, new OnCredentialExceptionThrownEvent($ex, $userOrNull) ); return [$userOrNull, $ex]; } return [$user, null]; }
php
{ "resource": "" }
q5408
OracleMetaDataDAO.hydrateDataObject
train
private function hydrateDataObject($data) { $dataObject = new MetadataDataObjectOracle( new MetaDataColumnCollection(), new MetaDataRelationCollection() ); $tableName = $data['TABLE_NAME']; $owner = $data['OWNER']; $dataObject->setName($owner . '/' . $tableName); $columnDataObject = new MetaDataColumn(); $statement = $this->pdo->prepare( sprintf( "SELECT COLUMN_NAME as name, NULLABLE as nullable, DATA_TYPE as type, DATA_LENGTH as length FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME = '%s' and OWNER= '%s'", $tableName, $owner ) ); $statement->execute(array()); $allFields = $statement->fetchAll(PDO::FETCH_ASSOC); $identifiers = $this->getIdentifiers($owner, $tableName); foreach ($allFields as $metadata) { $column = clone $columnDataObject; $type = $metadata['type']; if (isset($this->typeConversion[$type]) === true) { $type = $this->typeConversion[$type]; } $column->setName($metadata['name']) ->setType($type) ->setLength( isset($metadata['length']) === true ? $metadata['length'] : null ); if (in_array($metadata['name'], $identifiers) === true) { $column->setPrimaryKey(true); } $dataObject->appendColumn($column); } return $dataObject; }
php
{ "resource": "" }
q5409
MySQLMetaDataDAO.pdoMetadataToGeneratorMetadata
train
private function pdoMetadataToGeneratorMetadata(array $metadataCollection) { $metaDataCollection = new MetaDataCollection(); foreach ($metadataCollection as $tableName) { $metaDataCollection->append( $this->hydrateDataObject($tableName) ); } return $metaDataCollection; }
php
{ "resource": "" }
q5410
MySQLMetaDataDAO.hydrateDataObject
train
private function hydrateDataObject($tableName, array $parentName = array()) { $dataObject = new MetadataDataObjectMySQL( new MetaDataColumnCollection(), new MetaDataRelationCollection() ); $dataObject->setName($tableName); $statement = $this->pdo->prepare( "SELECT columnTable.column_name, columnTable.table_name, columnTable.data_type, columnTable.column_key, columnTable.is_nullable, k.referenced_table_name, k.referenced_column_name FROM information_schema.columns as columnTable left outer join information_schema.key_column_usage k on k.table_schema=columnTable.table_schema and k.table_name=columnTable.table_name and k.column_name=columnTable.column_name WHERE columnTable.table_name = :tableName AND columnTable.table_schema = :databaseName" ); $statement->execute( array( ':tableName' => $tableName, ':databaseName' => $this->pdoConfig->getResponse('configDatabaseName'), ) ); $allFields = $statement->fetchAll(PDO::FETCH_ASSOC); $columnsAssociation = array(); foreach ($allFields as $index => $metadata) { if ($metadata['referenced_table_name'] !== null && $metadata['referenced_column_name'] !== null) { $columnsAssociation[$index] = $metadata; unset($allFields[$index]); continue; } } return $this->hydrateRelation( $this->hydrateFields($dataObject, $allFields), $columnsAssociation, $parentName ); }
php
{ "resource": "" }
q5411
Auth.authenticate
train
public static function authenticate($identity, $credential) { //błędna autoryzacja (brak aktywnego użytkownika) if (null === $record = self::_findUserByIdentity($identity)) { return; } //próby logowania lokalnie i ldap if (!self::_localAuthenticate($record, $credential) && !self::_ldapAuthenticate($record, $credential)) { self::_updateUserFailedLogin($record); return self::_authFailed($identity, 'Invalid password.'); } //poprawna autoryzacja return self::_authSuccess($record); }
php
{ "resource": "" }
q5412
Auth.idAuthenticate
train
public static function idAuthenticate($id) { //wyszukiwanie aktywnego użytkownika if (null === $record = self::_findUserByIdentity($id)) { return; } return self::_authSuccess($record); }
php
{ "resource": "" }
q5413
Auth._authSuccess
train
protected static function _authSuccess(CmsAuthRecord $record) { //zapis poprawnego logowania do rekordu $record->lastIp = \Mmi\App\FrontController::getInstance()->getEnvironment()->remoteAddress; $record->lastLog = date('Y-m-d H:i:s'); $record->save(); \Mmi\App\FrontController::getInstance()->getLogger()->info('Logged in: ' . $record->username); //nowy obiekt autoryzacji $authRecord = new \Mmi\Security\AuthRecord; //ustawianie pól rekordu $authRecord->id = $record->id; $authRecord->name = $record->name; $authRecord->username = $record->username; $authRecord->email = $record->email; $authRecord->lang = $record->lang; $authRecord->roles = count($record->getRoles()) ? $record->getRoles() : ['guest']; return $authRecord; }
php
{ "resource": "" }
q5414
ConnectorModel.importFileMeta
train
public function importFileMeta(array $files) { //iteracja po plikach (ta sama nazwa "name") foreach ($files as $importData) { //brak id if (!isset($importData['name']) || !isset($importData['id'])) { return; } //sprawdzanie istnienia pliku if (null === $file = (new \Cms\Orm\CmsFileQuery)->findPk($importData['id'])) { $file = new \Cms\Orm\CmsFileRecord; } //identyfikatory niezgodne if ($file->name && $file->name != $importData['name']) { continue; } //ustawienie danych rekordu rekordu $file->setFromArray($importData); //poprawny zapis if (!$file->save()) { return; } } //zwrot ostatniego pliku (potrzebny jest dowolny) return $file; }
php
{ "resource": "" }
q5415
Client.decode
train
public function decode($json) { $decoded = json_decode($json, true); if (null !== $decoded) { return $decoded; } if (JSON_ERROR_NONE === json_last_error()) { return $json; } return self::$json_errors[json_last_error()]; }
php
{ "resource": "" }
q5416
CustomColumn.renderCell
train
public function renderCell(\Mmi\Orm\RecordRo $record) { $view = FrontController::getInstance()->getView(); $view->record = $record; return $view->renderDirectly($this->getTemplateCode()); }
php
{ "resource": "" }
q5417
SerializeHydrator.extract
train
public function extract(callable $callback = null) { if ($callback === null) { $result = $this->result->serialize(); } else { $result = $callback($this->result->serialize()); } return $result; }
php
{ "resource": "" }
q5418
PHPCompiler.set_conf
train
function set_conf( $confname ){ $this->confname = $confname; $this->confdir = PLUG_HOST_DIR.'/'.$confname; if( ! PLUGTool::check_dir($this->confdir) ){ throw new PLUGException('bad conf'); } // parse default plug conf using external parser $confpath = $this->confdir.'/PLUG.conf.php'; $this->conf_vars = array(); $this->conf_consts = array (); $this->load_conf( $confpath ); }
php
{ "resource": "" }
q5419
PHPCompiler.load_conf
train
function load_conf( $confpath ){ if( ! PLUGTool::check_file($confpath) ){ throw new PLUGException('bad conf'); } $e = PLUG::exec_bin( 'parseconf', array($confpath), $s ); if( $e ){ trigger_error('Failed to parse '.basename($confpath), E_USER_NOTICE ); return false; } $a = unserialize( $s ); if( ! is_array($a) ){ trigger_error( "parseconf returned bad serialize string, $s", E_USER_WARNING ); return false; } $this->conf_vars = array_merge( $this->conf_vars, $a[0] ); $this->conf_consts = array_merge( $this->conf_consts, $a[1] ); return true; }
php
{ "resource": "" }
q5420
PHPCompiler.register_include
train
function register_include( $path ){ if( ! isset($this->incs[$path]) ){ $this->incs[$path] = 1; return false; } else { $this->incs[$path]++; return true; } }
php
{ "resource": "" }
q5421
PHPCompiler.next_dependency
train
function next_dependency(){ foreach( $this->dependencies as $path => $done ){ if( ! $done ){ $this->dependencies[$path] = 1; return $path; } } // none return null; }
php
{ "resource": "" }
q5422
PHPCompiler.open_php
train
private function open_php( &$src ){ if( ! $this->inphp ){ $this->inphp = true; // this may result in back to back tags, which we can avoid with a bit of string manipulation. $makenice = $this->opt(COMPILER_OPTION_NICE_TAGS); if( $makenice && substr( $src, -2 ) === '?>' ){ // trim trailing close tag, so no need to open one $src = substr_replace( $src, '', -2 ); } else { $ws = $this->opt(COMPILER_OPTION_WHITESPACE) ? "\n" : ' '; $src .= '<?php'.$ws; } } return $src; }
php
{ "resource": "" }
q5423
PHPCompiler.close_php
train
private function close_php( &$src ){ if( $this->inphp ){ $this->inphp = false; // this may result in back to back tags, which we can avoid with a bit of string manipulation. $makenice = $this->opt(COMPILER_OPTION_NICE_TAGS); if( $makenice && substr( $src, -5 ) === '<?php' ){ // trim trailing open tag, so no need to close $src = substr_replace( $src, '', -5 ); } else { $src .= ' ?>'; } } return $src; }
php
{ "resource": "" }
q5424
PLUGSessionObject.session_lifespan
train
function session_lifespan( $ttl = null, $hibernate = null ){ $current = $this->sess_ttl; if( $ttl !== null ){ $this->sess_ttl = $ttl; } if( $hibernate !== null ){ $this->sess_hibernate = $hibernate; } return $current; }
php
{ "resource": "" }
q5425
PLUG.raise_error
train
static function raise_error( $code, $message, $type, array $trace = null ){ if( error_reporting() === 0 ){ // suppressed with `@' operator return; } self::clear_error_handlers(); if( is_null($trace) ){ $trace = debug_backtrace(); array_shift( $trace ); } $callee = current( $trace ); $Err = new PLUGError( $code, $type, $message, $callee['file'], $callee['line'], $trace ); $Err->raise(); self::set_error_handlers(); return $Err; }
php
{ "resource": "" }
q5426
PLUG.raise_exception
train
static function raise_exception( Exception $Ex, $type ){ if( error_reporting() === 0 ){ // suppressed with `@' operator return; } PLUG::clear_error_handlers(); $code = $Ex->getCode() or $code = PLUG_EXCEPTION_STD; $Err = new PLUGError( $code, $type, $Ex->getMessage(), $Ex->getFile(), $Ex->getLine(), $Ex->getTrace() ); $Err->raise(); PLUG::set_error_handlers(); return $Err; }
php
{ "resource": "" }
q5427
PLUG.dump_errors
train
static function dump_errors( $emask = PLUG_ERROR_REPORTING ){ $errs = PLUGError::get_errors( $emask ); foreach( $errs as $Err ){ $s = $Err->__toString(). "\n"; if( PLUG_CLI ){ PLUGCli::stderr( $s ); } else { echo $s; } } }
php
{ "resource": "" }
q5428
PLUG.set_error_display
train
static function set_error_display( $handler ){ if( ! is_callable($handler) ){ trigger_error( 'Error display handler is not callable ('.var_export($handler,1).')', E_USER_WARNING ); return false; } PLUGError::$displayfunc = $handler; return true; }
php
{ "resource": "" }
q5429
PLUG.set_error_logger
train
static function set_error_logger( $handler ){ if( ! is_callable($handler) ){ trigger_error( 'Error logging handler is not callable ('.var_export($handler,1).')', E_USER_WARNING ); return false; } PLUGError::$logfunc = $handler; return true; }
php
{ "resource": "" }
q5430
PLUG.set_error_terminator
train
static function set_error_terminator( $handler ){ if( ! is_callable($handler) ){ trigger_error( 'Fatal error handler is not callable ('.var_export($handler,1).')', E_USER_WARNING ); return false; } PLUGError::$deathfunc = $handler; return true; }
php
{ "resource": "" }
q5431
UpdateLastActionFieldListener.onFirewallLogin
train
public function onFirewallLogin(OnFirewallAuthenticationEvent $event) { $this->doModify($event); $this->om->persist($event->getUser()); $this->om->flush(); }
php
{ "resource": "" }
q5432
UpdateLastActionFieldListener.doModify
train
private function doModify(AbstractUserEvent $event) { $this->classMetadata->modifyProperty( $event->getUser(), new \DateTime(sprintf('@%s', $this->requestStack->getMasterRequest()->server->get('REQUEST_TIME'))), ClassMetadata::LAST_ACTION_PROPERTY ); }
php
{ "resource": "" }
q5433
Acl.setupAcl
train
public static function setupAcl() { $acl = new \Mmi\Security\Acl; $aclData = (new CmsAclQuery) ->join('cms_role')->on('cms_role_id') ->find(); foreach ($aclData as $aclRule) { /* @var $aclData \Cms\Orm\CmsAclRecord */ $resource = ''; if ($aclRule->module) { $resource .= $aclRule->module . ':'; } if ($aclRule->controller) { $resource .= $aclRule->controller . ':'; } if ($aclRule->action) { $resource .= $aclRule->action . ':'; } $access = $aclRule->access; if ($access == 'allow' || $access == 'deny') { $acl->$access($aclRule->getJoined('cms_role')->name, trim($resource, ':')); } } return $acl; }
php
{ "resource": "" }
q5434
Log.create
train
public function create($userId=null, $eventLog=null, $eventData=null) { if(is_null($userId)) throw new \Exception('User ID is required.'); if(is_null($eventLog)) throw new \Exception('Event Log is required.'); if(!is_numeric($userId)) throw new \Exception("Invalid User ID."); $id = $this->save($this->generateEntity(intval($userId), $eventLog, $eventData)); return $id; }
php
{ "resource": "" }
q5435
AnnotatedRouteControllerLoader.configureRoute
train
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot) { parent::configureRoute($route, $class, $method, $annot); if(is_a($annot, 'FOM\ManagerBundle\Configuration\Route')) { $route->setPath($this->prefix . $route->getPath()); } }
php
{ "resource": "" }
q5436
PayPayWebservice.checkIntegrationState
train
public function checkIntegrationState() { $this->response = parent::checkIntegrationState($this->entity); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response)) { throw new Exception\IntegrationState($this->response); } return $this->response; }
php
{ "resource": "" }
q5437
PayPayWebservice.subscribeToWebhook
train
public function subscribeToWebhook(Structure\RequestWebhook $requestWebhook) { $this->response = parent::subscribeToWebhook($this->entity, $requestWebhook); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) { throw new Exception\IntegrationState($this->response->integrationState); } /** * Caso ocorra algum erro específico do método. */ if ($this->response->integrationState->state == 0) { throw new Exception\IntegrationResponse( $this->response->integrationState->message, $this->response->integrationState->code ); } return $this->response; }
php
{ "resource": "" }
q5438
PayPayWebservice.createPaymentReference
train
public function createPaymentReference(Structure\RequestReferenceDetails $paymentData) { $this->response = parent::createPaymentReference($this->entity, $paymentData); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) { throw new Exception\IntegrationState($this->response->integrationState); } /** * In case an error code is returned not related to the integration state. * (eg.: maximum daily amount exceeded, maximum reference amount, etc.) */ if ($this->response->state == 0) { throw new Exception\IntegrationResponse( $this->response->err_msg, $this->response->err_code ); } return $this->response; }
php
{ "resource": "" }
q5439
PayPayWebservice.validatePaymentReference
train
public function validatePaymentReference(Structure\RequestReferenceDetails $paymentData) { $this->response = parent::validatePaymentReference($this->entity, $paymentData); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) { throw new Exception\IntegrationState($this->response->integrationState); } /** * In case an error code is returned not related to the integration state. * (eg.: maximum daily amount exceeded, maximum reference amount, etc.) */ if (!empty($this->response->err_code)) { throw new Exception\IntegrationResponse( $this->response->err_msg, $this->response->err_code ); } return $this->response; }
php
{ "resource": "" }
q5440
PayPayWebservice.doWebPayment
train
public function doWebPayment($requestWebPayment) { $this->response = parent::doWebPayment($this->entity, $requestWebPayment); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->requestState)) { throw new Exception\IntegrationState($this->response->requestState); } /** * Se a resposta retornar algum erro previsto. */ if ($this->response->requestState->state == 0) { throw new Exception\IntegrationResponse( $this->response->requestState->message, $this->response->requestState->code ); } return $this->response; }
php
{ "resource": "" }
q5441
PayPayWebservice.checkWebPayment
train
public function checkWebPayment($token, $transactionId) { $requestPayment = new Structure\RequestPaymentDetails($token, $transactionId); $this->response = parent::checkWebPayment($this->entity, $requestPayment); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->requestState)) { throw new Exception\IntegrationState($this->response->requestState); } if ($this->response->requestState->state == 0) { throw new Exception\IntegrationResponse( $this->response->requestState->message, $this->response->requestState->code ); } return $this->response; }
php
{ "resource": "" }
q5442
PayPayWebservice.getEntityPayments
train
public function getEntityPayments($startDate, $endDate) { $requestInterval = new Structure\RequestInterval($startDate, $endDate); $this->response = parent::getEntityPayments($this->entity, $requestInterval); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) { throw new Exception\IntegrationState($this->response->integrationState); } return $this->response; }
php
{ "resource": "" }
q5443
PayPayWebservice.checkEntityPayments
train
public function checkEntityPayments($payments = array()) { $requestReferenceDetails = new Structure\RequestEntityPayments(); if ($payments) { foreach ($payments as $key => $value) { $requestPayment = new Structure\RequestReferenceDetails($value); $requestReferenceDetails->addPayment($requestPayment); } } $this->response = parent::checkEntityPayments($this->entity, $requestReferenceDetails); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->state)) { throw new Exception\IntegrationState($this->response->state); } if ($this->response->state->state == 0) { throw new Exception\IntegrationResponse($this->response->state->message, $this->response->state->code); } return $this->response; }
php
{ "resource": "" }
q5444
ZendFramework2Environnement.getDependence
train
public static function getDependence(FileManager $fileManager) { if (null === self::$serviceManager) { $config = self::findConfigFile($fileManager); try { self::$serviceManager = Application::init( $fileManager->includeFile($config) )->getServiceManager(); } catch(RuntimeException $e) { throw new EnvironnementResolverException($e->getMessage()); } catch (ExceptionInterface $e) { throw new EnvironnementResolverException( sprintf( '%s. Config loaded %s', $e->getMessage(), $config ) ); } } return self::$serviceManager; }
php
{ "resource": "" }
q5445
LRStation.collect_non_deterministic
train
function collect_non_deterministic( Grammar $Grammar, $k ){ // avoid recursion by testing if already collected if ( isset($this->etransitions) ){ return; } $this->etransitions = array(); // get all rules with our non-terminal as left had side foreach( $Grammar->get_rules($this->nt) as $r => $rule ){ // create single Item for new state with pointer at start of rule $Item = LRItem::make( $r, $rule, 0 ); if( isset($this->la) && $k === 1 ){ $Item->lookahead( $this->la ); } // create e-transition to state with single item $State = LRState::make( $Item ); $State->collect_non_deterministic( $Grammar, $k ); $this->etransitions[] = $State; } }
php
{ "resource": "" }
q5446
LRStation.collect_states
train
function collect_states( Grammar $Grammar ){ $states = array(); // start recursion $this->collect_states_recursive( $states, $Grammar, array(), ++self::$threadInc ); return $states; }
php
{ "resource": "" }
q5447
LRStation.make
train
static function make( $nt, $la = null ){ if( isset(self::$uindex[$nt][$la]) ){ return self::$uindex[$nt][$la]; } return new LRStation( $nt, $la ); }
php
{ "resource": "" }
q5448
LRStation.get
train
static function get( $nt, $la = null ){ if( isset(self::$uindex[$nt][$la]) ){ return self::$uindex[$nt][$la]; } return null; }
php
{ "resource": "" }
q5449
IncStatementNode.get_args
train
function get_args( array $consts, array $vars ){ $args = array(); // limit depth of search to avoid collecting nested func calls $argnodes = $this->get_nodes_by_symbol( NT_ARG, 3 ); foreach( $argnodes as $i => $arg ){ $args[] = $arg->compile_string( $consts, $vars ); } return $args; }
php
{ "resource": "" }
q5450
HistoryFactory.getInstance
train
public static function getInstance(ContextInterface $context) { $fileManager = new FileManager(); $historyHydrator = HistoryHydratorFactory::getInstance($context); return new HistoryManager($fileManager, $historyHydrator); }
php
{ "resource": "" }
q5451
GrammarBuilder.make
train
static function make( array $grammar, $class = __CLASS__ ){ $Me = new $class; foreach( $grammar as $nt => $rhss ){ foreach( $rhss as $rhs ){ $Me->make_rule( $nt, $rhs ); } } return $Me; }
php
{ "resource": "" }
q5452
GrammarBuilder.rule_signature
train
private static function rule_signature( $lhs, array $rhs ){ $a[] = $lhs; foreach( $rhs as $t ){ $a[] = $t; } return implode( '.', $a ); }
php
{ "resource": "" }
q5453
GrammarBuilder.make_rule
train
function make_rule( $nt, array $rhs ){ if( ! isset($this->uindex) || ! isset($this->ntindex) ){ $this->rebuild_index(); } // explicit goal rule ?? if( end($rhs) === P_EOF ){ // trigger_error("Do not specify P_EOF explicitly in grammar", E_USER_WARNING ); $this->goal = $nt; $this->rules[ -2 ] = array( P_GOAL, array( $nt ) ); $this->rebuild_index(); } // guess start symbol as first in grammar else if( is_null( $this->start_symbol() ) ){ $this->start_symbol( $nt ); } reset( $rhs ); $sig = self::rule_signature( $nt, $rhs ); // return existing if possible if( isset($this->uindex[$sig]) ){ return $this->rules[ $this->uindex[$sig] ]; } // else create new rule $rule = array( $nt, $rhs ); // register globally $this->rules[ $this->i ] = $rule; $this->uindex[$sig] = $this->i; $this->ntindex[$nt][] = $this->i; $this->i += 2; // register symbols if( isset($this->ts[$nt] ) ){ // not terminal after all unset( $this->ts[$nt] ); } $this->nts[ $nt ] = $nt; // assume rhs all terminals until identified as not foreach( $rhs as $s ){ is_array( $s ) and $s = $s[0]; if( !isset($this->nts[$s]) ){ $this->ts[ $s ] = $s; } } return $rule; }
php
{ "resource": "" }
q5454
GrammarBuilder.remove_rules
train
function remove_rules( $nt ){ if( ! isset($this->ntindex) ){ $this->rebuild_index(); } // remove this non-terminal's rules if( isset($this->ntindex[$nt]) ){ foreach( $this->ntindex[$nt] as $i ){ $sig = self::rule_signature( $nt, $this->rules[$i][1] ); unset( $this->rules[$i] ); unset( $this->uindex[$sig] ); } } // remove non terminal unset ( $this->nts[$nt], $this->ntindex[$nt] ); }
php
{ "resource": "" }
q5455
GrammarBuilder.build_first_sets
train
private function build_first_sets(){ $firsts = array(); do { $changes = 0; foreach( $this->rules as $rule ){ list( $nt, $rhs ) = $rule; $s = reset( $rhs ); // get any special rule processing for this non-terminal //$excludela = isset($this->excludela[$nt]) ? $this->excludela[$nt] : null; do { // add terminal to first set of $nt if( $this->is_terminal( $s ) ){ if( ! isset($firsts[$nt][$s]) ){ $firsts[$nt][$s] = $s; $changes++; } continue 2; } // else inherit from first set of this non-terminal if( ! isset($firsts[$s]) ){ // throw new Exception( sprintf("FIRST(%s) not defined", $s) ); $changes++; continue 2; } // collect all terminal symbols in this non-terminal's set // except the empty string which we do not inherit. $derives_e = isset( $firsts[$s][P_EPSILON] ); foreach( $firsts[$s] as $t ){ // Omit any lookahead symbols denied by special rule //if( $excludela && in_array( $t, $excludela,true ) ){ // // ignored //} //else if( $t !== P_EPSILON && ! isset( $firsts[$nt][$t] ) ){ $firsts[$nt][$t] = $t; $changes++; } } // we move to next in sequence if non-terminal can derive empty } while( $derives_e && $s = next($rhs) ); } } while( $changes > 0 ); return $firsts; }
php
{ "resource": "" }
q5456
GrammarBuilder.build_follow_sets
train
private function build_follow_sets(){ if( ! isset($this->firsts) ){ $this->firsts = $this->build_first_sets(); } // remember inhritance for error checking //$inherits = array(); // create default/dummy sets with special symbols $follows = array( P_GOAL => array(), P_EOF => array() ); do { $changes = 0; foreach( $this->rules as $rule ){ list( $s, $rhs ) = $rule; //echo "----\n"; //echo "$s -> ", implode(',', $rhs), "\n"; while( $a = current($rhs) ){ if( $a === P_EPSILON ){ next($rhs); continue; } //echo "\na = $a\n"; if( false === next($rhs) ){ // end of rule, inherit from LHS if( !isset($follows[$s]) ){ //echo "FOLLOW($s) not set, required by $a \n"; //$inherits[$s] = true; continue 2; } foreach( $follows[$s] as $t ){ if( !isset($follows[$a][$t]) ){ //echo "FOLLOW($a) []= $t \n"; $follows[$a][$t] = $t; $changes++; } } // next rule. continue 2; } $r = array_slice( $rhs, key($rhs) ); while( $b = current($r) ){ //echo "b = $b\n"; // merge first(b) into follow(a), // if it derives the empty string, continue to next in rhs $fs = $this->is_terminal($b) ? array($b) : $this->firsts[$b]; //echo "FOLLOW($a) []= FIRST($b) = ",implode(',', $fs),"\n"; foreach( $fs as $t ){ if( ! isset($follows[$a][$t]) && $t !== P_EPSILON ){ $follows[$a][$t] = $t; //echo "FOLLOW($a) []= $t \n"; $changes++; } } // if derives empty, skip to next or inherit lhs if( ! isset($fs[P_EPSILON]) ){ break; } if( false === next($r) ){ //echo "FOLLOW($a) []= FOLLOW($s)\n"; if( !isset($follows[$s]) ){ //echo "FOLLOW($s) not set, required by $a \n"; //$inherits[$s] = true; continue 3; } foreach( $follows[$s] as $t ){ if( !isset($follows[$a][$t]) ){ //echo "FOLLOW($a) []= $t \n"; $follows[$a][$t] = $t; $changes++; } } } } } } } while( $changes ); // check inheritance problems, uncomment to debug /* foreach( $inherits as $s => $bool ){ if( ! isset($follows[$s]) ){ trigger_error("FOLLOW($s) was never created", E_USER_NOTICE ); } } //*/ return $follows; }
php
{ "resource": "" }
q5457
JsonHydrator.extract
train
public function extract(callable $callback = null) { $this->response = Di::getDefault()->get('response'); if ($callback === null) { $this->response->setContent(json_encode($this->result->toArray())); } else { $this->response->setContent($callback( json_encode($this->result->toArray()) )); } $this->response->send(); }
php
{ "resource": "" }
q5458
IsEventSubscriberConstraint.matches
train
protected function matches($other): bool { $this->resetProblems(); if (!($other instanceof EventSubscriberInterface)) { $this->addProblem('Subscriber must implement \Symfony\Component\EventDispatcher\EventSubscriberInterface.'); return false; } $subscribedEvents = call_user_func(array(get_class($other), 'getSubscribedEvents')); if (!is_array($subscribedEvents)) { $this->addProblem('getSubscribedEvents() must return an array.'); return false; } foreach ($subscribedEvents as $event => $subscription) { /* @var $event string */ /* @var $subscription mixed|string|array */ $this->checkListener($other, $event, $subscription); } return !$this->hasProblems(); }
php
{ "resource": "" }
q5459
IsEventSubscriberConstraint.checkListener
train
protected function checkListener(EventSubscriberInterface $subscriber, $event, $listener) { if (is_string($listener)) { // Add the default priority and use the default validation. $listener = array($listener, 0); } if (!is_array($listener)) { $this->addProblem(sprintf('Listener definition for event "%s" must be an array or a string.', $event)); return; } if ($this->containsSeveralSubscriptions($listener)) { foreach ($listener as $subListener) { $this->checkListener($subscriber, $event, $subListener); } return; } if (count($listener) === 1) { // Method without priority. $listener[] = 0; } if (count($listener) !== 2) { $message = 'Listener definition for event "%s" must consist of a method and a priority, but received: %s'; $this->addProblem(sprintf($message, $event, $this->exporter->export($listener))); return; } list($method, $priority) = $listener; $this->checkMethod($subscriber, $event, $method); $this->checkPriority($event, $priority); }
php
{ "resource": "" }
q5460
IsEventSubscriberConstraint.checkMethod
train
protected function checkMethod($subscriber, $event, $method) { if (!is_string($method)) { $message = 'Listener definition for event "%s" contains an invalid method reference: %s'; $this->addProblem(sprintf($message, $event, $this->exporter->export($method))); return; } if (!method_exists($subscriber, $method)) { $message = 'Listener definition for event "%s" references method "%s", ' . 'but the method does not exist on subscriber.'; $this->addProblem(sprintf($message, $event, $method)); return; } if (!is_callable(array($subscriber, $method))) { $message = 'Listener definition for event "%s" references method "%s", ' . 'but the method is not publicly accessible.'; $this->addProblem(sprintf($message, $event, $method)); return; } }
php
{ "resource": "" }
q5461
IsEventSubscriberConstraint.checkPriority
train
protected function checkPriority($event, $priority) { if (!is_int($priority)) { $message = 'Priority for event "%s" must be an integer, but received: %s'; $this->addProblem(sprintf($message, $event, $this->exporter->export($priority))); return; } }
php
{ "resource": "" }
q5462
ControllerPolicyMiddleware.isIgnoredDomain
train
public function isIgnoredDomain($domain) { if ($ignoreRegexes = $this->config()->get('ignore_domain_regexes')) { foreach ($ignoreRegexes as $ignore) { if (preg_match($ignore, $domain) > 0) { return true; } } } return false; }
php
{ "resource": "" }
q5463
ControllerPolicyMiddleware.process
train
public function process(HTTPRequest $request, callable $delegate) { /** @var HTTPResponse $response */ $response = $delegate($request); // Ignore by regexes. if ($this->shouldCheckHttpHost() && $this->isIgnoredDomain($_SERVER['HTTP_HOST'])) { return $response; } foreach ($this->requestedPolicies as $requestedPolicy) { /** @var ControllerPolicy $policyInstance */ $policyInstance = $requestedPolicy['policy']; $policyInstance->applyToResponse( $requestedPolicy['originator'], $request, $response ); } return $response; }
php
{ "resource": "" }
q5464
Direct._message
train
public function _message($type, $message) { $context = $this->_context; $cssClasses = isset($this->_cssClasses[$type]) ? $this->_cssClasses[$type] : ''; $context->messages[] = '<div class="' . $cssClasses . '">' . $message . '</div>' . PHP_EOL; }
php
{ "resource": "" }
q5465
CategoryAclModel._updateAcl
train
protected function _updateAcl(\Cms\Orm\CmsCategoryAclRecord $aclRecord) { //iteracja po identyfikatorach kategorii foreach ($this->_getChildrenCategoryIds($aclRecord->cmsCategoryId) as $categoryId) { //dozwalanie lub zabranianie w ACL $aclRecord->access == 'allow' ? $this->_acl->allow($aclRecord->getJoined('cms_role')->name, $categoryId) : $this->_acl->deny($aclRecord->getJoined('cms_role')->name, $categoryId); } }
php
{ "resource": "" }
q5466
PLUGTool.import_php
train
static function import_php( $package, $silent = false ){ $type = current( explode('.', $package) ); $paths = self::collect_package( $package, 'php', $silent, 'conf' ); if( !$silent && empty($paths) ){ trigger_error("Bad import `$package'", E_USER_ERROR ); } foreach( $paths as $cname => $path ){ // leniant inclusion if silent if( $silent ){ include_once $path; continue; } // path should already be validated by collect_package require_once $path; // Run checks according to type of import switch( $type ){ case 'conf': break; default: // Class or function import must define an entity with the same name as the file // testing function first to avoid call to __autoload if( ! function_exists($cname) && ! class_exists($cname) ){ trigger_error( "Class, or function '$cname' not defined in file `$path'", E_USER_ERROR ); } } } }
php
{ "resource": "" }
q5467
PLUGTool.collect_package
train
static function collect_package( $package, $ext, $silent, $confname ){ // get from cache for speed $cachekey = $package.'.'.$ext; if( isset(self::$dircache[$cachekey]) ){ return self::$dircache[$cachekey]; } $apath = explode( '.', $package ); $type = $apath[0]; // e.g. "PLUG" $cname = array_pop( $apath ); // e.g. "PLUGSession" // force special extensions, in certain cases switch( $type ){ case 'conf': $ext = 'conf.php'; break; } // special rules for types of import switch( $ext ){ case 'js': // Javascript under document root $dpath = PLUG_VIRTUAL_DIR.'/plug/js/'.implode( '/', $apath ); break; case 'conf.php': // replace with target conf dir $apath[0] = $confname; // fall through .... default: // regular PHP import from outside document root $dpath = PLUG_HOST_DIR .'/'. implode( '/', $apath ); } $incs = array(); switch( $cname ){ case '': case '*': // import all files under directory if( !$silent && !self::check_dir( $dpath ) ){ break; } $dhandle = opendir( $dpath ); while( $f = readdir($dhandle) ){ // skip dot files if( $f{0} === '.' ){ continue; } $i = strpos( $f, ".$ext" ); if( $i ){ // file has correct extension if( substr($f,0,2) === '__' ){ // skip file name starting "__" continue; } $cname = substr_replace( $f, '', $i ); $incs[$cname] = "$dpath/$f"; } } closedir($dhandle); break; default: // assume single file exists with expected extension $path = "$dpath/$cname.$ext"; if( !$silent && !self::check_file($path) ){ break; } $incs[$cname] = $path; } // cache for next time self::$dircache[$cachekey] = $incs; return $incs; }
php
{ "resource": "" }
q5468
PLUGTool.collect_files
train
static function collect_files( $dpath, $r = false, $match = null, $ignore = null ){ $paths = array(); $dhandle = opendir( $dpath ); while( $f = readdir($dhandle) ){ if( $f === '.' || $f === '..' ){ continue; } // pattern tested only on file name // ignore pattern applies to directories as well as files if( isset($ignore) && preg_match($ignore, $f) ){ continue; } $path = $dpath.'/'.$f; if( is_dir($path) ){ if( $r ){ $paths = array_merge( $paths, self::collect_files($path, true, $match, $ignore) ); } } // test match requirement on files only else if( isset($match) && ! preg_match($match, $f) ){ continue; } // else file ok to collect else { $paths[] = $path; } } closedir($dhandle); return $paths; }
php
{ "resource": "" }
q5469
PLUGTool.check_file
train
static function check_file( $path, $w = false, $isdir = false ){ $strtype = $isdir ? 'Directory' : 'File'; if( !file_exists($path) ){ trigger_error("$strtype not found; `$path'", E_USER_NOTICE ); return false; } if( $isdir && !is_dir($path) ){ trigger_error("Not a directory; `$path'", E_USER_NOTICE ); return false; } if( !$isdir && !is_file($path) ){ trigger_error("Not a file; `$path'", E_USER_NOTICE ); return false; } if( !is_readable($path) ){ trigger_error("$strtype not readable by `".trim(`whoami`)."'; `$path'", E_USER_NOTICE ); return false; } if( $w && !is_writeable($path) ){ trigger_error("$strtype not writeable by `".trim(`whoami`)."'; `$path'", E_USER_NOTICE ); return false; } return true; }
php
{ "resource": "" }
q5470
PLUGTool.map_deployment_virtual
train
static function map_deployment_virtual( $path ){ // if path is outside document root move to special plug include dir if( strpos( $path, PLUG_VIRTUAL_DIR ) !== 0 ){ if( strpos( $path, PLUG_HOST_DIR ) === 0 ){ // is under host root $len = strlen(PLUG_HOST_DIR) + 1; $subpath = substr_replace( $path, '', 0, $len ); } else{ // else could be anywhere in filesystem $subpath = md5( dirname($path) ).'/'.basename($path); } return '/plug/inc/'.$subpath; } // else just remove document root return str_replace( PLUG_VIRTUAL_DIR, '', $path ); }
php
{ "resource": "" }
q5471
AttributeValueRelationModel.getRelationFiles
train
public function getRelationFiles() { $filesByObject = new \Mmi\Orm\RecordCollection; //wyszukiwanie wartości foreach ($this->getAttributeValues() as $record) { //pobieranie klucza atrybutu (w celu zgrupowania) if ($record->getJoined('cms_attribute_type')->uploader) { //dołączanie plików foreach (\Cms\Orm\CmsFileQuery::byObject($record->value, $this->_objectId)->find() as $file) { $filesByObject->append($file); } } } return $filesByObject; }
php
{ "resource": "" }
q5472
ExportResponse.setCsv
train
public function setCsv(array &$data, $detectHead = true) { $handle = self::createMemoryHandle(); if($detectHead && count($data)> 0){ fputcsv($handle, array_keys($data[0]), $this->delimiter, $this->enclosure); } foreach ($data as $row) { fputcsv($handle, $row, $this->delimiter, $this->enclosure); } rewind($handle); $output = chr(255) . chr(254 ) . mb_convert_encoding('sep=' . $this->delimiter . "\n" . stream_get_contents($handle), self::UTF_16_LE, $this->encodingFrom ); $this->setData($output); fclose($handle); }
php
{ "resource": "" }
q5473
ExportResponse.setType
train
public function setType($type) { switch ($type) { case self::TYPE_CSV: $this->headers->add(array('Content-Type' => 'text/csv;charset=' . self::UTF_16_LE)); break; case self::TYPE_XLS: $this->headers->add(array("Content-Type" => "application/vnd.ms-excel")); break; } $this->type = $type; }
php
{ "resource": "" }
q5474
ExportResponse.setFileName
train
public function setFileName($fileName) { $this->fileName = $fileName; $this->headers->add(array('Content-Disposition' => 'attachment; filename="' . $this->fileName . '"')); return $this; }
php
{ "resource": "" }
q5475
BNFRulesNode.collect_symbols
train
function collect_symbols(){ if( ! $this->length ){ return null; } $Rule = $this->reset(); do { if( $Rule->length !== 6 ){ // empty rule most likely continue; } // collect rule name - guaranteed to be nontermainal $Name = $Rule->get_child( 1 ); $n = $Name->evaluate(); $nts[ $n ] = $n; // assume first nt is start symbol if( is_null( $this->startsymbol ) ){ $this->startsymbol = $n; } $Expr = $Rule->get_child( 4 ); // lists in Expression $List = $Expr->reset(); do { // terms in list - may be terminal or nonterminal $Term = $List->reset(); do { $s = $Term->evaluate(); switch( $Term->length ){ case 1: // "terminal" or terminal if( $s === P_EPSILON || $s === P_EOF ){ // mandatory symbols already known break; } $ts[ $s ] = (string) $Term; break; case 3: // angle-bracketed <nonterminal> $nts[ $s ] = (string) $Term; break; } } while( $Term = $List->next() ); } while( $Expr->next() && $List = $Expr->next() ); } while( $Rule = $this->next() ); return array( $ts, $nts ); }
php
{ "resource": "" }
q5476
BNFRulesNode.make_lex
train
function make_lex( $i = 0 ){ $Lex = new LexBuilder( $i ); foreach( $this->collect_symbols() as $symbols ){ foreach( $symbols as $t => $s ){ if( preg_match('/^\W/', $s, $r ) ){ $Lex->define_literal( (string) $t ); } else if( $Lex->defined($s) ){ } else if( defined($s) ){ $Lex->redefine( $s ); } else { $Lex->define( $t ); } } } return $Lex; }
php
{ "resource": "" }
q5477
View.setVar
train
public function setVar($name, $value) { $context = $this->_context; $context->vars[$name] = $value; return $this; }
php
{ "resource": "" }
q5478
View.setVars
train
public function setVars($vars) { $context = $this->_context; $context->vars = array_merge($context->vars, $vars); return $this; }
php
{ "resource": "" }
q5479
View.getVar
train
public function getVar($name = null) { $context = $this->_context; if ($name === null) { return $context->vars; } else { return isset($context->vars[$name]) ? $context->vars[$name] : null; } }
php
{ "resource": "" }
q5480
View.render
train
public function render($template = null, $vars = null) { $context = $this->_context; if ($vars !== null) { $context->vars = $vars; } if (!$template) { $area = $this->dispatcher->getArea(); $controller = $this->dispatcher->getController(); if ($area) { $dir = "@app/Areas/$area/Views/$controller"; } else { $dir = "@views/$controller"; } if (!isset($this->_dirs[$dir])) { $this->_dirs[$dir] = $this->filesystem->dirExists($dir); } if ($this->_dirs[$dir]) { $template = $dir . '/' . ucfirst($this->dispatcher->getAction()); } else { $template = $dir; } } $this->eventsManager->fireEvent('view:beforeRender', $this); $context->content = $this->_render($template, $context->vars, false); if ($context->layout !== false) { $layout = $this->_findLayout(); $context->content = $this->_render($layout, $context->vars, false); } $this->eventsManager->fireEvent('view:afterRender', $this); return $context->content; }
php
{ "resource": "" }
q5481
JbConfigKnpMenuExtension.parseFile
train
public function parseFile($file) { $bundleConfig = Yaml::parse(file_get_contents(realpath($file))); if (!is_array($bundleConfig)) { return array(); } return $bundleConfig; }
php
{ "resource": "" }
q5482
GeneratorFinderFactory.getInstance
train
public static function getInstance() { return new GeneratorFinderCache( new GeneratorFinder( TranstyperFactory::getInstance(), GeneratorValidatorFactory::getInstance(), new FileManager() ), Installer::getDirectories(), new FileManager() ); }
php
{ "resource": "" }
q5483
Route._compilePattern
train
protected function _compilePattern($pattern) { if (strpos($pattern, '{') !== false) { $tr = [ '{area}' => '{area:[a-z]\w*}', '{controller}' => '{controller:[a-z]\w*}', '{action}' => '{action:[a-z]\w*}', '{params}' => '{params:.*}', '{id}' => '{id:[^/]+}', ':int' => ':\d+', ]; $pattern = strtr($pattern, $tr); } if (strpos($pattern, '{') !== false) { $need_restore_token = false; if (preg_match('#{\d#', $pattern) === 1) { $need_restore_token = true; $pattern = (string)preg_replace('#{([\d,]+)}#', '@\1@', $pattern); } $matches = []; if (preg_match_all('#{([A-Z].*)}#Ui', $pattern, $matches, PREG_SET_ORDER) > 0) { foreach ($matches as $match) { $parts = explode(':', $match[1], 2); $to = '(?<' . $parts[0] . '>' . (isset($parts[1]) ? $parts[1] : '[\w-]+') . ')'; $pattern = (string)str_replace($match[0], $to, $pattern); } } if ($need_restore_token) { $pattern = (string)preg_replace('#@([\d,]+)@#', '{\1}', $pattern); } return '#^' . $pattern . '$#i'; } else { return $pattern; } }
php
{ "resource": "" }
q5484
ClassMetadataPropertiesCacheWarmer.buildCacheData
train
private function buildCacheData() { $metadata = $this->driver->getMetadataForUser(); return serialize( array_map(function (\ReflectionProperty $property) { return $property->getName(); }, $metadata) ); }
php
{ "resource": "" }
q5485
Generator.addBuilder
train
public function addBuilder(BuilderInterface $builder) { $builder->setGenerator($this); $builder->setTemplateDirs($this->templateDirectories); $builder->setMustOverwriteIfExists($this->mustOverwriteIfExists); $builder->setVariables(array_merge($this->variables, $builder->getVariables())); $this->builders[] = $builder; return $builder; }
php
{ "resource": "" }
q5486
TextCat.createLM
train
public function createLM( $text, $maxNgrams ) { $ngram = []; foreach ( preg_split( "/[{$this->wordSeparator}]+/u", $text ) as $word ) { if ( empty( $word ) ) { continue; } $word = "_" . $word . "_"; $len = mb_strlen( $word, "UTF-8" ); for ( $i = 0; $i < $len; $i++ ) { $rlen = $len - $i; if ( $rlen > 4 ) { @$ngram[mb_substr( $word, $i, 5, "UTF-8" )]++; } if ( $rlen > 3 ) { @$ngram[mb_substr( $word, $i, 4, "UTF-8" )]++; } if ( $rlen > 2 ) { @$ngram[mb_substr( $word, $i, 3, "UTF-8" )]++; } if ( $rlen > 1 ) { @$ngram[mb_substr( $word, $i, 2, "UTF-8" )]++; } @$ngram[mb_substr( $word, $i, 1, "UTF-8" )]++; } } if ( $this->minFreq ) { $min = $this->minFreq; $ngram = array_filter( $ngram, function ( $v ) use ( $min ) { return $v > $min; } ); } uksort( $ngram, function ( $k1, $k2 ) use ( $ngram ) { if ( $ngram[$k1] == $ngram[$k2] ) { return strcmp( $k1, $k2 ); } return $ngram[$k2] - $ngram[$k1]; } ); if ( count( $ngram ) > $maxNgrams ) { array_splice( $ngram, $maxNgrams ); } return $ngram; }
php
{ "resource": "" }
q5487
TextCat.writeLanguageFile
train
public function writeLanguageFile( $ngrams, $outfile ) { $out = fopen( $outfile, "w" ); // write original array as "$ngrams" fwrite( $out, '<?php $ngrams = ' . var_export( $ngrams, true ) . ";\n" ); // write reduced array as "$ranks" $rank = 1; $ranks = array_map( function ( $x ) use ( &$rank ) { return $rank++; }, $ngrams ); fwrite( $out, '$ranks = ' . var_export( $ranks, true ) . ";\n" ); fclose( $out ); }
php
{ "resource": "" }
q5488
TextCat.classify
train
public function classify( $text, $candidates = null ) { $results = []; $this->resultStatus = ''; // strip non-word characters before checking for min length, don't assess empty strings $wordLength = mb_strlen( preg_replace( "/[{$this->wordSeparator}]+/", "", $text ) ); if ( $wordLength < $this->minInputLength || $wordLength == 0 ) { $this->resultStatus = self::STATUSTOOSHORT; return $results; } $inputgrams = array_keys( $this->createLM( $text, $this->maxNgrams ) ); if ( $candidates ) { // flip for more efficient lookups $candidates = array_flip( $candidates ); } foreach ( $this->langFiles as $language => $langFile ) { if ( $candidates && !isset( $candidates[$language] ) ) { continue; } $ngrams = $this->loadLanguageFile( $langFile ); $p = 0; foreach ( $inputgrams as $i => $ingram ) { if ( !empty( $ngrams[$ingram] ) ) { $p += abs( $ngrams[$ingram] - $i ); } else { $p += $this->maxNgrams; } } if ( isset( $this->boostedLangs[$language] ) ) { $p = round( $p * ( 1 - $this->langBoostScore ) ); } $results[$language] = $p; } asort( $results ); // ignore any item that scores higher than best * resultsRatio $max = reset( $results ) * $this->resultsRatio; $results = array_filter( $results, function ( $res ) use ( $max ) { return $res <= $max; } ); // if more than maxReturnedLanguages remain, the result is too ambiguous, so bail if ( count( $results ) > $this->maxReturnedLanguages ) { $this->resultStatus = self::STATUSAMBIGUOUS; return []; } // filter max proportion of max score after ambiguity check; reuse $max variable $max = count( $inputgrams ) * $this->maxNgrams * $this->maxProportion; $results = array_filter( $results, function ( $res ) use ( $max ) { return $res <= $max; } ); if ( count( $results ) == 0 ) { $this->resultStatus = self::STATUSNOMATCH; return $results; } return $results; }
php
{ "resource": "" }
q5489
AuthenticationPostListener.findAccessToken
train
private function findAccessToken(array $identity) { $config = $this->container->get('config'); foreach ($config['zf-oauth2-doctrine'] as $oauth2Config) { if (array_key_exists('object_manager', $oauth2Config)) { $objectManager = $this->container->get($oauth2Config['object_manager']); $accessTokenRepository = $objectManager ->getRepository($oauth2Config['mapping']['AccessToken']['entity']); $accessToken = $accessTokenRepository->findOneBy([ $oauth2Config['mapping']['AccessToken']['mapping']['access_token']['name'] => array_key_exists('access_token', $identity) ? $identity['access_token'] : $identity['id'], ]); if ($accessToken) { if ($accessToken->getClient()->getClientId() == $identity['client_id']) { // Match found return $accessToken; } } } } }
php
{ "resource": "" }
q5490
ProductControllerFeaturesExtension.GroupedFeatures
train
public function GroupedFeatures($showungrouped = false) { $features = $this->owner->Features() ->innerJoin("Feature","Feature.ID = ProductFeatureValue.FeatureID"); //figure out feature groups $groupids = FeatureGroup::get() ->innerJoin("Feature","Feature.GroupID = FeatureGroup.ID") ->innerJoin("ProductFeatureValue","Feature.ID = ProductFeatureValue.FeatureID") ->filter("ProductID",$this->owner->ID) ->getIDList(); //pack existin features into seperate lists $result = new ArrayList(); foreach($groupids as $groupid) { $group = FeatureGroup::get()->byID($groupid); $result->push(new ArrayData(array( 'Group' => $group, 'Children' => $features->filter("GroupID", $groupid) ))); } $ungrouped = $features->filter("GroupID:not", $groupids); if ($ungrouped->exists() && $showungrouped) { $result->push(new ArrayData(array( 'Children' => $ungrouped ))); } return $result; }
php
{ "resource": "" }
q5491
BNFParser.parse_string
train
static function parse_string( $s ){ if( $s == '' ){ throw new Exception('Cannot parse empty string'); } // instantiate self $Parser = new BNFParser; // perform external tokenizing on string input $tokens = bnf_tokenize( $s ); return $Parser->parse( $tokens ); }
php
{ "resource": "" }
q5492
BNFParser.parse_file
train
static function parse_file( $f ){ $src = file_get_contents( $f, true ); if( $src === false ){ throw new Exception("Cannot read file $f"); } return self::parse_string( $src ); }
php
{ "resource": "" }
q5493
Db.fetchOne
train
public function fetchOne($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false) { return ($rs = $this->fetchAll($sql, $bind, $fetchMode, $useMaster)) ? $rs[0] : false; }
php
{ "resource": "" }
q5494
Db.fetchAll
train
public function fetchAll($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false) { $context = $this->_context; $context->sql = $sql; $context->bind = $bind; $context->affected_rows = 0; $this->eventsManager->fireEvent('db:beforeQuery', $this); if ($context->connection) { $type = null; $connection = $context->connection; } else { $type = $this->_has_slave ? 'slave' : 'default'; $connection = $this->poolManager->pop($this, $this->_timeout, $type); } try { $start_time = microtime(true); $result = $connection->query($sql, $bind, $fetchMode, $useMaster); $elapsed = round(microtime(true) - $start_time, 3); } finally { if ($type) { $this->poolManager->push($this, $connection, $type); } } $count = $context->affected_rows = count($result); $event_data = compact('elapsed', 'count', 'sql', 'bind', 'result'); $this->logger->debug($event_data, 'db.query'); $this->eventsManager->fireEvent('db:afterQuery', $this, $event_data); return $result; }
php
{ "resource": "" }
q5495
Db.delete
train
public function delete($table, $conditions, $bind = []) { if (is_string($conditions)) { $conditions = [$conditions]; } $wheres = []; /** @noinspection ForeachSourceInspection */ foreach ($conditions as $k => $v) { if (is_int($k)) { $wheres[] = stripos($v, ' or ') ? "($v)" : $v; } else { $wheres[] = "[$k]=:$k"; $bind[$k] = $v; } } $sql = 'DELETE' . ' FROM ' . $this->_escapeIdentifier($table) . ' WHERE ' . implode(' AND ', $wheres); return $this->_execute('delete', $sql, $bind); }
php
{ "resource": "" }
q5496
Db.getEmulatedSQL
train
public function getEmulatedSQL($preservedStrLength = -1) { $context = $this->_context; if (!$context->bind) { return (string)$context->sql; } $bind = $context->bind; if (isset($bind[0])) { return (string)$context->sql; } else { $replaces = []; foreach ($bind as $key => $value) { $replaces[':' . $key] = $this->_parseBindValue($value, $preservedStrLength); } return strtr($context->sql, $replaces); } }
php
{ "resource": "" }
q5497
Db.begin
train
public function begin() { $context = $this->_context; $this->logger->info('transaction begin', 'db.transaction.begin'); if ($context->transaction_level === 0) { $this->eventsManager->fireEvent('db:beginTransaction', $this); try { $connection = $this->poolManager->pop($this, $this->_timeout); if (!$connection->beginTransaction()) { throw new DbException('beginTransaction failed.'); } $context->connection = $connection; } catch (\PDOException $exception) { throw new DbException('beginTransaction failed: ' . $exception->getMessage(), $exception->getCode(), $exception); } finally { if (!$context->connection) { $this->poolManager->push($this, $context); } } } $context->transaction_level++; }
php
{ "resource": "" }
q5498
Db.rollback
train
public function rollback() { $context = $this->_context; if ($context->transaction_level > 0) { $this->logger->info('transaction rollback', 'db.transaction.rollback'); $context->transaction_level--; if ($context->transaction_level === 0) { $this->eventsManager->fireEvent('db:rollbackTransaction', $this); try { if (!$context->connection->rollBack()) { throw new DbException('rollBack failed.'); } } catch (\PDOException $exception) { throw new DbException('rollBack failed: ' . $exception->getMessage(), $exception->getCode(), $exception); } finally { $this->poolManager->push($this, $context->connection); $context->connection = null; } } } }
php
{ "resource": "" }
q5499
CategoryModel.getCategoryTree
train
public function getCategoryTree($parentCategoryId = null) { //brak zdefiniowanej kategorii if ($parentCategoryId === null) { return $this->_categoryTree; } //wyszukiwanie kategorii return $this->_searchChildren($this->_categoryTree, $parentCategoryId); }
php
{ "resource": "" }