_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7600 | ItemCollection.add | train | public function add($data = null) {
if (is_array($data)) {
foreach ($data as $elem) {
$this->add($elem);
}
} else {
$guid = $this->toGUID($data);
if ($guid) {
array_push($this->guids, $guid);
sort($this->guids);
}
}
return $this;
} | php | {
"resource": ""
} |
q7601 | ItemCollection.toGUID | train | protected function toGUID($entity = null) {
if ($entity instanceof ElggEntity) {
return (int) $entity->getGUID();
} else if ($this->exists($entity)) {
return (int) $entity;
}
return false;
} | php | {
"resource": ""
} |
q7602 | Product.generate | train | public function generate($pageTitle)
{
$tags = parent::generate($pageTitle);
$product = $this->registry->registry('current_product');
if (!$product instanceof MagentoProduct) {
$this->logger->error('Could not retrieve mage product from registry');
return $tags;
}
/** @var \Magento\Store\Model\Store $store */
$store = $this->storeManager->getStore();
$image = $product->getMediaGalleryImages()->getFirstItem();
$imageUrl = is_object($image) ? $image->getData('url') : '';
$name = $product->getName();
$description = $product->getDescription();
$availableText = $product->isInStock() ? 'instock' : 'oos';
$categoryName = $this->getCategoryName();
$defaultCurrency = $store->getCurrentCurrency()->getCode();
$eanIdentifier = $this->config->getConfigByPath(ExportInterface::PATH_PROD_EAN_CODE)->getValue();
$ean = (string) $product->getData($eanIdentifier);
$taxClassId = $product->getTaxClassId();
$storeId = $store->getId();
$taxRate = $this->taxCalculation->getDefaultCalculatedRate($taxClassId, null, $storeId);
$priceIsGross = $this->taxConfig->priceIncludesTax($this->storeManager->getStore());
$price = $product->getFinalPrice();
$priceNet = $priceIsGross ? round($price / (1 + $taxRate), 2) : round($price, 2);
$priceGross = !$priceIsGross ? round($price * (1 + $taxRate), 2) : round($price, 2);
$productTags = [
TagGenerator::SITE_PARAMETER_PRODUCT_IMAGE => $imageUrl,
TagGenerator::SITE_PARAMETER_PRODUCT_NAME => $name,
TagGenerator::SITE_PARAMETER_PRODUCT_DESCRIPTION_SHORT => $description,
TagGenerator::SITE_PARAMETER_PRODUCT_EAN => $ean,
TagGenerator::SITE_PARAMETER_PRODUCT_AVAILABILITY => $availableText,
TagGenerator::SITE_PARAMETER_PRODUCT_CATEGORY => $categoryName,
TagGenerator::SITE_PARAMETER_PRODUCT_PRICE => $priceGross,
TagGenerator::SITE_PARAMETER_PRODUCT_PRETAX_PRICE => $priceNet
];
if ($priceGross || $priceNet) {
$productTags[TagGenerator::SITE_PARAMETER_PRODUCT_CURRENCY] = $defaultCurrency;
$productTags[TagGenerator::SITE_PARAMETER_PRODUCT_PRETAX_CURRENCY] = $defaultCurrency;
}
$tags = array_merge($tags, $productTags);
return $tags;
} | php | {
"resource": ""
} |
q7603 | AbstractLiteral.toNQuads | train | public function toNQuads()
{
$string = '"'.$this->encodeStringLitralForNQuads($this->getValue()).'"';
if ($this->getLanguage() !== null) {
$string .= '@'.$this->getLanguage();
} elseif ($this->getDatatype() !== null) {
$string .= '^^<'.$this->getDatatype().'>';
}
return $string;
} | php | {
"resource": ""
} |
q7604 | HTTPHelper.getHTTPMethods | train | public static function getHTTPMethods() {
return[
self::HTTP_METHOD_DELETE,
self::HTTP_METHOD_GET,
self::HTTP_METHOD_HEAD,
self::HTTP_METHOD_OPTIONS,
self::HTTP_METHOD_PATCH,
self::HTTP_METHOD_POST,
self::HTTP_METHOD_PUT,
];
} | php | {
"resource": ""
} |
q7605 | HTTPHelper.getHTTPStatus | train | public static function getHTTPStatus() {
return [
self::HTTP_STATUS_CONTINUE,
self::HTTP_STATUS_SWITCHING_PROTOCOLS,
self::HTTP_STATUS_PROCESSING,
self::HTTP_STATUS_OK,
self::HTTP_STATUS_CREATED,
self::HTTP_STATUS_ACCEPTED,
self::HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION,
self::HTTP_STATUS_NO_CONTENT,
self::HTTP_STATUS_RESET_CONTENT,
self::HTTP_STATUS_PARTIAL_CONTENT,
self::HTTP_STATUS_MULTI_STATUS,
self::HTTP_STATUS_ALREADY_REPORTED,
self::HTTP_STATUS_IM_USED,
self::HTTP_STATUS_MULTIPLE_CHOICES,
self::HTTP_STATUS_MOVED_PERMANENTLY,
self::HTTP_STATUS_MOVED_TEMPORARILY,
self::HTTP_STATUS_SEE_OTHER,
self::HTTP_STATUS_NOT_MODIFIED,
self::HTTP_STATUS_USE_PROXY,
self::HTTP_STATUS_TEMPORARY_REDIRECT,
self::HTTP_STATUS_PERMANENT_REDIRECT,
self::HTTP_STATUS_BAD_REQUEST,
self::HTTP_STATUS_UNAUTHORIZED,
self::HTTP_STATUS_PAYMENT_REQUIRED,
self::HTTP_STATUS_FORBIDDEN,
self::HTTP_STATUS_NOT_FOUND,
self::HTTP_STATUS_METHOD_NOT_ALLOWED,
self::HTTP_STATUS_NOT_ACCEPTABLE,
self::HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED,
self::HTTP_STATUS_REQUEST_TIME_OUT,
self::HTTP_STATUS_CONFLICT,
self::HTTP_STATUS_GONE,
self::HTTP_STATUS_LENGTH_REQUIRED,
self::HTTP_STATUS_PRECONDITION_FAILED,
self::HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE,
self::HTTP_STATUS_REQUEST_URI_TOO_LONG,
self::HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
self::HTTP_STATUS_REQUESTED_RANGE_UNSATISFIABLE,
self::HTTP_STATUS_EXPECTATION_FAILED,
self::HTTP_STATUS_UNPROCESSABLE_ENTITY,
self::HTTP_STATUS_LOCKED,
self::HTTP_STATUS_METHOD_FAILURE,
self::HTTP_STATUS_UPGRADE_REQUIRED,
self::HTTP_STATUS_PRECONDITION_REQUIRED,
self::HTTP_STATUS_TOO_MANY_REQUESTS,
self::HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE,
self::HTTP_STATUS_INTERNAL_SERVER_ERROR,
self::HTTP_STATUS_NOT_IMPLEMENTED,
self::HTTP_STATUS_BAD_GATEWAY_OU_PROXY_ERROR,
self::HTTP_STATUS_SERVICE_UNAVAILABLE,
self::HTTP_STATUS_GATEWAY_TIME_OUT,
self::HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
self::HTTP_STATUS_VARIANT_ALSO_NEGOTIATES,
self::HTTP_STATUS_INSUFFICIENT_STORAGE,
self::HTTP_STATUS_LOOP_DETECTED,
self::HTTP_STATUS_NOT_EXTENDED,
self::HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED,
];
} | php | {
"resource": ""
} |
q7606 | SFTPClient.connect | train | public function connect() {
$host = $this->getAuthenticator()->getHost();
$port = $this->getAuthenticator()->getPort();
$this->setConnection(ssh2_connect($host, $port));
if (false === $this->getConnection()) {
throw $this->newFTPException("connection failed");
}
return $this;
} | php | {
"resource": ""
} |
q7607 | SFTPClient.getSFTP | train | private function getSFTP() {
if (null === $this->sftp) {
$this->sftp = ssh2_sftp($this->getConnection());
}
return $this->sftp;
} | php | {
"resource": ""
} |
q7608 | SFTPClient.login | train | public function login() {
$username = $this->getAuthenticator()->getPasswordAuthentication()->getUsername();
$password = $this->getAuthenticator()->getPasswordAuthentication()->getPassword();
if (false === ssh2_auth_password($this->getConnection(), $username, $password)) {
throw $this->newFTPException("login failed");
}
return $this;
} | php | {
"resource": ""
} |
q7609 | SFTPClient.rename | train | public function rename($oldName, $newName) {
if (false === ssh2_sftp_rename($this->getSFTP(), $oldName, $newName)) {
throw $this->newFTPException(sprintf("rename %s into %s failed", $oldName, $newName));
}
return $this;
} | php | {
"resource": ""
} |
q7610 | Upgrader.pre_install | train | public function pre_install( $bool, $hook_extra ) {
if ( ! isset( $hook_extra['theme'] ) || $this->theme_name !== $hook_extra['theme'] ) {
return $bool;
}
global $wp_filesystem;
$theme_dir = trailingslashit( get_theme_root( $this->theme_name ) ) . $this->theme_name;
if ( ! $wp_filesystem->is_writable( $theme_dir ) ) {
return new \WP_Error();
}
return $bool;
} | php | {
"resource": ""
} |
q7611 | Upgrader.source_selection | train | public function source_selection( $source, $remote_source, $install, $hook_extra ) {
if ( ! isset( $hook_extra['theme'] ) || $this->theme_name !== $hook_extra['theme'] ) {
return $source;
}
global $wp_filesystem;
$slash_count = substr_count( $this->theme_name, '/' );
if ( $slash_count ) {
add_action( 'switch_theme', [ $this, '_re_activate' ], 10, 3 );
}
$source_theme_dir = untrailingslashit( WP_CONTENT_DIR ) . '/upgrade';
if ( $wp_filesystem->is_writable( $source_theme_dir ) && $wp_filesystem->is_writable( $source ) ) {
$newsource = trailingslashit( $source_theme_dir ) . trailingslashit( $this->theme_name );
if ( $wp_filesystem->move( $source, $newsource, true ) ) {
return $newsource;
}
}
return new \WP_Error();
} | php | {
"resource": ""
} |
q7612 | StartRecordFormatParser.parseEntity | train | public function parseEntity(StartRecordFormat $entity) {
$output = [
$this->encodeInteger($entity->getVersionRecordStructure(), 6),
$this->encodeInteger($entity->getFacilityNumber(), 7),
$this->encodeDate($entity->getDateFile()),
$this->encodeInteger($entity->getNumberRecords(), 5),
$this->encodeString($entity->getCurrency(), 6),
];
return implode(";", $output);
} | php | {
"resource": ""
} |
q7613 | HashTable.onConstruct | train | public function onConstruct($app)
{
//if not null
if (!is_null($app)) {
$key = $this->settingsKey;
$this->$key = $app;
}
} | php | {
"resource": ""
} |
q7614 | HashTable.getSettingsKey | train | public function getSettingsKey(): string
{
$key = $this->settingsKey;
if (empty($this->$key)) {
throw new Exception("No settings key is set on the constructor");
}
return $this->$key;
} | php | {
"resource": ""
} |
q7615 | HashTable.get | train | public function get(string $key)
{
$hash = self::findFirst([
'conditions' => "{$this->settingsKey} = ?0 and key = ?1",
'bind' => [$this->getSettingsKey(), $key]
]);
if ($hash) {
return $hash->value;
}
return null;
} | php | {
"resource": ""
} |
q7616 | HashTable.set | train | public function set(string $key, string $value) : self
{
if (!$setting = $this->get($key)) {
$setting = new self($this->getSettingsKey());
}
$setting->key = $key;
$setting->value = $value;
if (!$setting->save()) {
throw new Exception(current($setting->getMessages()));
}
return $setting;
} | php | {
"resource": ""
} |
q7617 | Virtuoso.openConnection | train | protected function openConnection()
{
// connection still closed
if (null === $this->connection) {
// check for dsn parameter. it is usually the ODBC identifier, e.g. VOS.
// for more information have a look into /etc/odbc.ini (*NIX systems)
if (false === isset($this->configuration['dsn'])) {
throw new \Exception('Parameter dsn is not set.');
}
// check for username parameter
if (false === isset($this->configuration['username'])) {
throw new \Exception('Parameter username is not set.');
}
// check for password parameter
if (false === isset($this->configuration['password'])) {
throw new \Exception('Parameter password is not set.');
}
/*
* Setup ODBC connection using PDO-ODBC
*/
$this->connection = new \PDO(
'odbc:'.(string) $this->configuration['dsn'],
(string) $this->configuration['username'],
(string) $this->configuration['password']
);
$this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
return $this->connection;
} | php | {
"resource": ""
} |
q7618 | Virtuoso.sqlQuery | train | public function sqlQuery($queryString)
{
try {
// execute query
$query = $this->connection->prepare(
$queryString,
[\PDO::ATTR_CURSOR => \PDO::CURSOR_FWDONLY]
);
$query->execute();
return $query;
} catch (\PDOException $e) {
throw new \Exception($e->getMessage());
}
} | php | {
"resource": ""
} |
q7619 | Virtuoso.transformEntryToNode | train | public function transformEntryToNode($entry)
{
/*
* An $entry looks like:
* array(
* 'type' => 'uri',
* 'value' => '...'
* )
*/
// it seems that for instance Virtuoso returns type=literal for bnodes,
// so we manually fix that here to avoid that problem, if other stores act
// the same
if (isset($entry['value'])
&& true === is_string($entry['value'])
&& false !== strpos($entry['value'], '_:')) {
$entry['type'] = 'bnode';
}
$newEntry = null;
switch ($entry['type']) {
/*
* Literal (language'd)
*/
case 'literal':
if (isset($entry['xml:lang'])) {
$newEntry = $this->nodeFactory->createLiteral(
$entry['value'],
'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString',
$entry['xml:lang']
);
// if a literal was created, but with no language information, it seems to confuse
// it when loading, therefor check if lang was explicitly given, otherwise handle it
// as it were a normal string.
} else {
$newEntry = $this->nodeFactory->createLiteral(
$entry['value']
);
}
break;
/*
* Typed-Literal
*/
case 'typed-literal':
$newEntry = $this->nodeFactory->createLiteral($entry['value'], $entry['datatype']);
break;
/*
* NamedNode
*/
case 'uri':
$newEntry = $this->nodeFactory->createNamedNode($entry['value']);
break;
/*
* BlankNode
*/
case 'bnode':
$newEntry = $this->nodeFactory->createBlankNode($entry['value']);
break;
default:
throw new \Exception('Unknown type given: '.$entry['type']);
break;
}
return $newEntry;
} | php | {
"resource": ""
} |
q7620 | Temp.getTmpPath | train | private function getTmpPath(): string
{
$tmpDir = sys_get_temp_dir();
if (!empty($this->prefix)) {
$tmpDir .= '/' . $this->prefix;
}
$tmpDir .= '/' . $this->id;
return $tmpDir;
} | php | {
"resource": ""
} |
q7621 | Temp.createTmpFile | train | public function createTmpFile(string $suffix = ''): \SplFileInfo
{
$file = uniqid();
if ($suffix) {
$file .= '-' . $suffix;
}
return $this->createFile($file);
} | php | {
"resource": ""
} |
q7622 | Temp.createFile | train | public function createFile(string $fileName): \SplFileInfo
{
$fileInfo = new \SplFileInfo($this->getTmpFolder() . '/' . $fileName);
$pathName = $fileInfo->getPathname();
if (!file_exists(dirname($pathName))) {
$this->fileSystem->mkdir(dirname($pathName), self::FILE_MODE);
}
$this->fileSystem->touch($pathName);
$this->fileSystem->chmod($pathName, self::FILE_MODE);
return $fileInfo;
} | php | {
"resource": ""
} |
q7623 | CoreServiceProvider.setupListeners | train | protected function setupListeners()
{
$subscriber = $this->app->make(CommandSubscriber::class);
$this->app->events->subscribe($subscriber);
} | php | {
"resource": ""
} |
q7624 | CoreServiceProvider.registerUpdateCommand | train | protected function registerUpdateCommand()
{
$this->app->singleton('command.appupdate', function (Container $app) {
$events = $app['events'];
return new AppUpdate($events);
});
} | php | {
"resource": ""
} |
q7625 | CoreServiceProvider.registerInstallCommand | train | protected function registerInstallCommand()
{
$this->app->singleton('command.appinstall', function (Container $app) {
$events = $app['events'];
return new AppInstall($events);
});
} | php | {
"resource": ""
} |
q7626 | CoreServiceProvider.registerResetCommand | train | protected function registerResetCommand()
{
$this->app->singleton('command.appreset', function (Container $app) {
$events = $app['events'];
return new AppReset($events);
});
} | php | {
"resource": ""
} |
q7627 | Retriever.getAllowedAddressCountries | train | public function getAllowedAddressCountries()
{
$allowedShippingCountries = $this->getAllowedShippingCountries();
$allowedShippingCountriesMap = array_map(
function ($country) {
return $country['country'];
},
$allowedShippingCountries
);
$allowedAddressCountries = [];
foreach ($this->mainShipHelper->getMageShippingCountries() as $addressCountry) {
$state = array_search($addressCountry, $allowedShippingCountriesMap, true);
$states = $state !== false ? $allowedShippingCountries[$state]['state'] : ['All'];
$allowedAddressCountries[] =
[
'country' => $addressCountry,
'state' => $states
];
}
return $allowedAddressCountries;
} | php | {
"resource": ""
} |
q7628 | Retriever.getAllowedShippingCountries | train | public function getAllowedShippingCountries()
{
$allowedShippingCountriesRaw = $this->getAllowedShippingCountriesRaw();
$allowedShippingCountries = [];
foreach ($allowedShippingCountriesRaw as $countryCode => $states) {
$states = empty($states) ? ['All' => true] : $states;
$states = array_filter(
array_keys($states),
function ($st) {
return is_string($st) ? $st : 'All';
}
);
$states = in_array('All', $states, true) ? ['All'] : $states;
array_walk(
$states,
function (&$state, $key, $country) {
$state = $state === 'All' ? $state : $country . '-' . $state;
},
$countryCode
);
$allowedShippingCountries[] =
[
'country' => $countryCode,
'state' => $states
];
}
return $allowedShippingCountries;
} | php | {
"resource": ""
} |
q7629 | Retriever.getAllowedShippingCountriesRaw | train | private function getAllowedShippingCountriesRaw()
{
$allowedCountries = array_fill_keys($this->mainShipHelper->getMageShippingCountries(), []);
$carriers = $this->mainShipHelper->getActiveCarriers();
$countries = [];
/**
* @var AbstractCarrier $carrier
*/
foreach ($carriers as $carrier) {
/* skip shopgate cause its a container carrier */
if ($carrier->getCarrierCode() === Shipping\Carrier\Shopgate::CODE) {
continue;
}
/* if any carrier is using the allowed_countries collection, merge this into the result */
if ($carrier->getConfigData('sallowspecific') === '0') {
$countries = array_merge_recursive($countries, $allowedCountries);
continue;
}
/* fetching active shipping targets from rates direct from the database */
if ($carrier->getCarrierCode() === Shipping\Carrier\TableRate::CODE) {
$collection = $this->tableRate->getTableRateCollection();
$countryHolder = [];
/** @var Tablerate $rate */
foreach ($collection as $rate) {
$countryHolder[$rate->getData('dest_country_id')][$rate->getData('dest_region') ? : 'All'] = true;
}
$countries = array_merge_recursive($countryHolder, $countries);
continue;
}
$specificCountries = $carrier->getConfigData('specificcountry');
$countries = array_merge_recursive(
$countries,
array_fill_keys(explode(",", $specificCountries), [])
);
}
foreach ($countries as $countryCode => $item) {
if (!isset($allowedCountries[$countryCode])) {
unset($countries[$countryCode]);
}
}
return $countries;
} | php | {
"resource": ""
} |
q7630 | BasicTriplePatternStore.getGraphs | train | public function getGraphs()
{
$graphs = [];
foreach (array_keys($this->statements) as $graphUri) {
if ('http://saft/defaultGraph/' == $graphUri) {
$graphs[$graphUri] = $this->nodeFactory->createNamedNode($graphUri);
}
}
return $graphs;
} | php | {
"resource": ""
} |
q7631 | BasicTriplePatternStore.getMatchingStatements | train | public function getMatchingStatements(Statement $statement, Node $graph = null, array $options = [])
{
if (null !== $graph) {
$graphUri = $graph->getUri();
// no graph information given, use default graph
} elseif (null === $graph && null === $statement->getGraph()) {
$graphUri = 'http://saft/defaultGraph/';
// no graph given, use graph information from $statement
} elseif (null === $graph && $statement->getGraph()->isNamed()) {
$graphUri = $statement->getGraph()->getUri();
// no graph given, use graph information from $statement
} elseif (null === $graph && false == $statement->getGraph()->isNamed()) {
$graphUri = 'http://saft/defaultGraph/';
}
if (false == isset($this->statements[$graphUri])) {
$this->statements[$graphUri] = [];
}
// if not default graph was requested
if ('http://saft/defaultGraph/' != $graphUri) {
return new StatementSetResultImpl($this->statements[$graphUri]);
// if default graph was requested, return matching statements from all graphs
} else {
$_statements = [];
foreach ($this->statements as $graphUri => $statements) {
foreach ($statements as $statement) {
if ('http://saft/defaultGraph/' == $graphUri) {
$graph = null;
} else {
$graph = $this->nodeFactory->createNamedNode($graphUri);
}
$_statements[] = $this->statementFactory->createStatement(
$statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
$graph
);
}
}
return new StatementSetResultImpl($_statements);
}
} | php | {
"resource": ""
} |
q7632 | Logger.writeLogs | train | private function writeLogs(): void
{
// Write logs
$fileName = $this->getApp()->getConfig()->getDirectory(ConfigInterface::DIR_VAR_LOGS) . '/Berlioz.log';
if (is_resource($this->fp) || is_resource($this->fp = @fopen($fileName, 'a'))) {
if (count($this->logs) > 0) {
foreach ($this->logs as $key => $log) {
if (!$log['written']) {
$line = sprintf("%-26s %-11s %s\n",
\DateTime::createFromFormat('U.u', number_format($log['time'], 6, '.', ''))
->format('Y-m-d H:i:s.u'),
'[' . $log['level'] . ']',
$log['message']);
if (@fwrite($this->fp, $line) !== false) {
$this->logs[$key]['written'] = true;
}
}
}
}
unset($log);
}
} | php | {
"resource": ""
} |
q7633 | Logger.needToLog | train | private function needToLog(string $level): bool
{
$logLevels = [LogLevel::EMERGENCY => 0,
LogLevel::ALERT => 1,
LogLevel::CRITICAL => 2,
LogLevel::ERROR => 3,
LogLevel::WARNING => 4,
LogLevel::NOTICE => 5,
LogLevel::INFO => 6,
LogLevel::DEBUG => 7];
if (isset($logLevels[$this->getApp()->getConfig()->getLogLevel()])) {
return isset($logLevels[$level]) && $logLevels[$level] <= $logLevels[$this->getApp()->getConfig()->getLogLevel()];
} else {
return false;
}
} | php | {
"resource": ""
} |
q7634 | Config.getCroppableSizes | train | public function getCroppableSizes() {
return array(
self::SIZE_LARGE,
self::SIZE_MEDIUM,
self::SIZE_SMALL,
self::SIZE_TINY,
self::SIZE_TOPBAR,
);
} | php | {
"resource": ""
} |
q7635 | DescriptorTrait.getSourceCodePath | train | public function getSourceCodePath()
{
if ($this->path === null) {
$path = [];
$current = $this;
while ($current && !$current instanceof FileDescriptor) {
$parent = $current->getContaining();
if (!$parent) {
throw new \Exception("parent cannot be null");
}
array_unshift($path, $current->getIndex());
// field number in definition:descriptor.proto
$name = $this->getClassShortName($current);
$pname = $this->getClassShortName($parent);
if (isset(self::$pathMap[$name])) {
if (is_int(self::$pathMap[$name])) {
$fieldNumber = self::$pathMap[$name];
} else {
if (isset(self::$pathMap[$name][$pname])) {
$fieldNumber = self::$pathMap[$name][$pname];
} else {
throw new \Exception("unimplemented situation $name $pname");
}
}
} else {
throw new \Exception("unimplemented situation $name $pname");
}
array_unshift($path, $fieldNumber);
$current = $parent;
}
$this->path = $path;
} else {
$path = $this->path;
}
return $path;
} | php | {
"resource": ""
} |
q7636 | RestController.response | train | protected function response($mixed): ResponseInterface
{
$statusCode = 200;
$reasonPhrase = '';
$headers['Content-Type'] = ['application/json'];
$body = new Stream();
// Booleans
if (is_bool($mixed)) {
if ($mixed == false) {
$statusCode = 500;
}
} else {
// Array
if (is_array($mixed)) {
$body->write(json_encode($mixed));
} else {
// Exception
if ($mixed instanceof \Exception) {
if ($mixed instanceof RoutingException) {
$statusCode = $mixed->getCode();
$reasonPhrase = $mixed->getMessage();
} else {
$statusCode = 500;
}
$body->write(json_encode(['errno' => $mixed->getCode(), 'error' => $mixed->getMessage()]));
} else {
// Object
if (is_object($mixed)) {
if ($mixed instanceof \JsonSerializable) {
$body->write(json_encode($mixed));
} else {
throw new BerliozException('Parameter object must implement \JsonSerializable interface to be converted');
}
} else {
$statusCode = 500;
}
}
}
}
// Response
return new Response($body, $statusCode, $headers, $reasonPhrase);
} | php | {
"resource": ""
} |
q7637 | Uploader.handle | train | public function handle($input = '', array $attributes = array(), array $options = array()) {
$result = array();
$uploads = $this->getUploads($input);
$filestore_prefix = elgg_extract('filestore_prefix', $options, $this->config->getDefaultFilestorePrefix());
unset($options['filestore_prefix']);
foreach ($uploads as $props) {
$upload = new \hypeJunction\Files\Upload($props);
$upload->save($attributes, $filestore_prefix);
if ($upload->file instanceof \ElggEntity && $upload->simpletype == 'image') {
$this->iconFactory->create($upload->file, null, $options);
}
$result[] = $upload;
}
return $result;
} | php | {
"resource": ""
} |
q7638 | Uploader.getFriendlyUploadError | train | public function getFriendlyUploadError($error_code = '') {
switch ($error_code) {
case UPLOAD_ERR_OK:
return '';
case UPLOAD_ERR_INI_SIZE:
$key = 'ini_size';
break;
case UPLOAD_ERR_FORM_SIZE:
$key = 'form_size';
break;
case UPLOAD_ERR_PARTIAL:
$key = 'partial';
break;
case UPLOAD_ERR_NO_FILE:
$key = 'no_file';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$key = 'no_tmp_dir';
break;
case UPLOAD_ERR_CANT_WRITE:
$key = 'cant_write';
break;
case UPLOAD_ERR_EXTENSION:
$key = 'extension';
break;
default:
$key = 'unknown';
break;
}
return elgg_echo("upload:error:$key");
} | php | {
"resource": ""
} |
q7639 | SubsiteMemberReportExtension.getSubsiteDescription | train | public function getSubsiteDescription()
{
$subsites = Subsite::accessible_sites(
$this->owner->config()->get('subsite_description_permission'),
true,
"Main site",
$this->owner
);
return implode(', ', $subsites->column('Title'));
} | php | {
"resource": ""
} |
q7640 | ContextIO.checkFilterParams | train | protected function checkFilterParams($givenParams, $validParams, $requiredParams = array())
{
$filteredParams = array();
foreach ($givenParams as $name => $value) {
if (in_array(strtolower($name), $validParams)) {
$filteredParams[ strtolower($name) ] = $value;
} else {
return false;
}
}
foreach ($requiredParams as $name) {
if (!array_key_exists(strtolower($name), $filteredParams)) {
return false;
}
}
return $filteredParams;
} | php | {
"resource": ""
} |
q7641 | WorkflowAbstract.initializeStates | train | protected function initializeStates()
{
if (!array_key_exists('states', $this->vars)) {
throw new WorkflowException("You must define some states:\n", 99, NULL);
}
//check if all the methods for each status is callable
$methods_not_implemented = '';
try {
foreach ($this->vars['states'] as $status) {
array_push($this->states, new Status($status));
/*
* The initial state will never be executed but only the transitions, therefore it will be excluded
* from the list of methods which must be implemented
*/
if (!method_exists($this, $status['name'])
&& $status['type'] != \Mothership\StateMachine\StatusInterface::TYPE_INITIAL
&& $status['type'] != \Mothership\StateMachine\StatusInterface::TYPE_EXCEPTION) {
$methods_not_implemented .= $status['name'] . "\n";
}
}
} catch (StatusException $ex) {
throw new WorkflowException("Error in one state of the workflow:\n" . $ex->getMessage(), 79);
}
if (strlen($methods_not_implemented) > 0) {
throw new WorkflowException(
"This methods are not implemented in the workflow:\n" .
$methods_not_implemented, 79, NULL
);
}
} | php | {
"resource": ""
} |
q7642 | WorkflowAbstract.setInitialState | train | public function setInitialState()
{
foreach ($this->states as $status) {
if ($status->getType() == StatusInterface::TYPE_INITIAL) {
$this->currentStatus = $status;
return;
}
}
throw new WorkflowException('No initial state found for the workflow', 90, NULL);
} | php | {
"resource": ""
} |
q7643 | WorkflowAbstract.getStatus | train | public function getStatus($name)
{
foreach ($this->states as $status) {
if ($status->getName() == $name) {
return $status;
}
}
throw new WorkflowException('No status found with the name ' . $name, 70, NULL);
} | php | {
"resource": ""
} |
q7644 | WorkflowAbstract.addToLog | train | protected function addToLog($state, $return = NULL)
{
$data['name'] = $state;
if (NULL !== $return) {
$data['return'] = $return;
}
$this->log[] = $data;
} | php | {
"resource": ""
} |
q7645 | WorkflowAbstract.run | train | public function run($args = [], $saveLog = false)
{
/**
* The state machine must be able to re run the same processes again.
*/
$this->reset();
// just store the arguments for external logic
$this->args = $args;
$continueExecution = true;
$nextState = $this->currentStatus;
/**
* Based on the initial state, the algorithm
* will try to execute each method until the
* final state is reached
*/
while (true === $continueExecution) {
if ($nextState->getType() == StatusInterface::TYPE_FINAL) {
$continueExecution = false;
}
/*
* Every workflow class has methods, which names are equal to the state names in the
* configuration file. By executing the methods, a return value can be given. This
* depends on your graph logic.
*
* However the return value will be seen as a condition for the NEXT state
* transition evaluation.
*/
try {
$this->executeMethod('preDispatch');
$condition = $this->executeMethod($nextState->getName());
$this->executeMethod('postDispatch');
} catch (\Exception $e) {
if (method_exists($this, 'exception')) {
call_user_func([$this, 'exception'], [$e]);
$nextState = $this->getNextStateFrom('exception');
$this->setState($nextState);
continue;
} else {
throw $e;
}
}
if (true === $saveLog) {
$this->addToLog($nextState->getName(), $condition);
}
/**
* Mark the execution to be stopped when the next state
* is StatusInterface::TYPE_FINAL.
*/
if (false === $continueExecution) {
continue;
}
$nextState = $this->getNextStateFrom($nextState->getName(), $condition);
/**
* Overwrite the current state. This does not affect
* the application logic but will be used for debugging purpose to be able
* to inspect the current state machine
*/
$this->setState($nextState);
}
if (true === $saveLog) {
return $this->log;
}
} | php | {
"resource": ""
} |
q7646 | WorkflowAbstract.executeMethod | train | private function executeMethod($method, $args = [])
{
if (method_exists($this, $method)) {
return call_user_func_array([$this, $method], $args);
}
} | php | {
"resource": ""
} |
q7647 | WorkflowAbstract.getStatusIndex | train | private function getStatusIndex($statusname)
{
$status_count = count($this->states);
for ($i = 0; $i < $status_count; ++$i) {
if ($this->states[$i]->getName() == $statusname) {
return $i;
}
}
} | php | {
"resource": ""
} |
q7648 | MemberReportExtension.getLastLoggedIn | train | public function getLastLoggedIn()
{
$lastTime = LoginAttempt::get()
->filter([
'MemberID' => $this->owner->ID,
'Status' => 'Success',
])
->sort('Created', 'DESC')
->first();
if ($lastTime) {
return $lastTime->dbObject('Created')->format(DBDatetime::ISO_DATETIME);
}
return _t(__CLASS__ . '.NEVER', 'Never');
} | php | {
"resource": ""
} |
q7649 | MemberReportExtension.getGroupsDescription | train | public function getGroupsDescription()
{
if (class_exists(Subsite::class)) {
Subsite::disable_subsite_filter(true);
}
// Get the member's groups, if any
$groups = $this->owner->Groups();
if ($groups->Count()) {
// Collect the group names
$groupNames = array();
foreach ($groups as $group) {
/** @var Group $group */
$groupNames[] = html_entity_decode($group->getTreeTitle());
}
// return a csv string of the group names, sans-markup
$result = preg_replace("#</?[^>]>#", '', implode(', ', $groupNames));
} else {
// If no groups then return a status label
$result = _t(__CLASS__ . '.NOGROUPS', 'Not in a Security Group');
}
if (class_exists(Subsite::class)) {
Subsite::disable_subsite_filter(false);
}
return $result;
} | php | {
"resource": ""
} |
q7650 | MemberReportExtension.getPermissionsDescription | train | public function getPermissionsDescription()
{
if (class_exists(Subsite::class)) {
Subsite::disable_subsite_filter(true);
}
$permissionsUsr = Permission::permissions_for_member($this->owner->ID);
$permissionsSrc = Permission::get_codes(true);
sort($permissionsUsr);
$permissionNames = array();
foreach ($permissionsUsr as $code) {
$code = strtoupper($code);
foreach ($permissionsSrc as $k => $v) {
if (isset($v[$code])) {
$name = empty($v[$code]['name'])
? _t(__CLASS__ . '.UNKNOWN', 'Unknown')
: $v[$code]['name'];
$permissionNames[] = $name;
}
}
}
$result = $permissionNames
? implode(', ', $permissionNames)
: _t(__CLASS__ . '.NOPERMISSIONS', 'No Permissions');
if (class_exists(Subsite::class)) {
Subsite::disable_subsite_filter(false);
}
return $result;
} | php | {
"resource": ""
} |
q7651 | SerializerFactoryEasyRdf.createSerializerFor | train | public function createSerializerFor($serialization)
{
$serializer = new SerializerEasyRdf($serialization);
if (in_array($serialization, $serializer->getSupportedSerializations())) {
return $serializer;
} else {
throw new \Exception(
'No serializer for requested serialization available: '.$serialization.'. '.
'Supported serializations are: '.implode(', ', $this->getSupportedSerializations())
);
}
} | php | {
"resource": ""
} |
q7652 | StringHelper.parseArray | train | public static function parseArray(array $values) {
// Initialize the output.
$output = [];
// Handle each value.
foreach ($values as $key => $value) {
// Check if the value is null.
if (null === $value) {
continue;
}
// Check if the value is an array.
if (true === is_array($value)) {
$buffer = trim(implode(" ", $value));
} else {
$buffer = trim($value);
}
// Check if the buffer is not empty.
if ("" !== $buffer) {
$output[] = $key . "=\"" . preg_replace("/\s+/", " ", $buffer) . "\"";
}
}
// Concatenates all attributes.
return implode(" ", $output);
} | php | {
"resource": ""
} |
q7653 | FlashBag.get | train | public function get(string $type): array
{
if (isset($this->messages[$type])) {
$messages = $this->messages[$type];
// Clear messages
$this->clear($type);
return $messages;
} else {
return [];
}
} | php | {
"resource": ""
} |
q7654 | FlashBag.clear | train | public function clear(string $type = null): FlashBag
{
if (is_null($type)) {
$this->messages = [];
} else {
if (isset($this->messages[$type])) {
unset($this->messages[$type]);
}
}
// Save into session
$this->saveToSession();
return $this;
} | php | {
"resource": ""
} |
q7655 | AbstractParser.decodeDate | train | protected function decodeDate($str) {
$date = DateTime::createFromFormat("!" . self::DATE_FORMAT, $str);
return false === $date ? null : $date;
} | php | {
"resource": ""
} |
q7656 | AbstractParser.decodeDateTime | train | protected function decodeDateTime($str) {
$date = DateTime::createFromFormat(self::DATETIME_FORMAT, $str);
return false === $date ? null : $date;
} | php | {
"resource": ""
} |
q7657 | AbstractParser.encodeDate | train | protected function encodeDate(DateTime $value = null) {
return null === $value ? "" : $value->format(self::DATE_FORMAT);
} | php | {
"resource": ""
} |
q7658 | AbstractParser.encodeDateTime | train | protected function encodeDateTime(DateTime $value = null) {
return null === $value ? "" : $value->format(self::DATETIME_FORMAT);
} | php | {
"resource": ""
} |
q7659 | AbstractParser.encodeInteger | train | protected function encodeInteger($value, $length) {
$format = "%'.0" . $length . "d";
$output = null === $value ? "" : sprintf($format, $value);
if ($length < strlen($output)) {
throw new TooLongDataException($value, $length);
}
return $output;
} | php | {
"resource": ""
} |
q7660 | AbstractParser.encodeString | train | protected function encodeString($value, $length = -1) {
if (-1 !== $length && $length < strlen($value)) {
throw new TooLongDataException($value, $length);
}
return "\"" . substr($value, 0, (-1 === $length ? strlen($value) : $length)) . "\"";
} | php | {
"resource": ""
} |
q7661 | CoverHandler.getIconSizes | train | protected static function getIconSizes($entity, $icon_sizes = array()) {
$type = $entity->getType();
$subtype = $entity->getSubtype();
$defaults = array(
'master' => array(
'h' => 370,
'w' => 1000,
'upscale' => true,
'square' => false,
)
);
if (is_array($icon_sizes)) {
$icon_sizes = array_merge($defaults, $icon_sizes);
} else {
$icon_sizes = $defaults;
}
return elgg_trigger_plugin_hook('entity:cover:sizes', $type, array(
'entity' => $entity,
'subtype' => $subtype,
), $icon_sizes);
} | php | {
"resource": ""
} |
q7662 | ParserEasyRdf.rdfPhpToStatementIterator | train | protected function rdfPhpToStatementIterator(array $rdfPhp)
{
$statements = [];
// go through all subjects
foreach ($rdfPhp as $subject => $predicates) {
// predicates associated with the subject
foreach ($predicates as $property => $objects) {
// object(s)
foreach ($objects as $object) {
/*
* Create subject node
*/
if (true === $this->RdfHelpers->simpleCheckURI($subject)) {
$s = $this->nodeFactory->createNamedNode($subject);
} elseif (true === $this->RdfHelpers->simpleCheckBlankNodeId($subject)) {
$s = $this->nodeFactory->createBlankNode($subject);
} else {
// should not be possible, because EasyRdf is able to check for invalid subjects.
throw new \Exception('Only URIs and blank nodes are allowed as subjects.');
}
/*
* Create predicate node
*/
if (true === $this->RdfHelpers->simpleCheckURI($property)) {
$p = $this->nodeFactory->createNamedNode($property);
} elseif (true === $this->RdfHelpers->simpleCheckBlankNodeId($property)) {
$p = $this->nodeFactory->createBlankNode($property);
} else {
// should not be possible, because EasyRdf is able to check for invalid predicates.
throw new \Exception('Only URIs and blank nodes are allowed as predicates.');
}
/*
* Create object node
*/
// URI
if ($this->RdfHelpers->simpleCheckURI($object['value'])) {
$o = $this->nodeFactory->createNamedNode($object['value']);
// datatype set
} elseif (isset($object['datatype'])) {
$o = $this->nodeFactory->createLiteral($object['value'], $object['datatype']);
// lang set
} elseif (isset($object['lang'])) {
$o = $this->nodeFactory->createLiteral(
$object['value'],
'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString',
$object['lang']
);
// if no information about the object was provided, assume its a simple string
} else {
$o = $this->nodeFactory->createLiteral($object['value']);
}
// build and add statement
$statements[] = $this->statementFactory->createStatement($s, $p, $o);
}
}
}
return $this->statementIteratorFactory->createStatementIteratorFromArray($statements);
} | php | {
"resource": ""
} |
q7663 | TableRate.getTableRateCollection | train | public function getTableRateCollection($storeId = null)
{
return $this->tableRateCollection->setWebsiteFilter($this->storeManager->getStore($storeId)->getWebsiteId());
} | php | {
"resource": ""
} |
q7664 | Plugin.init | train | public function init() {
elgg_register_plugin_hook_handler('entity:icon:url', 'all', new Handlers\EntityIconUrlHook());
elgg_register_plugin_hook_handler('graph:properties', 'all', new Handlers\PropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'user', new Handlers\UserPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'group', new Handlers\GroupPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'site', new Handlers\SitePropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'object', new Handlers\ObjectPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'object:blog', new Handlers\BlogPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'object:file', new Handlers\FilePropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'object:messages', new Handlers\MessagePropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'metadata', new Handlers\ExtenderPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'annotation', new Handlers\ExtenderPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'relationship', new Handlers\RelationshipPropertiesHook());
elgg_register_plugin_hook_handler('graph:properties', 'river:item', new Handlers\RiverPropertiesHook());
} | php | {
"resource": ""
} |
q7665 | Coupon.setCoupon | train | public function setCoupon()
{
foreach ($this->cart->getExternalCoupons() as $coupon) {
$this->setCouponToQuote($coupon);
}
return $this->quote;
} | php | {
"resource": ""
} |
q7666 | Actions.parseActionName | train | public function parseActionName() {
$uri = trim(get_input('__elgg_uri', ''), '/');
$segments = explode('/', $uri);
$handler = array_shift($segments);
if ($handler == 'action') {
return implode('/', $segments);
}
return $uri;
} | php | {
"resource": ""
} |
q7667 | Base.getItemsWithUnhandledErrors | train | public function getItemsWithUnhandledErrors()
{
$list = [];
foreach ($this->getItems() as $item) {
if ($item->hasUnhandledError()) {
$list[] = $item;
}
}
return $list;
} | php | {
"resource": ""
} |
q7668 | Base.setItems | train | public function setItems($list)
{
if (!is_array($list)) {
$this->items = null;
return;
}
$items = [];
foreach ($list as $index => $element) {
if ((!is_object($element) || !($element instanceof \ShopgateOrderItem)) && !is_array($element)) {
unset($list[$index]);
continue;
}
if ($element instanceof \ShopgateOrderItem) {
$element = $element->toArray();
}
$item = $this->itemFactory->create();
$item->loadArray($element);
$items[$item->getItemNumber()] = $item;
}
$this->items = $items;
} | php | {
"resource": ""
} |
q7669 | Base.customFieldsToArray | train | public function customFieldsToArray()
{
$result = [];
foreach ($this->getCustomFields() as $field) {
$result[$field->getInternalFieldName()] = $field->getValue();
}
return $result;
} | php | {
"resource": ""
} |
q7670 | Property.toArray | train | public function toArray() {
return array_filter(array(
'name' => $this->getAttributeName(),
'required' => $this->required,
'type' => $this->type,
'enum' => $this->getEnumOptions(),
'default' => $this->default,
));
} | php | {
"resource": ""
} |
q7671 | NotifyServiceProvider.registerNotifyService | train | private function registerNotifyService()
{
$this->singleton(Contracts\Notify::class, function ($app) {
/** @var \Illuminate\Config\Repository $config */
$config = $app['config'];
return new Notify(
$app[Contracts\SessionStore::class],
$config->get('notify.session.prefix', 'notifier')
);
});
} | php | {
"resource": ""
} |
q7672 | AbstractStatement.isConcrete | train | public function isConcrete()
{
if ($this->isQuad() && !$this->getGraph()->isConcrete()) {
return false;
}
return $this->getSubject()->isConcrete()
&& $this->getPredicate()->isConcrete()
&& $this->getObject()->isConcrete();
} | php | {
"resource": ""
} |
q7673 | AbstractStatement.toNQuads | train | public function toNQuads()
{
if ($this->isConcrete()) {
if ($this->isQuad()) {
return $this->getSubject()->toNQuads().' '.
$this->getPredicate()->toNQuads().' '.
$this->getObject()->toNQuads().' '.
$this->getGraph()->toNQuads().' .';
} else {
return $this->getSubject()->toNQuads().' '.
$this->getPredicate()->toNQuads().' '.
$this->getObject()->toNQuads().' .';
}
} else {
throw new \Exception('A Statement has to be concrete in N-Quads.');
}
} | php | {
"resource": ""
} |
q7674 | AbstractStatement.toNTriples | train | public function toNTriples()
{
if ($this->isConcrete()) {
return $this->getSubject()->toNQuads().' '.
$this->getPredicate()->toNQuads().' '.
$this->getObject()->toNQuads().' .';
} else {
throw new \Exception('A Statement has to be concrete in N-Triples.');
}
} | php | {
"resource": ""
} |
q7675 | AbstractStatement.equals | train | public function equals(Statement $toTest)
{
if ($toTest instanceof Statement &&
$this->getSubject()->equals($toTest->getSubject()) &&
$this->getPredicate()->equals($toTest->getPredicate()) &&
$this->getObject()->equals($toTest->getObject())
) {
if ($this->isQuad() && $toTest->isQuad() && $this->getGraph()->equals($toTest->getGraph())) {
return true;
} elseif ($this->isTriple() && $toTest->isTriple()) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q7676 | AbstractStatement.matches | train | public function matches(Statement $toTest)
{
if ($this->isConcrete() && $this->equals($toTest)) {
return true;
}
if ($toTest instanceof Statement &&
$this->getSubject()->matches($toTest->getSubject()) &&
$this->getPredicate()->matches($toTest->getPredicate()) &&
$this->getObject()->matches($toTest->getObject())
) {
if ($this->isQuad() && $toTest->isQuad() && $this->getGraph()->matches($toTest->getGraph())) {
return true;
} elseif ($this->isQuad() && $this->getGraph()->isPattern()) {
/*
* This case also matches the default graph i.e. if the graph is set to a variable it also matches the
* defaultgraph
*/
return true;
} elseif ($this->isTriple() && $toTest->isTriple()) {
return true;
}
/*
* TODO What should happen if $this->isTriple() is true, should this pattern match any $quad?
* This is the same descission, as, if the default graph should contain the union of all graphs!
*
* As I understand the situation with SPARQL it doesn't give a descission for this, but in the case that
* named graphs are included in a query only using FROM NAMED the default graph is empty per definiton.
* {@url http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#rdfDataset}
*/
}
return false;
} | php | {
"resource": ""
} |
q7677 | CommentStringBuffer.append | train | public function append($line, $newline = true, $indentOffset = 0)
{
$line = trim($line);
if (strlen($line) > 0) {
parent::append(
self::COMMENT_LINE_PREFIX . ' ' . $line, $newline, $indentOffset
);
} else {
parent::append(
self::COMMENT_LINE_PREFIX, $newline, $indentOffset
);
}
return $this;
} | php | {
"resource": ""
} |
q7678 | TypeReflection.getStandardizedType | train | public function getStandardizedType()
{
foreach ($this->getStandardizedTypes() as $standardizedType) {
if ($this->is($standardizedType)) {
return $standardizedType;
}
}
return self::UNKNOWN_TYPE;
} | php | {
"resource": ""
} |
q7679 | TypeReflection.getTypeMapping | train | private function getTypeMapping($standardizeType)
{
if(!isset($this->getTypeMappingList()[$standardizeType])){
throw new InvalidArgumentException(sprintf(
'$standardizeType not valid. Should be on of the values: %s. "%s" given.',
json_encode($this->getStandardizedTypes()),
$standardizeType
));
}
return $this->getTypeMappingList()[$standardizeType];
} | php | {
"resource": ""
} |
q7680 | Collection.shuffle | train | public function shuffle(): Collection
{
// Get keys and shuffle
$keys = array_keys($this->list);
shuffle($keys);
// Attribute shuffle keys to theirs values
$newList = [];
foreach ($keys as $key) {
$newList[$key] = $this->list[$key];
}
// Update list
$this->list = $newList;
return $this;
} | php | {
"resource": ""
} |
q7681 | Collection.offsetSet | train | public function offsetSet($offset, $value): void
{
if ($this->isValidEntity($value)) {
if (is_null($offset) || mb_strlen($offset) == 0) {
$this->list[] = $value;
} else {
$this->list[$offset] = $value;
}
} else {
throw new \InvalidArgumentException(sprintf('This collection does\'t accept this entity "%s"', gettype($value)));
}
} | php | {
"resource": ""
} |
q7682 | Collection.isValidEntity | train | public function isValidEntity($mixed): bool
{
if (empty($this->entityClasses)) {
return true;
} else {
if (is_object($mixed)) {
foreach ($this->entityClasses as $entityClass) {
if (is_a($mixed, $entityClass, true)) {
return true;
}
}
}
}
return false;
} | php | {
"resource": ""
} |
q7683 | Collection.mergeWith | train | public function mergeWith(Collection $collection): Collection
{
$calledClass = get_called_class();
if ($collection instanceof $calledClass) {
foreach ($collection as $key => $object) {
$this[$key] = $object;
}
} else {
throw new \InvalidArgumentException(sprintf('%s::mergeWith() method require an same type of Collection.', get_class($this)));
}
return $this;
} | php | {
"resource": ""
} |
q7684 | AddAppOnlySalesRuleCondition.execute | train | public function execute(\Magento\Framework\Event\Observer $observer)
{
$additional = $observer->getAdditional();
$conditions = (array) $additional->getConditions();
$conditions = array_merge_recursive($conditions, [$this->getShopgateCondition()]);
$additional->setConditions($conditions);
return $this;
} | php | {
"resource": ""
} |
q7685 | AbstractQuery.determineEntityType | train | public function determineEntityType($entity)
{
// remove braces at the beginning (only if $entity looks like <http://...>)
if ('<' == substr($entity, 0, 1)) {
$entity = str_replace(['>', '<'], '', $entity);
}
// checks if $entity is an URL
if (true === $this->rdfHelpers->simpleCheckURI($entity)) {
return 'uri';
// checks if ^^< is in $entity OR if $entity is surrounded by quotation marks
} elseif (false !== strpos($entity, '"^^<')
|| ('"' == substr($entity, 0, 1) && '"' == substr($entity, strlen($entity) - 1, 1))) {
return 'typed-literal';
// blank node
} elseif (false !== strpos($entity, '_:')) {
return 'blanknode';
// checks if $entity is an URL, which was written with prefix, such as rdfs:label
} elseif (false !== strpos($entity, ':')) {
return 'uri';
// checks if "@ is in $entity
} elseif (false !== strpos($entity, '"@')) {
return 'literal';
// checks if $entity is a string; only strings can be a variable
} elseif (true === is_string($entity)) {
return 'var';
// unknown type
} else {
return null;
}
} | php | {
"resource": ""
} |
q7686 | AbstractQuery.determineObjectDatatype | train | public function determineObjectDatatype($objectString)
{
$datatype = null;
// checks if ^^< is in $objectString
$arrowPos = strpos($objectString, '"^^<');
// checks if $objectString starts with " and contains "^^<
if ('"' === substr($objectString, 0, 1) && false !== $arrowPos) {
// extract datatype URI
$datatype = substr($objectString, $arrowPos + 4);
return substr($datatype, 0, strlen($datatype) - 1);
// checks for surrounding ", without ^^<
} elseif ('"' == substr($objectString, 0, 1)
&& '"' == substr($objectString, strlen($objectString) - 1, 1)) {
// if we land here, there are surrounding quotation marks, but no datatype
return 'http://www.w3.org/2001/XMLSchema#string';
// malformed string, return null as datatype
} else {
return null;
}
} | php | {
"resource": ""
} |
q7687 | AbstractQuery.extractNamespacesFromQuery | train | public function extractNamespacesFromQuery($query)
{
preg_match_all('/\<([a-zA-Z\\\.\/\-\#\:0-9]+)\>/', $query, $matches);
$uris = [];
// only use URI until the last occurence of one of these chars: # /
foreach ($matches[1] as $match) {
$hashPos = strrpos($match, '#');
// check for last #
if (false !== $hashPos) {
$uri = substr($match, 0, $hashPos + 1);
} else {
if (7 < strlen($match)) {
$slashPos = strrpos($match, '/', 7);
// check for last /
if (false !== $slashPos) {
$uri = substr($match, 0, $slashPos + 1);
} else {
continue;
}
} else {
continue;
}
}
$uris[$uri] = $uri;
}
$uris = array_values($uris);
$prefixes = [];
$uriSet = false;
$prefixNumber = 0;
foreach ($uris as $uri) {
$uriSet = false;
// go through common namespaces and try to find according prefix for
// current URI
foreach ($this->commonNamespaces as $prefix => $_uri) {
if ($uri == $_uri) {
$prefixes[$prefix] = $uri;
$uriSet = true;
break;
}
}
// in case, it couldnt find according prefix, generate one
if (false === $uriSet) {
$prefixes['ns-'.$prefixNumber++] = $uri;
}
}
return $prefixes;
} | php | {
"resource": ""
} |
q7688 | AbstractQuery.extractPrefixesFromQuery | train | public function extractPrefixesFromQuery($query)
{
preg_match_all('/PREFIX\s+([a-z0-9]+)\:\s*\<([a-z0-9\:\/\.\#\-]+)\>/', $query, $matches);
$prefixes = [];
foreach ($matches[1] as $index => $key) {
$prefixes[$key] = $matches[2][$index];
}
return $prefixes;
} | php | {
"resource": ""
} |
q7689 | AbstractQuery.extractQuads | train | public function extractQuads($query)
{
$quads = [];
/**
* Matches the following pattern: Graph <http://uri/> { ?s ?p ?o }
* Whereas ?s ?p ?o stands for any triple, so also for an URI. It also matches multi line strings
* which have { and triple on different lines.
*/
$result = preg_match_all('/GRAPH\s*\<(.*?)\>\s*\{\n*\s*(.*?)\s*\n*\}/si', $query, $matches);
// if no errors occour and graphs and triple where found
if (false !== $result
&& true === isset($matches[1])
&& true === isset($matches[2])) {
foreach ($matches[1] as $key => $graph) {
// parse according triple string, for instance: <http://saft/test/s1> dc:p1 <http://saft/test/o1>
// and extract S, P and O.
$triplePattern = $this->extractTriplePattern($matches[2][$key]);
// TODO Handle case that more than one triple pattern was found
if (0 == count($triplePattern)) {
throw new \Exception('Quad related part of the query is invalid: '.$matches[2][$key]);
}
$quad = $triplePattern[0];
$quad['g'] = $graph;
$quad['g_type'] = 'uri';
$quads[] = $quad;
}
}
return $quads;
} | php | {
"resource": ""
} |
q7690 | AbstractQuery.replacePrefixWithUri | train | public function replacePrefixWithUri($prefixedString, $prefixes)
{
// check for qname. a qname was given if a : was found, but no < and >
if (false !== strpos($prefixedString, ':') &&
false === strpos($prefixedString, '<') && false === strpos($prefixedString, '>')) {
// prefix is the part before the :
$prefix = substr($prefixedString, 0, strpos($prefixedString, ':'));
// if a prefix
if (true === isset($prefixes[$prefix])) {
$prefixedString = str_replace($prefix.':', $prefixes[$prefix], $prefixedString);
}
}
return $prefixedString;
} | php | {
"resource": ""
} |
q7691 | Transit.importFromLocal | train | public function importFromLocal($overwrite = true, $delete = false) {
$path = $this->_data;
$file = new File($path);
$target = $this->findDestination($file, $overwrite);
if (copy($path, $target)) {
if ($delete) {
$file->delete();
}
$this->_file = new File($target);
return true;
}
throw new IoException(sprintf('Failed to copy %s to new location', $file->basename()));
} | php | {
"resource": ""
} |
q7692 | Transit.importFromRemote | train | public function importFromRemote($overwrite = true, array $options = array()) {
if (!function_exists('curl_init')) {
throw new RuntimeException('The cURL module is required for remote file importing');
}
$url = $this->_data;
$name = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_BASENAME);
if (!$name) {
$name = md5(microtime(true));
}
$options = $options + array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_FAILONERROR => true,
CURLOPT_SSL_VERIFYPEER => false
);
// Fetch the remote file
$curl = curl_init($url);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
// Save the file locally
if (!$error) {
$target = $this->findDestination($name, $overwrite);
if (file_put_contents($target, $response)) {
$this->_file = new File($target);
return true;
}
}
throw new IoException(sprintf('Failed to import %s from remote location: %s', $name, $error));
} | php | {
"resource": ""
} |
q7693 | Transit.importFromStream | train | public function importFromStream($overwrite = true) {
$target = $this->findDestination($this->_data, $overwrite);
$input = fopen('php://input', 'r');
$output = fopen($target, 'w');
$size = stream_copy_to_stream($input, $output);
fclose($input);
fclose($output);
if ($size <= 0) {
@unlink($target);
throw new IoException('No file detected in input stream');
}
$this->_file = new File($target);
return $size;
} | php | {
"resource": ""
} |
q7694 | Transit.rollback | train | public function rollback() {
if ($files = $this->getAllFiles()) {
foreach ($files as $file) {
if ($file instanceof File) {
$file->delete();
}
}
}
$this->_file = null;
$this->_files = array();
return $this;
} | php | {
"resource": ""
} |
q7695 | Transit.setDirectory | train | public function setDirectory($path) {
if (substr($path, -1) !== '/') {
$path .= '/';
}
if (!file_exists($path)) {
mkdir($path, 0777, true);
} else if (!is_writable($path)) {
chmod($path, 0777);
}
$this->_directory = $path;
return $this;
} | php | {
"resource": ""
} |
q7696 | Transit.transform | train | public function transform() {
$originalFile = $this->getOriginalFile();
$transformedFiles = array();
$error = null;
if (!$originalFile) {
throw new IoException('No original file detected');
}
// Apply transformations to original
if ($this->_selfTransformers) {
foreach ($this->_selfTransformers as $transformer) {
try {
$originalFile = $transformer->transform($originalFile, true);
} catch (Exception $e) {
$error = $e->getMessage();
break;
}
}
$originalFile->reset();
}
// Create transformed files based off original
if ($this->_transformers && !$error) {
foreach ($this->_transformers as $transformer) {
try {
$transformedFiles[] = $transformer->transform($originalFile, false);
} catch (Exception $e) {
$error = $e->getMessage();
break;
}
}
}
$this->_file = $originalFile;
$this->_files = $transformedFiles;
// Throw error and rollback
if ($error) {
$this->rollback();
throw new TransformationException($error);
}
return true;
} | php | {
"resource": ""
} |
q7697 | Transit.transport | train | public function transport(array $config = array()) {
if (!$this->_transporter) {
throw new InvalidArgumentException('No Transporter has been defined');
}
$localFiles = $this->getAllFiles();
$transportedFiles = array();
$error = null;
if (!$localFiles) {
throw new IoException('No files to transport');
}
foreach ($localFiles as $i => $file) {
try {
$tempConfig = $config;
if (isset($tempConfig[$i])) {
$tempConfig = array_merge($tempConfig, $tempConfig[$i]);
}
$transportedFiles[] = $this->getTransporter()->transport($file, $tempConfig);
} catch (Exception $e) {
$error = $e->getMessage();
break;
}
}
// Throw error and rollback
if ($error) {
$this->rollback();
if ($transportedFiles) {
foreach ($transportedFiles as $path) {
$this->getTransporter()->delete($path);
}
}
throw new TransportationException($error);
}
return $transportedFiles;
} | php | {
"resource": ""
} |
q7698 | Transit.upload | train | public function upload($overwrite = false) {
$data = $this->_data;
if (empty($data['tmp_name'])) {
throw new ValidationException('Invalid file detected for upload');
}
// Check upload errors
if ($data['error'] > 0 || !$this->_isUploadedFile($data['tmp_name'])) {
switch ($data['error']) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$error = 'File exceeds the maximum file size';
break;
case UPLOAD_ERR_PARTIAL:
$error = 'File was only partially uploaded';
break;
case UPLOAD_ERR_NO_FILE:
$error = 'No file was found for upload';
break;
default:
$error = 'File failed to upload';
break;
}
throw new ValidationException($error);
}
// Validate rules
if ($validator = $this->getValidator()) {
$validator
->setFile(new File($data))
->validate();
}
// Upload the file
$target = $this->findDestination($data['name'], $overwrite);
if ($this->_moveUploadedFile($data['tmp_name'], $target)) {
$data['name'] = basename($target);
$data['tmp_name'] = $target;
$this->_file = new File($data);
return true;
}
throw new ValidationException('An unknown error has occurred');
} | php | {
"resource": ""
} |
q7699 | ArrayValue.add_validator_by_key | train | public function add_validator_by_key( ValidatorInterface $validator, $key ) {
if ( ! is_scalar( $key ) ) {
throw new Exception\InvalidArgumentException( 'key should be a scalar value.' );
}
$key = (string) $key;
if ( ! isset ( $this->validators_by_key[ $key ] ) ) {
$this->validators_by_key[ $key ] = [ ];
}
$this->validators_by_key[ $key ][] = $validator;
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.