_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16200 | WriteBatch.validatePrecondition | train | private function validatePrecondition(array &$options)
{
$precondition = isset($options['precondition'])
? $options['precondition']
: null;
if (!$precondition) {
return;
}
if (isset($precondition['exists'])) {
return $precondition;
}
if (isset($precondition['updateTime'])) {
if (!($precondition['updateTime'] instanceof Timestamp)) {
throw new \InvalidArgumentException(
'Precondition Update Time must be an instance of `Google\\Cloud\\Core\\Timestamp`'
);
}
return [
'updateTime' => $precondition['updateTime']->formatForApi()
];
}
throw new \InvalidArgumentException('Preconditions must provide either `exists` or `updateTime`.');
} | php | {
"resource": ""
} |
q16201 | WriteBatch.createDatabaseWriteOperation | train | private function createDatabaseWriteOperation($type, $document, array $options = [])
{
switch ($type) {
case self::TYPE_UPDATE:
return [
'update' => [
'name' => $document,
'fields' => $this->pluck('fields', $options)
]
];
break;
case self::TYPE_DELETE:
return ['delete' => $document];
break;
case self::TYPE_TRANSFORM:
return [
'transform' => [
'document' => $document,
'fieldTransforms' => $this->pluck('fieldTransforms', $options)
]
];
break;
// @codeCoverageIgnoreStart
default:
throw new \InvalidArgumentException(sprintf(
'Write operation type `%s is not valid. Allowed values are update, delete, verify, transform.',
$type
));
break;
// @codeCoverageIgnoreEnd
}
} | php | {
"resource": ""
} |
q16202 | WriteBatch.formatPrecondition | train | private function formatPrecondition(array $options, $mustExist = false)
{
if (!isset($options['precondition']) && !$mustExist) {
return $options;
}
$precondition = isset($options['precondition'])
? $options['precondition']
: [];
if (isset($precondition['updateTime'])) {
return $options;
}
if ($mustExist) {
$precondition['exists'] = true;
}
$options['precondition'] = $precondition;
return $options;
} | php | {
"resource": ""
} |
q16203 | WriteBatch.checkPrefixes | train | private function checkPrefixes(array $paths)
{
sort($paths);
for ($i = 1; $i < count($paths); $i++) {
$prefix = $paths[$i-1];
$suffix = $paths[$i];
$prefix = explode('.', $prefix);
$suffix = explode('.', $suffix);
$isPrefix = count($prefix) < count($suffix)
&& $prefix === array_slice($suffix, 0, count($prefix));
if ($isPrefix) {
throw new \InvalidArgumentException(sprintf(
'Field path conflict detected for field path `%s`. ' .
'Conflicts occur when a field path descends from another ' .
'path. For instance `a.b` is not allowed when `a` is also ' .
'provided.',
$prefix
));
}
}
} | php | {
"resource": ""
} |
q16204 | NetworkPolicy.setProvider | train | public function setProvider($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Container\V1\NetworkPolicy_Provider::class);
$this->provider = $var;
return $this;
} | php | {
"resource": ""
} |
q16205 | CreateNotificationChannelRequest.setNotificationChannel | train | public function setNotificationChannel($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\NotificationChannel::class);
$this->notification_channel = $var;
return $this;
} | php | {
"resource": ""
} |
q16206 | UnaryFilter.setOp | train | public function setOp($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Firestore\V1\StructuredQuery_UnaryFilter_Operator::class);
$this->op = $var;
return $this;
} | php | {
"resource": ""
} |
q16207 | ListInspectTemplatesResponse.setInspectTemplates | train | public function setInspectTemplates($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dlp\V2\InspectTemplate::class);
$this->inspect_templates = $arr;
return $this;
} | php | {
"resource": ""
} |
q16208 | SetMasterAuthRequest.setAction | train | public function setAction($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Container\V1\SetMasterAuthRequest_Action::class);
$this->action = $var;
return $this;
} | php | {
"resource": ""
} |
q16209 | SetMasterAuthRequest.setUpdate | train | public function setUpdate($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Container\V1\MasterAuth::class);
$this->update = $var;
return $this;
} | php | {
"resource": ""
} |
q16210 | EducationRecord.setStructuredDegree | train | public function setStructuredDegree($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Talent\V4beta1\Degree::class);
$this->writeOneof(7, $var);
return $this;
} | php | {
"resource": ""
} |
q16211 | Variable.setMembers | train | public function setMembers($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Debugger\V2\Variable::class);
$this->members = $arr;
return $this;
} | php | {
"resource": ""
} |
q16212 | Intent.setWebhookState | train | public function setWebhookState($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Dialogflow\V2\Intent_WebhookState::class);
$this->webhook_state = $var;
return $this;
} | php | {
"resource": ""
} |
q16213 | Intent.setEvents | train | public function setEvents($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
$this->events = $arr;
return $this;
} | php | {
"resource": ""
} |
q16214 | Intent.setTrainingPhrases | train | public function setTrainingPhrases($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase::class);
$this->training_phrases = $arr;
return $this;
} | php | {
"resource": ""
} |
q16215 | Intent.setMessages | train | public function setMessages($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dialogflow\V2\Intent\Message::class);
$this->messages = $arr;
return $this;
} | php | {
"resource": ""
} |
q16216 | Intent.setFollowupIntentInfo | train | public function setFollowupIntentInfo($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dialogflow\V2\Intent\FollowupIntentInfo::class);
$this->followup_intent_info = $arr;
return $this;
} | php | {
"resource": ""
} |
q16217 | InsertResponse.failedRows | train | public function failedRows()
{
$rows = [];
if ($this->isSuccessful()) {
return $rows;
}
foreach ($this->info['insertErrors'] as $error) {
$rows[] = $error + [
'rowData' => $this->rows[$error['index']]['json']
];
}
return $rows;
} | php | {
"resource": ""
} |
q16218 | ListDlpJobsResponse.setJobs | train | public function setJobs($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dlp\V2\DlpJob::class);
$this->jobs = $arr;
return $this;
} | php | {
"resource": ""
} |
q16219 | RecordKey.setIdValues | train | public function setIdValues($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
$this->id_values = $arr;
return $this;
} | php | {
"resource": ""
} |
q16220 | BigtableClient.table | train | public function table($instanceId, $tableId, array $options = [])
{
return new Table(
$this->gapicClient,
GapicClient::tableName($this->projectId, $instanceId, $tableId),
$options
);
} | php | {
"resource": ""
} |
q16221 | ErrorGroupServiceGrpcClient.UpdateGroup | train | public function UpdateGroup(\Google\Cloud\ErrorReporting\V1beta1\UpdateGroupRequest $argument,
$metadata = [], $options = []) {
return $this->_simpleRequest('/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/UpdateGroup',
$argument,
['\Google\Cloud\ErrorReporting\V1beta1\ErrorGroup', 'decode'],
$metadata, $options);
} | php | {
"resource": ""
} |
q16222 | Family.setColumns | train | public function setColumns($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Bigtable\V2\Column::class);
$this->columns = $arr;
return $this;
} | php | {
"resource": ""
} |
q16223 | ClusterOperationMetadata.setWarnings | train | public function setWarnings($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
$this->warnings = $arr;
return $this;
} | php | {
"resource": ""
} |
q16224 | RequestMetadata.setDeviceInfo | train | public function setDeviceInfo($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Talent\V4beta1\DeviceInfo::class);
$this->device_info = $var;
return $this;
} | php | {
"resource": ""
} |
q16225 | ListSubscriptionsResponse.setSubscriptions | train | public function setSubscriptions($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\PubSub\V1\Subscription::class);
$this->subscriptions = $arr;
return $this;
} | php | {
"resource": ""
} |
q16226 | ListGroupStatsResponse.setErrorGroupStats | train | public function setErrorGroupStats($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\ErrorReporting\V1beta1\ErrorGroupStats::class);
$this->error_group_stats = $arr;
return $this;
} | php | {
"resource": ""
} |
q16227 | Mutation.setSetCell | train | public function setSetCell($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\Mutation_SetCell::class);
$this->writeOneof(1, $var);
return $this;
} | php | {
"resource": ""
} |
q16228 | Mutation.setDeleteFromColumn | train | public function setDeleteFromColumn($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\Mutation_DeleteFromColumn::class);
$this->writeOneof(2, $var);
return $this;
} | php | {
"resource": ""
} |
q16229 | Mutation.setDeleteFromFamily | train | public function setDeleteFromFamily($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\Mutation_DeleteFromFamily::class);
$this->writeOneof(3, $var);
return $this;
} | php | {
"resource": ""
} |
q16230 | Mutation.setDeleteFromRow | train | public function setDeleteFromRow($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\Mutation_DeleteFromRow::class);
$this->writeOneof(4, $var);
return $this;
} | php | {
"resource": ""
} |
q16231 | Annotation.setDescription | train | public function setDescription($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Trace\V2\TruncatableString::class);
$this->description = $var;
return $this;
} | php | {
"resource": ""
} |
q16232 | Error.setTimestamps | train | public function setTimestamps($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Timestamp::class);
$this->timestamps = $arr;
return $this;
} | php | {
"resource": ""
} |
q16233 | EmulatorTrait.emulatorGapicConfig | train | private function emulatorGapicConfig($emulatorHost)
{
// Strip the URL scheme from the input, if it was provided.
if ($scheme = parse_url($emulatorHost, PHP_URL_SCHEME)) {
$search = $scheme . '://';
$emulatorHost = str_replace($search, '', $emulatorHost);
}
return [
'serviceAddress' => $emulatorHost,
'transportConfig' => [
'grpc' => [
'stubOpts' => [
'credentials' => \Grpc\ChannelCredentials::createInsecure()
]
]
]
];
} | php | {
"resource": ""
} |
q16234 | EmulatorTrait.emulatorBaseUri | train | private function emulatorBaseUri($emulatorHost)
{
$emulatorUriComponents = parse_url($emulatorHost);
$emulatorUriComponents = array_merge(['scheme' => 'http', 'port' => ''], $emulatorUriComponents);
$baseUri = "{$emulatorUriComponents['scheme']}://{$emulatorUriComponents['host']}";
$baseUri .= $emulatorUriComponents['port'] ? ":{$emulatorUriComponents['port']}/" : '/';
return $baseUri;
} | php | {
"resource": ""
} |
q16235 | EmulatorTrait.getEmulatorBaseUri | train | public function getEmulatorBaseUri($baseUri, $emulatorHost = null)
{
if ($emulatorHost) {
$baseUri = $this->emulatorBaseUri($emulatorHost);
}
return $baseUri;
} | php | {
"resource": ""
} |
q16236 | ImportSshPublicKeyResponse.setLoginProfile | train | public function setLoginProfile($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\OsLogin\V1\LoginProfile::class);
$this->login_profile = $var;
return $this;
} | php | {
"resource": ""
} |
q16237 | BatchSnapshot.executePartition | train | public function executePartition(PartitionInterface $partition, array $options = [])
{
if ($partition instanceof QueryPartition) {
return $this->executeQuery($partition);
} elseif ($partition instanceof ReadPartition) {
return $this->executeRead($partition);
}
throw new \BadMethodCallException('Unsupported partition type.');
} | php | {
"resource": ""
} |
q16238 | BatchSnapshot.serialize | train | public function serialize()
{
return base64_encode(json_encode([
'sessionName' => $this->session->name(),
'transactionId' => $this->transactionId,
'readTimestamp' => $this->readTimestamp->formatAsString()
]));
} | php | {
"resource": ""
} |
q16239 | BatchSnapshot.executeQuery | train | private function executeQuery(QueryPartition $partition)
{
return $this->execute($partition->sql(), [
'partitionToken' => $partition->token()
] + $partition->options());
} | php | {
"resource": ""
} |
q16240 | BatchSnapshot.executeRead | train | private function executeRead(ReadPartition $partition)
{
return $this->read($partition->table(), $partition->keySet(), $partition->columns(), [
'partitionToken' => $partition->token()
] + $partition->options());
} | php | {
"resource": ""
} |
q16241 | CreateClusterRequest.setCluster | train | public function setCluster($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1beta2\Cluster::class);
$this->cluster = $var;
return $this;
} | php | {
"resource": ""
} |
q16242 | UpdateTopicRequest.setTopic | train | public function setTopic($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\PubSub\V1\Topic::class);
$this->topic = $var;
return $this;
} | php | {
"resource": ""
} |
q16243 | CloudTasksGapicClient.queueName | train | public static function queueName($project, $location, $queue)
{
return self::getQueueNameTemplate()->render([
'project' => $project,
'location' => $location,
'queue' => $queue,
]);
} | php | {
"resource": ""
} |
q16244 | CloudTasksGapicClient.taskName | train | public static function taskName($project, $location, $queue, $task)
{
return self::getTaskNameTemplate()->render([
'project' => $project,
'location' => $location,
'queue' => $queue,
'task' => $task,
]);
} | php | {
"resource": ""
} |
q16245 | OrderedJob.setHadoopJob | train | public function setHadoopJob($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1\HadoopJob::class);
$this->writeOneof(2, $var);
return $this;
} | php | {
"resource": ""
} |
q16246 | OrderedJob.setSparkJob | train | public function setSparkJob($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1\SparkJob::class);
$this->writeOneof(3, $var);
return $this;
} | php | {
"resource": ""
} |
q16247 | Bucket.setMin | train | public function setMin($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\Value::class);
$this->min = $var;
return $this;
} | php | {
"resource": ""
} |
q16248 | Bucket.setMax | train | public function setMax($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\Value::class);
$this->max = $var;
return $this;
} | php | {
"resource": ""
} |
q16249 | Bucket.setReplacementValue | train | public function setReplacementValue($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\Value::class);
$this->replacement_value = $var;
return $this;
} | php | {
"resource": ""
} |
q16250 | DeviceInfo.setDeviceType | train | public function setDeviceType($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Talent\V4beta1\DeviceInfo_DeviceType::class);
$this->device_type = $var;
return $this;
} | php | {
"resource": ""
} |
q16251 | BigtableTableAdminGapicClient.snapshotName | train | public static function snapshotName($project, $instance, $cluster, $snapshot)
{
return self::getSnapshotNameTemplate()->render([
'project' => $project,
'instance' => $instance,
'cluster' => $cluster,
'snapshot' => $snapshot,
]);
} | php | {
"resource": ""
} |
q16252 | RequestedOptions.setSnapshotInspectTemplate | train | public function setSnapshotInspectTemplate($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\InspectTemplate::class);
$this->snapshot_inspect_template = $var;
return $this;
} | php | {
"resource": ""
} |
q16253 | AudioConfig.setAudioEncoding | train | public function setAudioEncoding($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\TextToSpeech\V1\AudioEncoding::class);
$this->audio_encoding = $var;
return $this;
} | php | {
"resource": ""
} |
q16254 | Row.setFamilies | train | public function setFamilies($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Bigtable\V2\Family::class);
$this->families = $arr;
return $this;
} | php | {
"resource": ""
} |
q16255 | OperationResponseTrait.operationToArray | train | private function operationToArray($operation, $serializer, array $lroMappers)
{
$response = $operation->getLastProtoResponse();
if (is_null($response)) {
return null;
}
$response = $serializer->encodeMessage($response);
$result = null;
if ($operation->isDone()) {
$type = $response['metadata']['typeUrl'];
$result = $this->deserializeResult($operation, $type, $serializer, $lroMappers);
}
$error = $operation->getError();
if (!is_null($error)) {
$error = $serializer->encodeMessage($error);
}
$response['response'] = $result;
$response['error'] = $error;
return $response;
} | php | {
"resource": ""
} |
q16256 | OperationResponseTrait.deserializeResult | train | private function deserializeResult($operation, $type, $serializer, array $mappers)
{
$mappers = array_filter($mappers, function ($mapper) use ($type) {
return $mapper['typeUrl'] === $type;
});
if (count($mappers) === 0) {
throw new \RuntimeException(sprintf('No mapper exists for operation response type %s.', $type));
}
$mapper = current($mappers);
$message = $mapper['message'];
$response = new $message();
$anyResponse = $operation->getLastProtoResponse()->getResponse();
if (is_null($anyResponse)) {
return null;
}
$response->mergeFromString($anyResponse->getValue());
return $serializer->encodeMessage($response);
} | php | {
"resource": ""
} |
q16257 | CurlPost.submit | train | public function submit(RequestParameters $params)
{
$handle = $this->curl->init($this->siteVerifyUrl);
$options = array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params->toQueryString(),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded'
),
CURLINFO_HEADER_OUT => false,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true
);
$this->curl->setoptArray($handle, $options);
$response = $this->curl->exec($handle);
$this->curl->close($handle);
if ($response !== false) {
return $response;
}
return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}';
} | php | {
"resource": ""
} |
q16258 | ReCaptcha.verify | train | public function verify($response, $remoteIp = null)
{
// Discard empty solution submissions
if (empty($response)) {
$recaptchaResponse = new Response(false, array(self::E_MISSING_INPUT_RESPONSE));
return $recaptchaResponse;
}
$params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION);
$rawResponse = $this->requestMethod->submit($params);
$initialResponse = Response::fromJson($rawResponse);
$validationErrors = array();
if (isset($this->hostname) && strcasecmp($this->hostname, $initialResponse->getHostname()) !== 0) {
$validationErrors[] = self::E_HOSTNAME_MISMATCH;
}
if (isset($this->apkPackageName) && strcasecmp($this->apkPackageName, $initialResponse->getApkPackageName()) !== 0) {
$validationErrors[] = self::E_APK_PACKAGE_NAME_MISMATCH;
}
if (isset($this->action) && strcasecmp($this->action, $initialResponse->getAction()) !== 0) {
$validationErrors[] = self::E_ACTION_MISMATCH;
}
if (isset($this->threshold) && $this->threshold > $initialResponse->getScore()) {
$validationErrors[] = self::E_SCORE_THRESHOLD_NOT_MET;
}
if (isset($this->timeoutSeconds)) {
$challengeTs = strtotime($initialResponse->getChallengeTs());
if ($challengeTs > 0 && time() - $challengeTs > $this->timeoutSeconds) {
$validationErrors[] = self::E_CHALLENGE_TIMEOUT;
}
}
if (empty($validationErrors)) {
return $initialResponse;
}
return new Response(
false,
array_merge($initialResponse->getErrorCodes(), $validationErrors),
$initialResponse->getHostname(),
$initialResponse->getChallengeTs(),
$initialResponse->getApkPackageName(),
$initialResponse->getScore(),
$initialResponse->getAction()
);
} | php | {
"resource": ""
} |
q16259 | MakeCommand.createSettingsFile | train | protected function createSettingsFile($format, $options)
{
$SettingsClass = ($format === 'json') ? JsonSettings::class : YamlSettings::class;
$filename = $this->exampleSettingsExists($format) ?
"{$this->basePath}/Homestead.{$format}.example" :
__DIR__."/../resources/Homestead.{$format}";
$settings = $SettingsClass::fromFile($filename);
if (! $this->exampleSettingsExists($format)) {
$settings->updateName($options['name'])
->updateHostname($options['hostname']);
}
$settings->updateIpAddress($options['ip'])
->configureSites($this->projectName, $this->defaultProjectName)
->configureSharedFolders($this->basePath, $this->defaultProjectName)
->save("{$this->basePath}/Homestead.{$format}");
} | php | {
"resource": ""
} |
q16260 | HomesteadSettings.update | train | public function update($attributes)
{
$this->attributes = array_merge($this->attributes, array_filter($attributes, function ($attribute) {
return ! is_null($attribute);
}));
return $this;
} | php | {
"resource": ""
} |
q16261 | HomesteadSettings.configureSites | train | public function configureSites($projectName, $projectDirectory)
{
$sites = [
[
'map' => "{$projectName}.test",
'to' => "/home/vagrant/{$projectDirectory}/public",
],
];
if (isset($this->attributes['sites']) && ! empty($this->attributes['sites'])) {
foreach ($this->attributes['sites'] as $index => $user_site) {
if (isset($user_site['map'])) {
$sites[$index]['map'] = $user_site['map'];
}
if (isset($user_site['to'])) {
$sites[$index]['to'] = $user_site['to'];
}
if (isset($user_site['type'])) {
$sites[$index]['type'] = $user_site['type'];
}
if (isset($user_site['schedule'])) {
$sites[$index]['schedule'] = $user_site['schedule'];
}
if (isset($user_site['php'])) {
$sites[$index]['php'] = $user_site['php'];
}
if (isset($user_site['xhgui'])) {
$sites[$index]['xhgui'] = $user_site['xhgui'];
}
}
}
$this->update(['sites' => $sites]);
return $this;
} | php | {
"resource": ""
} |
q16262 | HomesteadSettings.configureSharedFolders | train | public function configureSharedFolders($projectPath, $projectDirectory)
{
$folders = [
[
'map' => $projectPath,
'to' => "/home/vagrant/{$projectDirectory}",
],
];
if (isset($this->attributes['folders']) && ! empty($this->attributes['folders'])) {
foreach ($this->attributes['folders'] as $index => $user_folder) {
if (isset($user_folder['map']) && empty($folders[$index]['map'])) {
$folders[$index]['map'] = dirname($projectPath).'/'.basename($user_folder['map']);
}
if (isset($user_folder['to'])) {
$folders[$index]['to'] = $user_folder['to'];
}
if (isset($user_folder['type'])) {
$folders[$index]['type'] = $user_folder['type'];
}
}
}
$this->update(['folders' => $folders]);
return $this;
} | php | {
"resource": ""
} |
q16263 | AbstractAnnotation.mergeProperties | train | public function mergeProperties($object)
{
$defaultValues = get_class_vars(get_class($this));
$currentValues = get_object_vars($this);
foreach ($object as $property => $value) {
if ($property === '_context') {
continue;
}
if ($currentValues[$property] === $defaultValues[$property]) { // Overwrite default values
$this->$property = $value;
continue;
}
if ($property === '_unmerged') {
$this->_unmerged = array_merge($this->_unmerged, $value);
continue;
}
if ($currentValues[$property] !== $value) { // New value is not the same?
if ($defaultValues[$property] === $value) { // but is the same as the default?
continue; // Keep current, no notice
}
$identity = method_exists($object, 'identity') ? $object->identity() : get_class($object);
$context1 = $this->_context;
$context2 = property_exists($object, '_context') ? $object->_context : 'unknown';
if (is_object($this->$property) && $this->$property instanceof AbstractAnnotation) {
$context1 = $this->$property->_context;
}
Logger::warning('Multiple definitions for ' . $identity . '->' . $property . "\n Using: " . $context1 . "\n Skipping: " . $context2);
}
}
} | php | {
"resource": ""
} |
q16264 | AbstractAnnotation._validate | train | private static function _validate($fields, $parents, $skip, $baseRef)
{
$valid = true;
$blacklist = [];
if (is_object($fields)) {
if (in_array($fields, $skip, true)) {
return true;
}
$skip[] = $fields;
$blacklist = property_exists($fields, '_blacklist') ? $fields::$_blacklist : [];
}
foreach ($fields as $field => $value) {
if ($value === null || is_scalar($value) || in_array($field, $blacklist)) {
continue;
}
$ref = $baseRef !== '' ? $baseRef.'/'.urlencode((string)$field) : urlencode((string)$field);
if (is_object($value)) {
if (method_exists($value, 'validate')) {
if (!$value->validate($parents, $skip, $ref)) {
$valid = false;
}
} elseif (!self::_validate($value, $parents, $skip, $ref)) {
$valid = false;
}
} elseif (is_array($value) && !self::_validate($value, $parents, $skip, $ref)) {
$valid = false;
}
}
return $valid;
} | php | {
"resource": ""
} |
q16265 | AbstractAnnotation.validateType | train | private function validateType($type, $value): bool
{
if (substr($type, 0, 1) === '[' && substr($type, -1) === ']') { // Array of a specified type?
if ($this->validateType('array', $value) === false) {
return false;
}
$itemType = substr($type, 1, -1);
foreach ($value as $i => $item) {
if ($this->validateType($itemType, $item) === false) {
return false;
}
}
return true;
}
if (is_subclass_of($type, AbstractAnnotation::class)) {
$type = 'object';
}
return $this->validateDefaultTypes($type, $value);
} | php | {
"resource": ""
} |
q16266 | AbstractAnnotation.validateDefaultTypes | train | private function validateDefaultTypes($type, $value): bool
{
switch ($type) {
case 'string':
return is_string($value);
case 'boolean':
return is_bool($value);
case 'integer':
return is_int($value);
case 'number':
return is_numeric($value);
case 'object':
return is_object($value);
case 'array':
return $this->validateArrayType($value);
case 'scheme':
return in_array($value, ['http', 'https', 'ws', 'wss'], true);
default:
throw new Exception('Invalid type "' . $type . '"');
}
} | php | {
"resource": ""
} |
q16267 | AbstractAnnotation.validateArrayType | train | private function validateArrayType($value): bool
{
if (is_array($value) === false) {
return false;
}
$count = 0;
foreach ($value as $i => $item) {
//not a array, but a hash/map
if ($count !== $i) {
return false;
}
$count++;
}
return true;
} | php | {
"resource": ""
} |
q16268 | AbstractAnnotation.nested | train | private function nested($annotation, $nestedContext)
{
if (property_exists($annotation, '_context') && $annotation->_context === $this->_context) {
$annotation->_context = $nestedContext;
}
return $annotation;
} | php | {
"resource": ""
} |
q16269 | InheritProperties.addAllOfProperty | train | private function addAllOfProperty(Schema $childSchema, Schema $parentSchema)
{
$currentSchema = new Schema(['_context' => $childSchema->_context]);
$currentSchema->mergeProperties($childSchema);
$defaultValues = get_class_vars(Schema::class);
foreach (get_object_vars($currentSchema) as $property => $val) {
$childSchema->{$property} = $defaultValues[$property];
}
$childSchema->schema = $currentSchema->schema;
unset($currentSchema->schema);
if ($childSchema->allOf === UNDEFINED) {
$childSchema->allOf = [];
}
$childSchema->allOf[] = new Schema(
[
'_context' => $parentSchema->_context,
'ref' => Components::SCHEMA_REF . $parentSchema->schema
]
);
$childSchema->allOf[] = $currentSchema;
} | php | {
"resource": ""
} |
q16270 | Analyser.fromComment | train | public function fromComment($comment, $context = null)
{
if ($context === null) {
$context = new Context(['comment' => $comment]);
} else {
$context->comment = $comment;
}
try {
self::$context = $context;
if ($context->is('annotations') === false) {
$context->annotations = [];
}
$comment = preg_replace_callback(
'/^[\t ]*\*[\t ]+/m',
function ($match) {
// Replace leading tabs with spaces.
// Workaround for http://www.doctrine-project.org/jira/browse/DCOM-255
return str_replace("\t", ' ', $match[0]);
},
$comment
);
$annotations = $this->docParser->parse($comment, $context);
self::$context = null;
return $annotations;
} catch (Exception $e) {
self::$context = null;
if (preg_match('/^(.+) at position ([0-9]+) in ' . preg_quote((string)$context, '/') . '\.$/', $e->getMessage(), $matches)) {
$errorMessage = $matches[1];
$errorPos = (int)$matches[2];
$atPos = strpos($comment, '@');
$context->line += substr_count($comment, "\n", 0, $atPos + $errorPos);
$lines = explode("\n", substr($comment, $atPos, $errorPos));
$context->character = strlen(array_pop($lines)) + 1; // position starts at 0 character starts at 1
Logger::warning(new Exception($errorMessage . ' in ' . $context, $e->getCode(), $e));
} else {
Logger::warning($e);
}
return [];
}
} | php | {
"resource": ""
} |
q16271 | Serializer.deserialize | train | public function deserialize($jsonString, $className)
{
if (!$this->isValidClassName($className)) {
throw new \Exception($className.' is not defined in OpenApi PHP Annotations');
}
return $this->doDeserialize(json_decode($jsonString), $className);
} | php | {
"resource": ""
} |
q16272 | Serializer.deserializeFile | train | public function deserializeFile($filename, $className = 'OpenApi\Annotations\OpenApi')
{
if (!$this->isValidClassName($className)) {
throw new \Exception($className.' is not defined in OpenApi PHP Annotations');
}
$jsonString = file_get_contents($filename);
return $this->doDeserialize(json_decode($jsonString), $className);
} | php | {
"resource": ""
} |
q16273 | Serializer.doDeserialize | train | private function doDeserialize(\stdClass $c, $class)
{
$annotation = new $class([]);
foreach ($c as $property => $value) {
if ($property === '$ref') {
$property = 'ref';
}
if (substr($property, 0, 2) === 'x-') {
if ($annotation->x === UNDEFINED) {
$annotation->x = [];
}
$custom = substr($property, 2);
$annotation->x[$custom] = $value;
} else {
$annotation->$property = $this->doDeserializeProperty($annotation, $property, $value);
}
}
return $annotation;
} | php | {
"resource": ""
} |
q16274 | Serializer.doDeserializeProperty | train | private function doDeserializeProperty(Annotations\AbstractAnnotation $annotation, $property, $value)
{
// property is primitive type
if (array_key_exists($property, $annotation::$_types)) {
return $this->doDeserializeBaseProperty($annotation::$_types[$property], $value);
}
// property is embedded annotation
foreach ($annotation::$_nested as $class => $declaration) {
// property is an annotation
if (is_string($declaration) && $declaration === $property) {
return $this->doDeserialize($value, $class);
}
// property is an annotation array
if (is_array($declaration) && count($declaration) === 1 && $declaration[0] === $property) {
$annotationArr = [];
foreach ($value as $v) {
$annotationArr[] = $this->doDeserialize($v, $class);
}
return $annotationArr;
}
// property is an annotation hash map
if (is_array($declaration) && count($declaration) === 2 && $declaration[0] === $property) {
$key = $declaration[1];
$annotationHash = [];
foreach ($value as $k => $v) {
$annotation = $this->doDeserialize($v, $class);
$annotation->$key = $k;
$annotationHash[$k] = $annotation;
}
return $annotationHash;
}
}
return $value;
} | php | {
"resource": ""
} |
q16275 | Serializer.doDeserializeBaseProperty | train | private function doDeserializeBaseProperty($type, $value)
{
$isAnnotationClass = is_string($type) && is_subclass_of(trim($type, '[]'), AbstractAnnotation::class);
if ($isAnnotationClass) {
$isArray = strpos($type, '[') === 0 && substr($type, -1) === ']';
if ($isArray) {
$annotationArr = [];
$class = trim($type, '[]');
foreach ($value as $v) {
$annotationArr[] = $this->doDeserialize($v, $class);
}
return $annotationArr;
}
return $this->doDeserialize($value, $type);
}
return $value;
} | php | {
"resource": ""
} |
q16276 | Context.with | train | public function with($property)
{
if (property_exists($this, $property)) {
return $this;
}
if ($this->_parent) {
return $this->_parent->with($property);
}
return false;
} | php | {
"resource": ""
} |
q16277 | Context.getDebugLocation | train | public function getDebugLocation()
{
$location = '';
if ($this->class && ($this->method || $this->property)) {
$location .= $this->fullyQualifiedName($this->class);
if ($this->method) {
$location .= ($this->static ? '::' : '->') . $this->method . '()';
} elseif ($this->property) {
$location .= ($this->static ? '::$' : '->') . $this->property;
}
}
if ($this->filename) {
if ($location !== '') {
$location .= ' in ';
}
$location .= $this->filename;
}
if ($this->line) {
if ($location !== '') {
$location .= ' on';
}
$location .= ' line ' . $this->line;
if ($this->character) {
$location .= ':' . $this->character;
}
}
return $location;
} | php | {
"resource": ""
} |
q16278 | Context.phpdocSummary | train | public function phpdocSummary()
{
$content = $this->phpdocContent();
if (!$content) {
return UNDEFINED;
}
$lines = preg_split('/(\n|\r\n)/', $content);
$summary = '';
foreach ($lines as $line) {
$summary .= $line . "\n";
if ($line === '' || substr($line, -1) === '.') {
return trim($summary);
}
}
$summary = trim($summary);
if ($summary === '') {
return UNDEFINED;
}
return $summary;
} | php | {
"resource": ""
} |
q16279 | Context.detect | train | public static function detect($index = 0)
{
$context = new Context();
$backtrace = debug_backtrace();
$position = $backtrace[$index];
if (isset($position['file'])) {
$context->filename = $position['file'];
}
if (isset($position['line'])) {
$context->line = $position['line'];
}
$caller = isset($backtrace[$index + 1]) ? $backtrace[$index + 1] : null;
if (isset($caller['function'])) {
$context->method = $caller['function'];
if (isset($caller['type']) && $caller['type'] === '::') {
$context->static = true;
}
}
if (isset($caller['class'])) {
$fqn = explode('\\', $caller['class']);
$context->class = array_pop($fqn);
if (count($fqn)) {
$context->namespace = implode('\\', $fqn);
}
}
// @todo extract namespaces and use statements
return $context;
} | php | {
"resource": ""
} |
q16280 | Context.fullyQualifiedName | train | public function fullyQualifiedName($class)
{
if ($this->namespace) {
$namespace = str_replace('\\\\', '\\', '\\' . $this->namespace . '\\');
} else {
$namespace = '\\'; // global namespace
}
if ($this->class === null) {
$this->class = '';
}
if ($class === null) {
return '';
}
if (strcasecmp($class, $this->class) === 0) {
return $namespace . $this->class;
}
$pos = strpos($class, '\\');
if ($pos !== false) {
if ($pos === 0) {
// Fully qualified name (\Foo\Bar)
return $class;
}
// Qualified name (Foo\Bar)
if ($this->uses) {
foreach ($this->uses as $alias => $aliasedNamespace) {
$alias .= '\\';
if (strcasecmp(substr($class, 0, strlen($alias)), $alias) === 0) {
// Aliased namespace (use \Long\Namespace as Foo)
return '\\' . $aliasedNamespace . substr($class, strlen($alias) - 1);
}
}
}
} elseif ($this->uses) {
// Unqualified name (Foo)
foreach ($this->uses as $alias => $aliasedNamespace) {
if (strcasecmp($alias, $class) === 0) {
return '\\' . $aliasedNamespace;
}
}
}
return $namespace . $class;
} | php | {
"resource": ""
} |
q16281 | Analysis.getTraitsOfClass | train | public function getTraitsOfClass($class)
{
$definitions = [];
// in case there is a hierarchy of classes
$classes = $this->getSuperClasses($class);
if (is_array($classes)) {
foreach ($classes as $subClass) {
if (isset($subClass['traits'])) {
foreach ($subClass['traits'] as $classTrait) {
foreach ($this->traits as $trait) {
if ($classTrait === $trait['trait']) {
$traitDefinition[$trait['trait']] = $trait;
$definitions = array_merge($definitions, $traitDefinition);
}
}
}
}
}
}
// trait used by the given class
$classDefinition = isset($this->classes[$class]) ? $this->classes[$class] : null;
if (!$classDefinition || empty($classDefinition['traits'])) {
return $definitions;
}
$classTraits = $classDefinition['traits'];
foreach ($this->traits as $trait) {
foreach ($classTraits as $classTrait => $name) {
if ($trait['trait'] === $name) {
$traitDefinition[$name] = $trait;
$definitions = array_merge($definitions, $traitDefinition);
}
}
}
return $definitions;
} | php | {
"resource": ""
} |
q16282 | Analysis.merged | train | public function merged()
{
if (!$this->openapi) {
throw new Exception('No openapi target set. Run the MergeIntoOpenApi processor');
}
$unmerged = $this->openapi->_unmerged;
$this->openapi->_unmerged = [];
$analysis = new Analysis([$this->openapi]);
$this->openapi->_unmerged = $unmerged;
return $analysis;
} | php | {
"resource": ""
} |
q16283 | Analysis.split | train | public function split()
{
$result = new stdClass();
$result->merged = $this->merged();
$result->unmerged = new Analysis();
foreach ($this->annotations as $annotation) {
if ($result->merged->annotations->contains($annotation) === false) {
$result->unmerged->annotations->attach($annotation, $this->annotations[$annotation]);
}
}
return $result;
} | php | {
"resource": ""
} |
q16284 | Analysis.& | train | public static function &processors()
{
if (!self::$processors) {
// Add default processors.
self::$processors = [
new MergeIntoOpenApi(),
new MergeIntoComponents(),
new ImportTraits(),
new AugmentSchemas(),
new AugmentProperties(),
new BuildPaths(),
// new HandleReferences(),
new InheritProperties(),
new AugmentOperations(),
new AugmentParameters(),
new MergeJsonContent(),
new MergeXmlContent(),
new OperationId(),
new CleanUnmerged(),
];
}
return self::$processors;
} | php | {
"resource": ""
} |
q16285 | Analysis.unregisterProcessor | train | public static function unregisterProcessor($processor)
{
$processors = &self::processors();
$key = array_search($processor, $processors, true);
if ($key === false) {
throw new Exception('Given processor was not registered');
}
unset($processors[$key]);
} | php | {
"resource": ""
} |
q16286 | StaticAnalyser.fromFile | train | public function fromFile($filename)
{
if (function_exists('opcache_get_status') && function_exists('opcache_get_configuration')) {
if (empty($GLOBALS['openapi_opcache_warning'])) {
$GLOBALS['openapi_opcache_warning'] = true;
$status = opcache_get_status();
$config = opcache_get_configuration();
if ($status['opcache_enabled'] && $config['directives']['opcache.save_comments'] == false) {
Logger::warning("php.ini \"opcache.save_comments = 0\" interferes with extracting annotations.\n[LINK] http://php.net/manual/en/opcache.configuration.php#ini.opcache.save-comments");
}
}
}
$tokens = token_get_all(file_get_contents($filename));
return $this->fromTokens($tokens, new Context(['filename' => $filename]));
} | php | {
"resource": ""
} |
q16287 | StaticAnalyser.fromCode | train | public function fromCode($code, $context)
{
$tokens = token_get_all($code);
return $this->fromTokens($tokens, $context);
} | php | {
"resource": ""
} |
q16288 | StaticAnalyser.nextToken | train | private function nextToken(&$tokens, $context)
{
while (true) {
$token = next($tokens);
if ($token[0] === T_WHITESPACE) {
continue;
}
if ($token[0] === T_COMMENT) {
$pos = strpos($token[1], '@OA\\');
if ($pos) {
$line = $context->line ? $context->line + $token[2] : $token[2];
$commentContext = new Context(['line' => $line], $context);
Logger::notice('Annotations are only parsed inside `/**` DocBlocks, skipping ' . $commentContext);
}
continue;
}
return $token;
}
} | php | {
"resource": ""
} |
q16289 | OpenApi.saveAs | train | public function saveAs($filename, $format = 'auto')
{
if ($format === 'auto') {
$format = strtolower(substr($filename, -5)) === '.json' ? 'json' : 'yaml';
}
if (strtolower($format) === 'json') {
$content = $this->toJson();
} else {
$content = $this->toYaml();
}
if (file_put_contents($filename, $content) === false) {
throw new Exception('Failed to saveAs("' . $filename . '", "'.$format.'")');
}
} | php | {
"resource": ""
} |
q16290 | Util.removePrefix | train | private static function removePrefix($str, $prefix)
{
if (substr($str, 0, strlen($prefix)) == $prefix) {
return substr($str, strlen($prefix));
}
return null;
} | php | {
"resource": ""
} |
q16291 | ItemMenu.route | train | public function route(string $name, array $parameters = [], bool $absolute = true): self
{
$this->route = route($name, $parameters, $absolute);
$this->active([$this->route, $this->route.'/*']);
return $this;
} | php | {
"resource": ""
} |
q16292 | Picture.targetId | train | public function targetId(): self
{
$this->set('target', 'id');
$this->addBeforeRender(function () {
$value = (string) $this->get('value');
if (! ctype_digit($value)) {
return;
}
/** @var Attachment $attach */
$attach = Dashboard::model(Attachment::class);
$url = optional($attach::find($value))->url();
$this->set('url', $url);
});
return $this;
} | php | {
"resource": ""
} |
q16293 | Menu.add | train | public function add(string $place, ItemMenu $itemMenu)
{
$arg = get_object_vars($itemMenu);
if (array_key_exists('show', $arg) && ! $arg['show']) {
return $this;
}
$this->location = $place;
$this->arg = $arg;
$this->sort = $arg['sort'];
$this->item = [
'location' => $this->location,
'arg' => $this->arg,
'sort' => $this->sort,
];
$this->container[$this->arg['slug']] = $this->item;
return $this;
} | php | {
"resource": ""
} |
q16294 | Menu.render | train | public function render(string $location, string $template = 'platform::partials.mainMenu'): string
{
$this->checkAccess();
return $this->findAllChildren($location)
->sortBy('sort')
->map(function ($value) use ($template) {
return view($template, $value)->render();
})
->implode(' ');
} | php | {
"resource": ""
} |
q16295 | ResourceController.show | train | public function show(string $package, string $path, Dashboard $dashboard)
{
$dir = $dashboard
->getPublicDirectory()
->get($package);
abort_if(is_null($dir), 404);
$resources = (new Finder())
->ignoreUnreadableDirs()
->followLinks()
->in($dir)
->files()
->path(dirname($path))
->name(basename($path));
$iterator = tap($resources->getIterator())
->rewind();
$this->resource = $iterator->current();
abort_if(is_null($this->resource), 404);
$mime = new MimeTypes();
$mime = $mime->getMimeType($this->resource->getExtension());
return response()->file($this->resource->getRealPath(), [
'Content-Type' => $mime ?? 'text/plain',
'Cache-Control' => 'public, max-age=31536000',
]);
} | php | {
"resource": ""
} |
q16296 | Post.getEntityObject | train | public function getEntityObject($slug = null)
{
if (! is_null($this->entity)) {
return $this->entity;
}
return $this->getEntity($slug ?? $this->getAttribute('type'))->entity;
} | php | {
"resource": ""
} |
q16297 | TaxonomyBuilder.slug | train | public function slug($slug = null): self
{
if (! empty($slug)) {
// set this slug to be used in with callback
$this->slug = $slug;
// exception to filter on specific slug
$exception = function ($query) {
$query->where('slug', '=', $this->slug);
};
// load term to filter
return $this->whereHas('term', $exception);
}
return $this;
} | php | {
"resource": ""
} |
q16298 | DateTimer.noCalendar | train | public function noCalendar(bool $noCalendar = true) : self
{
$this->enableTime();
$this->set('data-fields--datetime-no-calendar', var_export($noCalendar, true));
return $this;
} | php | {
"resource": ""
} |
q16299 | Many.getFilters | train | public function getFilters(): Collection
{
$filters = collect();
foreach ($this->filters() as $filter) {
$filter = new $filter($this);
$filters->push($filter);
}
return $filters;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.