_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6800 | Curl.prepareResponse | train | protected function prepareResponse($data, $code)
{
$rawHeaders = array();
$rawContent = null;
$lines = preg_split('/(\\r?\\n)/', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $count = count($lines); $i < $count; $i += 2) {
$line = $lines[$i];
if (!empty($line)) {
$rawHeaders[] = $line;
} else {
$rawContent = implode('', array_slice($lines, $i + 2));
break;
}
}
$headers = $this->prepareHeaders($rawHeaders);
return new Response($rawContent, $code, $headers);
} | php | {
"resource": ""
} |
q6801 | Curl.prepareHeaders | train | protected function prepareHeaders(array $rawHeaders)
{
$headers = array();
foreach ($rawHeaders as $rawHeader) {
if (strpos($rawHeader, ':')) {
$data = explode(':', $rawHeader);
$headers[$data[0]][] = trim($data[1]);
}
}
return $headers;
} | php | {
"resource": ""
} |
q6802 | Currency.valueOf | train | public static function valueOf($code = self::NONE)
{
if (self::isValidCode($code)) {
$details = self::getDetails($code);
$code = $details['code'];
$isoStatus = $details['isoStatus'];
$decimalDigits = $details['decimalDigits'];
$name = $details['name'];
return new Currency($code, $isoStatus, $decimalDigits, $name);
} else {
throw new \InvalidArgumentException('Unknown currency code \'' . $code . '\'.');
}
} | php | {
"resource": ""
} |
q6803 | Currency.isValidCode | train | public static function isValidCode($code)
{
if (array_key_exists($code, self::getInfoForCurrencies())) {
return true;
} elseif (array_key_exists($code, self::getInfoForCurrenciesWithoutCurrencyCode())) {
return true;
} elseif (array_key_exists($code, self::getInfoForCurrenciesWithUnofficialCode())) {
return true;
} elseif (array_key_exists($code, self::getInfoForCurrenciesWithHistoricalCode())) {
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q6804 | Currency.getDetails | train | public static function getDetails($code)
{
$infos = self::getInfoForCurrencies();
if (array_key_exists($code, $infos)) {
return $infos[$code];
}
$infos = self::getInfoForCurrenciesWithoutCurrencyCode();
if (array_key_exists($code, $infos)) {
return $infos[$code];
}
$infos = self::getInfoForCurrenciesWithUnofficialCode();
if (array_key_exists($code, $infos)) {
return $infos[$code];
}
$infos = self::getInfoForCurrenciesWithHistoricalCode();
if (array_key_exists($code, $infos)) {
return $infos[$code];
}
throw new \InvalidArgumentException('Unknown \$code: ' . $code);
} | php | {
"resource": ""
} |
q6805 | Currency.getInfoForCurrenciesWithoutCurrencyCode | train | public static function getInfoForCurrenciesWithoutCurrencyCode()
{
return array(
self::WITHOUT_CURRENCY_CODE_GGP => array(
'code' => self::WITHOUT_CURRENCY_CODE_GGP,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Guernsey pound',
),
self::WITHOUT_CURRENCY_CODE_JEP => array(
'code' => self::WITHOUT_CURRENCY_CODE_JEP,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Jersey pound',
),
self::WITHOUT_CURRENCY_CODE_IMP => array(
'code' => self::WITHOUT_CURRENCY_CODE_IMP,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Isle of Man pound also Manx pound',
),
self::WITHOUT_CURRENCY_CODE_KRI => array(
'code' => self::WITHOUT_CURRENCY_CODE_KRI,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Kiribati dollar',
),
self::WITHOUT_CURRENCY_CODE_SLS => array(
'code' => self::WITHOUT_CURRENCY_CODE_SLS,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Somaliland shilling',
),
self::WITHOUT_CURRENCY_CODE_PRB => array(
'code' => self::WITHOUT_CURRENCY_CODE_PRB,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Transnistrian ruble',
),
self::WITHOUT_CURRENCY_CODE_TVD => array(
'code' => self::WITHOUT_CURRENCY_CODE_TVD,
'isoStatus' => self::ISO_STATUS_WITHOUT_CURRENCY_CODE,
'decimalDigits' => 2,
'name' => 'Tuvalu dollar',
)
);
} | php | {
"resource": ""
} |
q6806 | Money.round | train | public function round($decimalDigits = null, $mode = self::ROUND_HALF_AWAY_FROM_ZERO)
{
if (null === $decimalDigits) {
$decimalDigits = $this->currency->getDecimalDigits();
}
$factor = bcpow('10', $decimalDigits, self::BCSCALE);
$amount = bcmul($this->amount, $factor, self::BCSCALE);
switch ($mode) {
case self::ROUND_UP:
$result = self::roundUp($amount);
break;
case self::ROUND_DOWN:
$result = self::roundDown($amount);
break;
case self::ROUND_TOWARDS_ZERO:
$result = self::roundTowardsZero($amount);
break;
case self::ROUND_AWAY_FROM_ZERO:
$result = self::roundAwayFromZero($amount);
break;
case self::ROUND_HALF_UP:
$result = self::roundHalfUp($amount);
break;
case self::ROUND_HALF_DOWN:
$result = self::roundHalfDown($amount);
break;
case self::ROUND_HALF_TOWARDS_ZERO:
$result = self::roundHalfTowardsZero($amount);
break;
case self::ROUND_HALF_AWAY_FROM_ZERO:
$result = self::roundHalfAwayFromZero($amount);
break;
case self::ROUND_HALF_TO_EVEN:
$result = self::roundHalfToEven($amount);
break;
case self::ROUND_HALF_TO_ODD:
$result = self::roundHalfToOdd($amount);
break;
default:
throw new \InvalidArgumentException('Unknown rounding mode \''.$mode.'\'');
}
$result = bcdiv($result, $factor, self::BCSCALE);
return self::valueOf($result, $this->currency);
} | php | {
"resource": ""
} |
q6807 | Money.discardDecimalDigitsZero | train | private static function discardDecimalDigitsZero($amount, $minimumDecimalDigits = 0)
{
if (false !== strpos($amount, '.')) {
while ('0' == substr($amount, -1)) {
$amount = substr($amount, 0, -1);
}
if ('.' == substr($amount, -1)) {
$amount = substr($amount, 0, -1);
}
}
if ($minimumDecimalDigits > 0) {
if (false === strpos($amount, '.')) {
$amount .= '.';
}
$currentDecimalDigits = strlen(substr($amount, strpos($amount, '.') + 1));
$minimumDecimalDigits -= $currentDecimalDigits;
while ($minimumDecimalDigits > 0) {
$amount .= '0';
$minimumDecimalDigits--;
}
}
return $amount;
} | php | {
"resource": ""
} |
q6808 | Money.roundToNearestIntegerIgnoringTies | train | private static function roundToNearestIntegerIgnoringTies($amount)
{
$relevantDigit = substr(self::roundTowardsZero(bcmul($amount, '10', self::BCSCALE)), -1);
$result = null;
switch ($relevantDigit) {
case '0':
case '1':
case '2':
case '3':
case '4':
$result = self::roundTowardsZero($amount);
break;
case '5':
$result = null; // handled by tie-breaking rules
break;
case '6':
case '7':
case '8':
case '9':
$result = self::roundAwayFromZero($amount);
break;
}
return $result;
} | php | {
"resource": ""
} |
q6809 | Money.roundHalfUp | train | private static function roundHalfUp($amount)
{
$result = self::roundToNearestIntegerIgnoringTies($amount);
if (null == $result) {
$result = self::roundToNearestIntegerIgnoringTies(bcadd($amount, '0.1', self::BCSCALE));
}
return $result;
} | php | {
"resource": ""
} |
q6810 | Money.roundHalfDown | train | private static function roundHalfDown($amount)
{
$result = self::roundToNearestIntegerIgnoringTies($amount);
if (null == $result) {
$result = self::roundToNearestIntegerIgnoringTies(bcsub($amount, '0.1', self::BCSCALE));
}
return $result;
} | php | {
"resource": ""
} |
q6811 | Money.roundHalfTowardsZero | train | private static function roundHalfTowardsZero($amount)
{
if (0 <= bccomp($amount, '0', self::BCSCALE)) {
$result = self::roundHalfDown($amount);
} else {
$result = self::roundHalfUp($amount);
}
return $result;
} | php | {
"resource": ""
} |
q6812 | Money.roundHalfAwayFromZero | train | private static function roundHalfAwayFromZero($amount)
{
if (0 <= bccomp($amount, '0', self::BCSCALE)) {
$result = self::roundHalfUp($amount);
} else {
$result = self::roundHalfDown($amount);
}
return $result;
} | php | {
"resource": ""
} |
q6813 | Money.roundHalfToEven | train | private static function roundHalfToEven($amount)
{
$result = self::roundToNearestIntegerIgnoringTies($amount);
if (null == $result) {
$truncated = self::roundHalfTowardsZero($amount);
if (0 == bcmod($truncated, '2')) { // Even
$result = $truncated;
} else {
$result = self::roundHalfAwayFromZero($amount);
}
}
return $result;
} | php | {
"resource": ""
} |
q6814 | Money.zero | train | public static function zero(Currency $currency = null)
{
if (null === $currency) {
$currency = Currency::valueOf(Currency::NONE);
}
return self::valueOf('0', $currency);
} | php | {
"resource": ""
} |
q6815 | Money.noCurrency | train | public static function noCurrency($amount = null)
{
if (null === $amount) {
$amount = '0';
}
return self::valueOf(strval($amount), Currency::valueOf(Currency::NONE));
} | php | {
"resource": ""
} |
q6816 | Money.compare | train | public function compare(Money $money)
{
return bccomp($this->amount, $money->getAmount(), self::BCSCALE);
} | php | {
"resource": ""
} |
q6817 | Money.equals | train | public function equals(Money $money)
{
if (!$this->currency->equals($money->getCurrency())) {
return false;
}
return (0 == $this->compare($money));
} | php | {
"resource": ""
} |
q6818 | Money.modulus | train | public function modulus($modulus)
{
if (!is_numeric($modulus)) {
throw new \InvalidArgumentException('Modulus must be numeric');
}
$amount = bcmod($this->amount, strval($modulus));
return self::valueOf($amount, $this->currency);
} | php | {
"resource": ""
} |
q6819 | Money.squareRoot | train | public function squareRoot()
{
$amount = bcsqrt($this->amount, self::BCSCALE);
return self::valueOf($amount, $this->currency);
} | php | {
"resource": ""
} |
q6820 | Configuration.projectName | train | public function projectName()
{
$name = $this->name();
if (null === $name) {
return null;
}
$atoms = explode(static::NAME_SEPARATOR, $name);
return array_pop($atoms);
} | php | {
"resource": ""
} |
q6821 | Configuration.vendorName | train | public function vendorName()
{
$name = $this->name();
if (null === $name) {
return null;
}
$atoms = explode(static::NAME_SEPARATOR, $name);
array_pop($atoms);
if (count($atoms) < 1) {
return null;
}
return implode(static::NAME_SEPARATOR, $atoms);
} | php | {
"resource": ""
} |
q6822 | Configuration.allPsr4SourcePaths | train | public function allPsr4SourcePaths()
{
$autoloadPsr4Paths = array();
foreach ($this->autoloadPsr4() as $namespace => $paths) {
$autoloadPsr4Paths = array_merge($autoloadPsr4Paths, $paths);
}
return $autoloadPsr4Paths;
} | php | {
"resource": ""
} |
q6823 | Configuration.allPsr0SourcePaths | train | public function allPsr0SourcePaths()
{
$autoloadPsr0Paths = array();
foreach ($this->autoloadPsr0() as $namespace => $paths) {
$autoloadPsr0Paths = array_merge($autoloadPsr0Paths, $paths);
}
return $autoloadPsr0Paths;
} | php | {
"resource": ""
} |
q6824 | Configuration.allSourcePaths | train | public function allSourcePaths()
{
return array_merge(
$this->allPsr4SourcePaths(),
$this->allPsr0SourcePaths(),
$this->autoloadClassmap(),
$this->autoloadFiles(),
$this->includePath()
);
} | php | {
"resource": ""
} |
q6825 | EloquentSetting.allToArray | train | public function allToArray()
{
$config = [];
try {
foreach ($this->findAll() as $object) {
$key = $object->key_name;
if ($object->group_name != 'config') {
$config[$object->group_name][$key] = $object->value;
} else {
$config[$key] = $object->value;
}
}
} catch (Exception $e) {
Log::error($e->getMessage());
}
return $config;
} | php | {
"resource": ""
} |
q6826 | DoctrineContext.theFollowingRecordsInTheRepository | train | public function theFollowingRecordsInTheRepository($entity, YamlStringNode $records)
{
$manager = $this->getDoctrine()->getManager();
$accessor = new PropertyAccessor();
foreach ($records->toArray() as $record) {
$instance = new $entity();
foreach ($record as $prop => $value) {
$accessor->setValue($instance, $prop, $value);
}
$manager->persist($instance);
}
$manager->flush();
} | php | {
"resource": ""
} |
q6827 | DoctrineContext.grabInFromRepositoryFirstRecordsOrderedByMatching | train | public function grabInFromRepositoryFirstRecordsOrderedByMatching($variable, $repo, $limitAndOffset = null, $orderBy = null, YamlStringNode $criteria = null)
{
//support to use "limit:offset"
if (strpos($limitAndOffset, ':') !== false) {
list($limit, $offset) = explode(':', $limitAndOffset);
} else {
$limit = $limitAndOffset;
$offset = null;
}
// support field:ORDER, eg. name:ASC
if (is_string($orderBy)) {
list($field, $order) = explode(':', $orderBy);
$orderBy = [$field => $order];
}
$records = $this->getDoctrine()
->getRepository($repo)
->findBy($criteria ? $criteria->toArray() : [], $orderBy, $limit, $offset);
$this->storage->setValue($variable, $records);
} | php | {
"resource": ""
} |
q6828 | Client.create | train | static function create(\Plasma\DriverFactoryInterface $factory, string $uri, array $options = array()): \Plasma\ClientInterface {
return (new static($factory, $uri, $options));
} | php | {
"resource": ""
} |
q6829 | Client.checkinConnection | train | function checkinConnection(\Plasma\DriverInterface $driver): void {
if($driver->getConnectionState() !== \Plasma\DriverInterface::CONNECTION_UNUSABLE && !$this->goingAway) {
$this->connections->add($driver);
$this->busyConnections->delete($driver);
}
} | php | {
"resource": ""
} |
q6830 | Client.beginTransaction | train | function beginTransaction(int $isolation = \Plasma\TransactionInterface::ISOLATION_COMMITTED): \React\Promise\PromiseInterface {
if($this->goingAway) {
return \React\Promise\reject((new \Plasma\Exception('Client is closing all connections')));
}
$connection = $this->getOptimalConnection();
return $connection->beginTransaction($this, $isolation)->then(null, function (\Throwable $error) use (&$connection) {
$this->checkinConnection($connection);
throw $error;
});
} | php | {
"resource": ""
} |
q6831 | Client.execute | train | function execute(string $query, array $params = array()): \React\Promise\PromiseInterface {
if($this->goingAway) {
return \React\Promise\reject((new \Plasma\Exception('Client is closing all connections')));
}
$connection = $this->getOptimalConnection();
return $connection->execute($this, $query, $params)->then(function ($value) use (&$connection) {
$this->checkinConnection($connection);
return $value;
}, function (\Throwable $error) use (&$connection) {
$this->checkinConnection($connection);
throw $error;
});
} | php | {
"resource": ""
} |
q6832 | Client.close | train | function close(): \React\Promise\PromiseInterface {
if($this->goingAway) {
return $this->goingAway;
}
$deferred = new \React\Promise\Deferred();
$this->goingAway = $deferred->promise();
$closes = array();
/** @var \Plasma\DriverInterface $conn */
foreach($this->connections->all() as $conn) {
$closes[] = $conn->close();
$this->connections->delete($conn);
}
/** @var \Plasma\DriverInterface $conn */
foreach($this->busyConnections->all() as $conn) {
$closes[] = $conn->close();
$this->busyConnections->delete($conn);
}
\React\Promise\all($closes)->then(array($deferred, 'resolve'), array($deferred, 'reject'));
return $this->goingAway;
} | php | {
"resource": ""
} |
q6833 | Client.quit | train | function quit(): void {
if($this->goingAway) {
return;
}
$this->goingAway = \React\Promise\resolve();
/** @var \Plasma\DriverInterface $conn */
foreach($this->connections->all() as $conn) {
$conn->quit();
$this->connections->delete($conn);
}
/** @var \Plasma\DriverInterface $conn */
foreach($this->busyConnections->all() as $conn) {
$conn->quit();
$this->busyConnections->delete($conn);
}
} | php | {
"resource": ""
} |
q6834 | Client.runQuery | train | function runQuery(\Plasma\QueryBuilderInterface $query): \React\Promise\PromiseInterface {
if($this->goingAway) {
return \React\Promise\reject((new \Plasma\Exception('Client is closing all connections')));
}
$connection = $this->getOptimalConnection();
try {
return $connection->runQuery($this, $query);
} catch (\Throwable $e) {
$this->checkinConnection($connection);
throw $e;
}
} | php | {
"resource": ""
} |
q6835 | Client.createReadCursor | train | function createReadCursor(string $query, array $params = array()): \React\Promise\PromiseInterface {
if($this->goingAway) {
return \React\Promise\reject((new \Plasma\Exception('Client is closing all connections')));
}
$connection = $this->getOptimalConnection();
try {
return $connection->createReadCursor($this, $query, $params);
} catch (\Throwable $e) {
$this->checkinConnection($connection);
throw $e;
}
} | php | {
"resource": ""
} |
q6836 | Client.getOptimalConnection | train | protected function getOptimalConnection(): \Plasma\DriverInterface {
if(\count($this->connections) === 0) {
$connection = $this->createNewConnection();
$this->busyConnections->add($connection);
return $connection;
}
/** @var \Plasma\DriverInterface $connection */
$this->connections->rewind();
$connection = $this->connections->current();
$backlog = $connection->getBacklogLength();
$state = $connection->getBusyState();
/** @var \Plasma\DriverInterface $conn */
foreach($this->connections as $conn) {
$cbacklog = $conn->getBacklogLength();
$cstate = $conn->getBusyState();
if($cbacklog === 0 && $conn->getConnectionState() === \Plasma\DriverInterface::CONNECTION_OK && $cstate == \Plasma\DriverInterface::STATE_IDLE) {
$this->connections->delete($conn);
$this->busyConnections->add($conn);
return $conn;
}
if($backlog > $cbacklog || $state > $cstate) {
$connection = $conn;
$backlog = $cbacklog;
$state = $cstate;
}
}
if($this->getConnectionCount() < $this->options['connections.max']) {
$connection = $this->createNewConnection();
}
$this->connections->delete($connection);
$this->busyConnections->add($connection);
return $connection;
} | php | {
"resource": ""
} |
q6837 | Client.createNewConnection | train | protected function createNewConnection(): \Plasma\DriverInterface {
$connection = $this->factory->createDriver();
// We relay a driver's specific events forward, e.g. PostgreSQL notifications
$connection->on('eventRelay', function (string $eventName, ...$args) use (&$connection) {
$args[] = $connection;
$this->emit($eventName, $args);
});
$connection->on('close', function () use (&$connection) {
$this->connections->delete($connection);
$this->busyConnections->delete($connection);
$this->emit('close', array($connection));
});
$connection->on('error', function (\Throwable $error) use (&$connection) {
$this->emit('error', array($error, $connection));
});
$connection->connect($this->uri)->then(function () use (&$connection) {
$this->connections->add($connection);
$this->busyConnections->delete($connection);
}, function (\Throwable $error) use (&$connection) {
$this->connections->delete($connection);
$this->busyConnections->delete($connection);
$this->emit('error', array($error, $connection));
});
return $connection;
} | php | {
"resource": ""
} |
q6838 | Client.validateOptions | train | protected function validateOptions(array $options) {
$validator = \CharlotteDunois\Validation\Validator::make($options, array(
'connections.max' => 'integer|min:1',
'connections.lazy' => 'boolean'
));
$validator->throw(\InvalidArgumentException::class);
} | php | {
"resource": ""
} |
q6839 | SolrIndexable.onAfterWrite | train | public function onAfterWrite() {
if (!self::$indexing) return;
// No longer doing the 'ischanged' check to avoid problems with multivalue field NOT being indexed
//$changes = $this->owner->getChangedFields(true, 2);
$stage = null;
// if it's being written and a versionable, then save only in the draft
// repository.
if ($this->owner->hasMethod('canBeVersioned') && $this->owner->canBeVersioned($this->owner->baseTable())) {
$stage = Versioned::current_stage();
}
if ($this->canShowInSearch()) {
// DataObject::write() does _not_ set LastEdited until _after_ onAfterWrite completes
$this->owner->LastEdited = date('Y-m-d H:i:s');
$this->reindex($stage);
}
} | php | {
"resource": ""
} |
q6840 | SolrIndexable.reindex | train | public function reindex($stage = null) {
// Make sure the current data object is not orphaned.
if($this->owner->ParentID > 0) {
$parent = $this->owner->Parent();
if(is_null($parent) || ($parent === false)) {
return;
}
}
// Make sure the extension requirements have been met before enabling the custom site tree search index,
// since this may impact performance.
if((ClassInfo::baseDataClass($this->owner) === 'SiteTree')
&& SiteTree::has_extension('SiteTreePermissionIndexExtension')
&& SiteTree::has_extension('SolrSearchPermissionIndexExtension')
&& ClassInfo::exists('QueuedJob')
) {
// Queue a job to handle the recursive indexing.
$indexing = new SolrSiteTreePermissionIndexJob($this->owner, $stage);
singleton('QueuedJobService')->queueJob($indexing);
}
else {
// When the requirements haven't been met, trigger a normal index.
$this->searchService->index($this->owner, $stage);
}
} | php | {
"resource": ""
} |
q6841 | GuerrillaMail.setEmailAddress | train | public function setEmailAddress($email_user, $lang = 'en')
{
$action = "set_email_user";
$options = array(
'email_user' => $email_user,
'lang' => $lang,
'sid_token' => $this->sid_token
);
return $this->client->post($action, $options);
} | php | {
"resource": ""
} |
q6842 | GuerrillaMail.forgetMe | train | public function forgetMe($email_address)
{
$action = "forget_me";
$options = array(
'email_addr' => $email_address,
'sid_token' => $this->sid_token
);
return $this->client->post($action, $options);
} | php | {
"resource": ""
} |
q6843 | EventsEndpoint.trackLogIn | train | public function trackLogIn($ip, array $user, $userAgent = null, array $source = null, array $session = null, array $device = null)
{
$this->trackEvent(self::VERB_LOG_IN, $ip, $user, $userAgent, $source, $session, $device);
} | php | {
"resource": ""
} |
q6844 | EventsEndpoint.trackLogInDenied | train | public function trackLogInDenied($ip, array $user = null, $userAgent = null, array $source = null, array $session = null, array $device = null)
{
$this->trackEvent(self::VERB_LOG_IN_DENIED, $ip, $user, $userAgent, $source, $session, $device);
} | php | {
"resource": ""
} |
q6845 | EventsEndpoint.trackEvent | train | public function trackEvent($verb, $ip, array $user = null, $userAgent = null, array $source = null, array $session = null, array $device = null)
{
$event = [
self::PARAM_VERB => $verb,
self::PARAM_IP => $ip
];
if (!is_null($userAgent)) {
$event[self::PARAM_USER_AGENT] = $userAgent;
}
if (!is_null($user)) {
$event[self::PARAM_USER] = array_filter([
self::PARAM_USER__ID => $this->findValue(self::PARAM_USER__ID, $user),
self::PARAM_USER__NAME => $this->findValue(self::PARAM_USER__NAME, $user),
self::PARAM_USER__EMAIL => $this->findValue(self::PARAM_USER__EMAIL, $user),
self::PARAM_USER__MOBILE => $this->findValue(self::PARAM_USER__MOBILE, $user),
self::PARAM_USER__AUTHENTICATED => $this->findValue(self::PARAM_USER__AUTHENTICATED, $user),
]);
}
if (!is_null($source)) {
$event[self::PARAM_SOURCE] = array_filter([
self::PARAM_SOURCE__NAME => $this->findValue(self::PARAM_SOURCE__NAME, $source),
self::PARAM_SOURCE__LOGO_URL => $this->findValue(self::PARAM_SOURCE__LOGO_URL, $source)
]);
}
// Add information about the session
// First, the session ID if it's passed
$event[self::PARAM_SESSION] = array_filter([
self::PARAM_SESSION__ID => $this->findValue(self::PARAM_SESSION__ID, $session)
]);
// Then pull the TD cookie if its present
if (isset($_COOKIE[ThisData::TD_COOKIE_NAME])) {
$event[self::PARAM_SESSION][self::PARAM_SESSION__TD_COOKIE_ID] = $_COOKIE[ThisData::TD_COOKIE_NAME];
}
// Then whether we expect the JS Cookie at all
if ($this->configuration[Builder::CONF_EXPECT_JS_COOKIE]) {
$event[self::PARAM_SESSION][self::PARAM_SESSION__TD_COOKIE_EXPECTED] = $this->configuration[Builder::CONF_EXPECT_JS_COOKIE];
}
if (!is_null($device)) {
$event[self::PARAM_DEVICE] = array_filter([
self::PARAM_DEVICE__ID => $this->findValue(self::PARAM_DEVICE__ID, $device)
]);
}
$this->execute('POST', ThisData::ENDPOINT_EVENTS, array_filter($event));
} | php | {
"resource": ""
} |
q6846 | EventsEndpoint.getEvents | train | public function getEvents(array $options = null)
{
$url = ThisData::ENDPOINT_EVENTS;
if (!is_null($options)) {
$url .= '?' . http_build_query($options);
}
$response = $this->synchronousExecute('GET', $url);
return json_decode($response->getBody(), TRUE);
} | php | {
"resource": ""
} |
q6847 | TranslatorInitializer.initialize | train | public function initialize(TranslatorInterface $translator)
{
$event = new CreateTranslatorEvent($translator);
$this->eventDispatcher->dispatch($event::NAME, $event);
return $translator;
} | php | {
"resource": ""
} |
q6848 | NewsArticle.onBeforeWrite | train | public function onBeforeWrite() {
parent::onBeforeWrite();
// dummy initial date
if (!$this->OriginalPublishedDate) {
// @TODO Fix this to be correctly localized!!
$this->OriginalPublishedDate = date('Y-m-d 12:00:00');
}
$parent = $this->Parent();
// just in case we've been moved, update our section
$section = $this->findSection();
$this->NewsSectionID = $section->ID;
$newlyCreated = $section->ID == $parent->ID;
$changedPublishDate = $this->isChanged('OriginalPublishedDate', 2);
if (($changedPublishDate || $newlyCreated) && ($section->AutoFiling || $section->FilingMode)) {
if (!$this->Created) {
$this->Created = date('Y-m-d H:i:s');
}
$pp = $this->PartitionParent();
if ($pp->ID != $this->ParentID) {
$this->ParentID = $pp->ID;
}
}
} | php | {
"resource": ""
} |
q6849 | NewsArticle.publishSection | train | protected function publishSection() {
$parent = DataObject::get_by_id('NewsHolder', $this->ParentID);
while ($parent && $parent instanceof NewsHolder) {
if (!$parent->isPublished()) {
$parent->doPublish();
}
$parent = $parent->Parent();
}
} | php | {
"resource": ""
} |
q6850 | NewsArticle.Link | train | public function Link($action='') {
if (strlen($this->ExternalURL) && !strlen($this->Content)) {
// redirect away
return $this->ExternalURL;
}
if ($this->InternalFile()->ID) {
$file = $this->InternalFile();
return $file->Link($action);
}
return parent::Link($action);
} | php | {
"resource": ""
} |
q6851 | NewsArticle.pagesAffectedByChanges | train | public function pagesAffectedByChanges() {
$parent = $this->Parent();
$urls = array($this->Link());
// add all parent (holders)
while($parent && $parent->ParentID > -1 && $parent instanceof NewsHolder) {
$urls[] = $parent->Link();
$parent = $parent->Parent();
}
$this->extend('updatePagesAffectedByChanges', $urls);
return $urls;
} | php | {
"resource": ""
} |
q6852 | Layout.renderZone | train | protected function renderZone($zone, $args=array()){
$sep = isset($args['seperator']) ? $args['seperator'] : ' ';
if($this->debug===true){
echo "\n\n".'<!-- Template Zone: '.$zone.' -->';
}
$content = '';
if(isset($this->content[$zone])){
foreach($this->content[$zone] as $item){
switch($item['type']){
case 'hook':
//method will be called with two arrays as arguments
//the first is the args passed to this method (ie. in a template call to $this->insert() )
//the second are the args passed when the hook was bound
$content .= call_user_func_array($item['hook'], array($args, $item['arguments']));
break;
case 'html':
$content .= $sep . (string) $item['html'];
break;
case 'template':
$content .= $this->renderTemplate($item['template'], $item['params']);
break;
case 'zone':
$content .= $this->renderZone($item['zone'], $item['params']);
break;
}
}
}
//content from #movetoskin and #skintemplate
if( \Skinny::hasContent($zone) ){
foreach(\Skinny::getContent($zone) as $item){
//pre-rendered html from #movetoskin
if(isset($item['html'])){
if($this->debug===true){
$content.='<!--Skinny:MoveToSkin: '.$template.'-->';
}
$content .= $sep . $item['html'];
}
else
//a template name to render
if(isset($item['template'])){
if($this->debug===true){
$content.='<!--Skinny:Template (via #skintemplate): '.$item['template'].'-->';
}
$content .= $this->renderTemplate( $item['template'], $item['params'] );
}
}
}
return $content;
} | php | {
"resource": ""
} |
q6853 | Layout.addHookTo | train | public function addHookTo($zone, $hook, Array $args=array()){
if(!isset($this->content[$zone])){
$this->content[$zone] = array();
}
//allow just a string reference to a method on this skin object
if (!is_array($hook) && method_exists($this, $hook)) {
$hook = array($this, $hook);
}
if (!is_callable($hook, false, $callbable_name)) {
throw new \Exception('Invalid skin content hook for zone:'.$zone.' (Hook callback was: '.$callbable_name.')');
}
$this->content[$zone][] = array('type'=>'hook', 'hook'=>$hook, 'arguments'=>$args);
} | php | {
"resource": ""
} |
q6854 | Layout.addTemplateTo | train | public function addTemplateTo($zone, $template, Array $params=array()){
if(!isset($this->content[$zone]))
$this->content[$zone] = array();
$this->content[$zone][] = array('type'=>'template', 'template'=>$template, 'params'=>$params);
} | php | {
"resource": ""
} |
q6855 | Layout.addHTMLTo | train | public function addHTMLTo($zone, $content){
if(!isset($this->content[$zone]))
$this->content[$zone] = array();
$this->content[$zone][] = array('type'=>'html', 'html'=>$content);
} | php | {
"resource": ""
} |
q6856 | Layout.addZoneTo | train | public function addZoneTo($zone, $name, Array $params=array()){
if(!isset($this->content[$zone]))
$this->content[$zone] = array();
$this->content[$zone][] = array('type'=>'zone', 'zone'=>$name, 'params'=>$params);
} | php | {
"resource": ""
} |
q6857 | Identicon.displayImage | train | public function displayImage($string, $size = 64, $color = null, $backgroundColor = null)
{
$imageData = $this->getImageData($string, $size, $color, $backgroundColor);
return Response::make($imageData, 200, ['Content-Type' => 'image/png']);
} | php | {
"resource": ""
} |
q6858 | SolrResultSet.getResult | train | public function getResult() {
if (!$this->result && $this->response && $this->response->getHttpStatus() >= 200 && $this->response->getHttpStatus() < 300) {
// decode the response
$this->result = json_decode($this->response->getRawResponse());
}
return $this->result;
} | php | {
"resource": ""
} |
q6859 | SolrResultSet.inflateRawResult | train | protected function inflateRawResult($doc, $convertToObject = true) {
$field = SolrSearchService::SERIALIZED_OBJECT . '_t';
if (isset($doc->$field) && $convertToObject) {
$raw = unserialize($doc->$field);
if (isset($raw['SS_TYPE'])) {
$class = $raw['SS_TYPE'];
$object = Injector::inst()->create($class);
$object->update($raw);
$object->ID = str_replace(SolrSearchService::RAW_DATA_KEY, '', $doc->id);
return $object;
}
return ArrayData::create($raw);
}
$data = array(
'ID' => str_replace(SolrSearchService::RAW_DATA_KEY, '', $doc->id),
);
if (isset($doc->attr_SS_URL[0])) {
$data['Link'] = $doc->attr_SS_URL[0];
}
if (isset($doc->title)) {
$data['Title'] = $doc->title;
}
if (isset($doc->title_as)) {
$data['Title'] = $doc->title_as;
}
foreach ($doc as $key => $val) {
if ($key != 'attr_SS_URL') {
$name = null;
if (strpos($key, 'attr_') === 0) {
$name = str_replace('attr_', '', $key);
} else if (preg_match('/(.*?)_('. implode('|', self::$solr_attrs) .')$/', $key, $matches)) {
$name = $matches[1];
}
$val = $doc->$key;
if (is_array($val) && count($val) == 1) {
$data[$name] = $val[0];
} else {
$data[$name] = $val;
}
}
}
return ArrayData::create($data);
} | php | {
"resource": ""
} |
q6860 | SolrResultSet.getFacets | train | public function getFacets() {
if ($this->returnedFacets) {
return $this->returnedFacets;
}
$result = $this->getResult();
if (!isset($result->facet_counts)) {
return;
}
if (isset($result->facet_counts->exception)) {
// $this->logger->error($result->facet_counts->exception)
return array();
}
$elems = $result->facet_counts->facet_fields;
$facets = array();
foreach ($elems as $field => $values) {
$elemVals = array();
foreach ($values as $vname => $vcount) {
if ($vname == '_empty_') {
continue;
}
$r = new stdClass;
$r->Name = $vname;
$r->Query = $vname;
$r->Count = $vcount;
$elemVals[] = $r;
}
$facets[$field] = $elemVals;
}
// see if there's any query facets for things too
$query_elems = $result->facet_counts->facet_queries;
if ($query_elems) {
foreach ($query_elems as $vname => $count) {
if ($vname == '_empty_') {
continue;
}
list($field, $query) = explode(':', $vname);
$r = new stdClass;
$r->Type = 'query';
$r->Name = $vname;
$r->Query = $query;
$r->Count = $count;
$existing = isset($facets[$field]) ? $facets[$field] : array();
$existing[] = $r;
$facets[$field] = $existing;
}
}
$this->returnedFacets = $facets;
return $this->returnedFacets;
} | php | {
"resource": ""
} |
q6861 | Serializer.createSerializer | train | public static function createSerializer()
{
$normalizers = array(
new AccountNormalizer(),
new ActorNormalizer(),
new AttachmentNormalizer(),
new ContextNormalizer(),
new ContextActivitiesNormalizer(),
new DefinitionNormalizer(),
new DocumentDataNormalizer(),
new ExtensionsNormalizer(),
new InteractionComponentNormalizer(),
new LanguageMapNormalizer(),
new ObjectNormalizer(),
new ResultNormalizer(),
new StatementNormalizer(),
new StatementResultNormalizer(),
new TimestampNormalizer(),
new VerbNormalizer(),
new ArrayDenormalizer(),
new FilterNullValueNormalizer(new PropertyNormalizer()),
new PropertyNormalizer(),
);
$encoders = array(
new JsonEncoder(),
);
return new SymfonySerializer($normalizers, $encoders);
} | php | {
"resource": ""
} |
q6862 | AuthorizationController.sync | train | public function sync(Authorization $processor, $vendor, $package = null)
{
return $processor->sync($this, $vendor, $package);
} | php | {
"resource": ""
} |
q6863 | AuthorizationController.updateSucceed | train | public function updateSucceed($metric)
{
\resolve(Synchronizer::class)->handle();
$message = \trans('orchestra/control::response.acls.update');
return $this->redirectWithMessage(
\handles("orchestra::control/acl?name={$metric}"), $message
);
} | php | {
"resource": ""
} |
q6864 | AbstractTypeExtension.canHandleType | train | function canHandleType($value, ?\Plasma\ColumnDefinitionInterface $column): bool {
$cb = $this->filter;
return $cb($value, $column);
} | php | {
"resource": ""
} |
q6865 | TimePoint.compare | train | public function compare(TimePoint $timepoint)
{
$first = $this->date;
$second = $this->timePointToDateTime($timepoint);
if ($first < $second) {
return -1;
}
if ($first > $second) {
return 1;
}
return 0;
} | php | {
"resource": ""
} |
q6866 | FileUploader.file | train | public function file(UploadedFile $file)
{
$this->file = $file;
$this->filename = $file->getClientOriginalName();
$this->sanitizeFilename();
return $this;
} | php | {
"resource": ""
} |
q6867 | FileUploader.move | train | public function move()
{
// Make sure the filename is unique if makeFilenameUnique is set to true
if($this->makeFilenameUnique)
{
$this->getUniqueFilename();
}
if($this->_validate())
{
// Validation passed so create any directories and move the tmp file to the specified location.
$this->_createDirs();
if($this->file->isValid())
{
// This will also perform some validations on the upload.
$this->file->move($this->uploadDir, $this->filename);
}
else
{
throw new Exception($this->file->getErrorMessage());
}
}
return $this->getUploadPath();
} | php | {
"resource": ""
} |
q6868 | FileUploader.getUniqueFilename | train | public function getUniqueFilename()
{
$pathInfo = pathinfo($this->filename);
$filename = $pathInfo['filename'];
$extension = $pathInfo['extension'];
$increment = 1;
while($this->fileExists($filename . "_" . $increment, $extension))
{
$increment++;
}
$this->filename = $filename . "_" . $increment . '.' . $extension;
return $this;
} | php | {
"resource": ""
} |
q6869 | FileUploader._validate | train | private function _validate()
{
$this->checkOverwritePermission();
$this->checkHasValidUploadDirectory();
$this->checkFileSize();
$this->checkFileTypeIsAllowed();
$this->checkFileTypeIsNotBlocked();
return true;
} | php | {
"resource": ""
} |
q6870 | FileUploader.checkFileTypeIsAllowed | train | private function checkFileTypeIsAllowed()
{
if(count($this->allowedMimeTypes) > 0)
{
if(! in_array($this->file->getMimeType(), $this->allowedMimeTypes))
{
throw new InvalidFileTypeException("Invalid File Type: " . $this->file->getMimeType() . " has not been allowed");
}
}
} | php | {
"resource": ""
} |
q6871 | FileUploader.checkFileTypeIsNotBlocked | train | private function checkFileTypeIsNotBlocked()
{
if(in_array($this->file->getMimeType(), $this->blockedMimeTypes))
{
throw new InvalidFileTypeException("Invalid File Type: " . $this->file->getMimeType() . " type has been blocked");
}
} | php | {
"resource": ""
} |
q6872 | FileUploader.uploadDir | train | public function uploadDir($dir)
{
$this->uploadDir = $dir;
if(! $this->hasTrailingSlash())
{
$this->uploadDir .= "/";
}
return $this;
} | php | {
"resource": ""
} |
q6873 | GraphQLContext.theOperationInFile | train | public function theOperationInFile($filename)
{
$queryFile = sprintf('%s%s%s', self::$currentFeatureFile->getPath(), DIRECTORY_SEPARATOR, $filename);
if (file_exists($queryFile)) {
$file = new File($queryFile);
$this->client->setGraphQL(file_get_contents($file->getPathname()));
} else {
throw new FileNotFoundException(null, 0, null, $queryFile);
}
} | php | {
"resource": ""
} |
q6874 | GraphQLContext.theOperationNamedInFile | train | public function theOperationNamedInFile($queryName, $file)
{
// TODO: add support for fragments
// if a fragment is not used in some operation in the same file a error is thrown
$this->theOperationInFile($file);
$this->operationName = $queryName;
if ($this->client->getGraphQL()) {
// remove non necessary operations to avoid errors with unsettled variables
$pattern = '/(query|mutation|subscription)\s+(?!'.$queryName.'\s*[\({])(.+\n)+}\n*/';
$this->client->setGraphQL(preg_replace($pattern, null, $this->client->getGraphQL()));
}
if ($queryName) {
if (strpos($this->client->getGraphQL(), $queryName) === false) {
throw new \RuntimeException(sprintf('Does not exist any operation called "%s" in "%s"', $queryName, $file));
}
}
} | php | {
"resource": ""
} |
q6875 | GraphQLContext.setVariableEqualTo | train | public function setVariableEqualTo($path, $value)
{
$accessor = new PropertyAccessor();
$variables = $this->client->getVariables();
$accessor->setValue($variables, sprintf("[%s]", $path), $value);
$this->client->setVariables($variables);
} | php | {
"resource": ""
} |
q6876 | GraphQLContext.debugLastQuery | train | public function debugLastQuery()
{
if ($this->client->getGraphQL()) {
/** @var Response $response */
$response = $this->client->getResponse();
$content = $response->getContent();
$json = @json_decode($content, true);
$error = $response->getStatusCode() >= 400;
if ($json && isset($json['errors'])) {
$error = true;
}
$bg = $error ? 41 : 42;
print_r("\n\n");
print_r("\033[{$bg}m-------------------- RESPONSE ----------------------\033[0m\n\n");
print_r(sprintf("STATUS: [%s] %s \n", $response->getStatusCode(), Response::$statusTexts[$response->getStatusCode()] ?? 'Unknown Status'));
if ($json) {
$output = json_encode($json, JSON_PRETTY_PRINT);
} else {
$output = $content;
}
print_r($output);
print_r("\n\n");
print_r("\033[46m------------------- VARIABLES-----------------------\033[0m\n\n");
$variables = $this->client->getVariables() ?? null;
print_r(json_encode($variables, JSON_PRETTY_PRINT));
$query = $this->client->getGraphQL() ?? null;
$type = 'QUERY';
if (preg_match('/^\s*mutation/', $query)) {
$type = 'MUTATION';
}
print_r("\n\n\033[43m----------------------- $type ---------------------\033[0m\n\n");
print_r($query ?? null);
print_r("\n\n");
print_r("-----------------------------------------------------\n\n");
ob_flush();
} else {
throw new \RuntimeException('Does not exist any executed query on current test, try use this method after "send" the query.');
}
} | php | {
"resource": ""
} |
q6877 | ContaoTranslatorFactory.createService | train | public function createService()
{
$translator = new TranslatorChain();
$translator->add(new LangArrayTranslator($this->dispatcher));
$initializer = new TranslatorInitializer($this->dispatcher);
return $initializer->initialize($translator);
} | php | {
"resource": ""
} |
q6878 | SubreportRenderControl.load | train | private function load(): void
{
// Skip if it's already loaded
if ($this->state === self::STATE_LOADED) return;
// Attach parameters (only if we have some)
if ($this->parameters !== []) {
// Attach parameters to form
$this['parametersForm']->setDefaults($this->parameters);
// Attach parameters to subreport
$this->subreport->attach($this->parameters);
}
// Compile (fetch data)
$this->subreport->compile();
// Preprocess (only if it is not already)
if (!$this->subreport->isState(Subreport::STATE_PREPROCESSED)) {
$this->subreport->preprocess();
}
// Change inner state
$this->state = self::STATE_LOADED;
} | php | {
"resource": ""
} |
q6879 | Client.call | train | public function call(string $method, array $arguments): Response
{
try {
return $this->request('GET', $method, [
'query' => $arguments
]);
} catch (\Exception $e) {
throw new ClientException($e->getMessage(), $e->getCode(), $e);
}
} | php | {
"resource": ""
} |
q6880 | Client.getHandlerStack | train | protected function getHandlerStack()
{
$handlerStack = HandlerStack::create($this->getHandler());
$this->configureHandlerStack($handlerStack);
return $handlerStack;
} | php | {
"resource": ""
} |
q6881 | Client.getApiKeyMiddleware | train | protected function getApiKeyMiddleware()
{
$handleRequest = function (RequestInterface $request) {
return $request->withUri(Uri::withQueryValue(
$request->getUri(),
static::PARAM_API_KEY,
$this->apiKey
));
};
return Middleware::mapRequest($handleRequest);
} | php | {
"resource": ""
} |
q6882 | TagFigTrans.fig_trans | train | private function fig_trans(Context $context) {
//If a @source attribute is specified, and is equal to
//the view's target language, then don't bother translating:
//just render the contents.
//However, even if the fig:trans tag does not specify a "source" attribute,
//we may look up the optional default trans source attribute
//defined at the template level.
$source = $this->getAttribute('source', $context->getView()->defaultTransSource);
//The $key is also needed in logging below, even if
//source = view's language, in case of missing value,
//so this is a good time to read it.
$key = $this->getAttribute('key', null);
$dictionaryName = $this->getAttribute('dict', null);
// Do we have a dictionary ?
$dictionary = $context->getDictionary($dictionaryName);
// Maybe not, but at this stage it is not important, I only need
// to know its source
$dicSource = ($dictionary ? $dictionary->getSource() : null);
if (
( (null == $source) && //no source on the trans tag
($dicSource == $context->getView()->getLanguage()) )
||
($source == $context->getView()->getLanguage()) ) {
$context->pushDoNotRenderFigParams();
$value = $this->renderChildren($context /*Do not render fig:param immediate children */);
$context->popDoNotRenderFigParams();
} else {
//Cross-language dictionary mechanism:
if(null == $key) {
//Missing @key attribute : consider the text contents as the key.
//throw new SyntaxErrorException($this->getCurrentFile()->getFilename(), $this->xmlLineNumber, $this->name, 'Missing @key attribute.');
$key = $this->renderChildren($context);
}
//Ask current context to translate key:
$value = $context->translate($key, $dictionaryName);
}
//Fetch the parameters specified as immediate children
//of the macro call : <fig:param name="" value=""/>
//TODO: Currently, the <fig:param> of a macro call cannot hold any fig:cond or fig:case conditions.
$arguments = array();
foreach ($this->children as $child) {
if($child instanceof ViewElementTag) {
if($child->name == $context->view->figNamespace . 'param') {
//If param is specified with an immediate value="" attribute :
if(isset($child->attributes['value'])) {
$arguments[$child->attributes['name']] = $this->evaluate($context, $child->attributes['value']);
}
//otherwise, the actual value is not scalar but is
//a nodeset in itself. Let's pre-render it and use it as text for the argument.
else {
$arguments[$child->attributes['name']] = $child->render($context);
}
}
}
}
//We must now perform the replacements of the parameters of the translation,
//which are written in the shape : {paramName}
//and are specified as extra attributes of the fig:trans tag, or child fig:param tags
//(fig:params override inline attributes).
$matches = array();
while(preg_match('/{([^}]+)}/', $value, $matches)) {
$attributeName = $matches[1];
//If there is a corresponding fig:param, use it:
if(array_key_exists($attributeName, $arguments)) {
$attributeValue = $arguments[$attributeName];
}
//Otherwise, use the inline attribute.
else {
$attributeValue = $this->evalAttribute($context, $attributeName);
}
$value = str_replace('{' . $attributeName . '}', $attributeValue, $value);
}
//If the translated value is empty (ie. we did find an entry in the proper dictionary file,
//but this entry has an empty value), it means that the entry remains to be translated by the person in charge.
//So in the meantime we output the key.
if($value == '') {
$value = $key;
// TODO: One might want to be notified, either by an exception or another mechanism (Context logging?).
}
return $value;
} | php | {
"resource": ""
} |
q6883 | GUID.createFromHex | train | public static function createFromHex($hexString): ?GUID
{
$hexString = str_replace(static::$searchChars, static::$replaceChars, $hexString);
if (!preg_match('/^[0-9A-Fa-f]{32}$/', $hexString)) {
return null;
}
$bin = pack('H*', $hexString);
if (!static::validate($bin)) {
return null;
}
return new static($bin);
} | php | {
"resource": ""
} |
q6884 | GUID.create | train | public static function create(): GUID
{
$guid = \random_bytes(16);
// Reset version byte to version 4 (0100)
$guid[6] = chr(ord($guid[6]) & 0x0f | 0x40);
$guid[8] = chr(ord($guid[8]) & 0x3f | 0x80);
return new static($guid);
} | php | {
"resource": ""
} |
q6885 | GUID.validate | train | protected static function validate($guid)
{
if (ByteString::strlen($guid) !== 16) {
return false;
}
$byte = $guid[6];
$byte = (ord($byte) & 0xF0) >> 4;
if ($byte !== 4) {
return false;
}
$byte = $guid[8];
$byte = (ord($byte) & 0xC0);
if ($byte !== 0x80) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q6886 | GUID.format | train | public function format($format = self::STANDARD)
{
$hexStr = strtolower($this->asHex());
$parts = [
substr($hexStr, 0, 8),
substr($hexStr, 8, 4),
substr($hexStr, 12, 4),
substr($hexStr, 16, 4),
substr($hexStr, 20)
];
if ($format & self::UPPERCASE) {
$parts = array_map(function ($v) {
return strtoupper($v);
}, $parts);
}
$separator = '';
if ($format & self::HYPHENATED) {
$separator = self::SEPERATOR_HYPHEN;
}
$formatted = implode($separator, $parts);
if ($format & self::BRACES) {
$formatted = sprintf('{%s}', $formatted);
}
return $formatted;
} | php | {
"resource": ""
} |
q6887 | GUID.asHex | train | public function asHex()
{
$normalizer = function ($val) {
return str_pad(strtoupper(dechex($val)), 2, '0', STR_PAD_LEFT);
};
$out = unpack('C*', $this->guid);
$out = array_map($normalizer, $out);
$out = implode('', $out);
return $out;
} | php | {
"resource": ""
} |
q6888 | AbstractCommand.getSynopsis | train | public function getSynopsis(bool $short = false): string
{
$key = $short ? 'short' : 'long';
if (!isset($this->synopsis[$key]))
{
$this->synopsis[$key] = trim(sprintf('%s %s', $this->getName(), $this->getDefinition()->getSynopsis($short)));
}
return $this->synopsis[$key];
} | php | {
"resource": ""
} |
q6889 | AbstractCommand.setDefinition | train | public function setDefinition($definition)
{
if ($definition instanceof InputDefinition)
{
$this->definition = $definition;
}
else
{
$this->definition->setDefinition($definition);
}
$this->applicationDefinitionMerged = false;
} | php | {
"resource": ""
} |
q6890 | DeprecationAdviser.dump | train | public function dump()
{
$message = '';
if (!empty($this->warnings)) {
uasort(
$this->warnings,
function ($a, $b) {
if (count($a) === count($b)) {
return 0;
}
return (count($a) > count($b)) ? -1 : 1;
}
);
foreach ($this->warnings as $message => $warnings) {
$count = count($warnings);
print_r(sprintf("\n\033[0;30m\033[43m %sx: %s\033[0m\n", $count, $message));
}
}
return $message;
} | php | {
"resource": ""
} |
q6891 | ConfigurationReader.read | train | public function read($path)
{
$data = $this->readJson($path);
$this->validator()->validate($data);
return $this->createConfiguration($data);
} | php | {
"resource": ""
} |
q6892 | ConfigurationReader.readJson | train | protected function readJson($path)
{
$jsonData = @file_get_contents($path);
if (false === $jsonData) {
throw new ConfigurationReadException($path);
}
$data = json_decode($jsonData);
$jsonError = json_last_error();
if (JSON_ERROR_NONE !== $jsonError) {
throw new InvalidJsonException($path, $jsonError);
}
return new ObjectAccess($data);
} | php | {
"resource": ""
} |
q6893 | ConfigurationReader.createConfiguration | train | protected function createConfiguration(ObjectAccess $data)
{
$autoloadData = new ObjectAccess(
$data->getDefault('autoload', (object) array())
);
return new Configuration(
$data->getDefault('name'),
$data->getDefault('description'),
$data->getDefault('version'),
$data->getDefault('type'),
$data->getDefault('keywords'),
$data->getDefault('homepage'),
$this->createTime($data->getDefault('time')),
$this->arrayize($data->getDefault('license')),
$this->createAuthors($data->getDefault('authors')),
$this->createSupport($data->getDefault('support')),
$this->objectToArray($data->getDefault('require')),
$this->objectToArray($data->getDefault('require-dev')),
$this->objectToArray($data->getDefault('conflict')),
$this->objectToArray($data->getDefault('replace')),
$this->objectToArray($data->getDefault('provide')),
$this->objectToArray($data->getDefault('suggest')),
$this->createAutoloadPsr($autoloadData->getDefault('psr-4')),
$this->createAutoloadPsr($autoloadData->getDefault('psr-0')),
$autoloadData->getDefault('classmap'),
$autoloadData->getDefault('files'),
$data->getDefault('include-path'),
$data->getDefault('target-dir'),
$this->createStability($data->getDefault('minimum-stability')),
$data->getDefault('prefer-stable'),
$this->createRepositories((array) $data->getDefault('repositories')),
$this->createProjectConfiguration($data->getDefault('config')),
$this->createScripts($data->getDefault('scripts')),
$data->getDefault('extra'),
$data->getDefault('bin'),
$this->createArchiveConfiguration($data->getDefault('archive')),
$data->data()
);
} | php | {
"resource": ""
} |
q6894 | ConfigurationReader.createAuthors | train | protected function createAuthors(array $authors = null)
{
if (null !== $authors) {
foreach ($authors as $index => $author) {
$authors[$index] = $this->createAuthor(
new ObjectAccess($author)
);
}
}
return $authors;
} | php | {
"resource": ""
} |
q6895 | ConfigurationReader.createAuthor | train | protected function createAuthor(ObjectAccess $author)
{
return new Author(
$author->get('name'),
$author->getDefault('email'),
$author->getDefault('homepage'),
$author->getDefault('role'),
$author->data()
);
} | php | {
"resource": ""
} |
q6896 | ConfigurationReader.createSupport | train | protected function createSupport(stdClass $support = null)
{
if (null !== $support) {
$supportData = new ObjectAccess($support);
$support = new SupportInformation(
$supportData->getDefault('email'),
$supportData->getDefault('issues'),
$supportData->getDefault('forum'),
$supportData->getDefault('wiki'),
$supportData->getDefault('irc'),
$supportData->getDefault('source'),
$supportData->data()
);
}
return $support;
} | php | {
"resource": ""
} |
q6897 | ConfigurationReader.createAutoloadPsr | train | protected function createAutoloadPsr(stdClass $autoloadPsr = null)
{
if (null !== $autoloadPsr) {
$autoloadPsr = $this->objectToArray($autoloadPsr);
foreach ($autoloadPsr as $namespace => $paths) {
$autoloadPsr[$namespace] = $this->arrayize($paths);
}
}
return $autoloadPsr;
} | php | {
"resource": ""
} |
q6898 | ConfigurationReader.createStability | train | protected function createStability($stability)
{
if (null !== $stability) {
$stability = Stability::memberByValue($stability, false);
}
return $stability;
} | php | {
"resource": ""
} |
q6899 | ConfigurationReader.createRepositories | train | protected function createRepositories(array $repositories = null)
{
if (null !== $repositories) {
foreach ($repositories as $index => $repository) {
$repositories[$index] = $this->createRepository(
new ObjectAccess($repository)
);
}
}
return $repositories;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.