_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q7700
ArrayValue.validate
train
private function validate( $values ) { $is_valid = TRUE; foreach ( $values as $key => $value ) { if ( ! is_scalar( $value ) ) { continue; } foreach ( $this->validators as $validator ) { $is_valid = $validator->is_valid( $value ); if ( ! $is_valid ) { $this->error_messages[ $key ] = $validator->get_error_messages(); break; } } if ( ! $is_valid ) { break; } } return $is_valid; }
php
{ "resource": "" }
q7701
ArrayValue.validate_by_key
train
protected function validate_by_key( $values ) { $is_valid = TRUE; if ( count( $this->validators_by_key ) < 1 ) { return $is_valid; } foreach ( $values as $key => $value ) { if ( ! is_scalar( $value ) || ! isset( $this->validators_by_key[ $key ] ) ) { continue; } /** @var $validators ValidatorInterface[] */ $validators = $this->validators_by_key[ $key ]; foreach ( $validators as $validator ) { $is_valid = $validator->is_valid( $value ); if ( ! $is_valid ) { $this->error_messages[ $key ] = $validator->get_error_messages(); break; } } if ( ! $is_valid ) { break; } } return $is_valid; }
php
{ "resource": "" }
q7702
User.convertToCommunityId
train
public function convertToCommunityId($id) { switch (self::getTypeOfId($id)) { case USER_ID_TYPE_COMMUNITY: return $id; case USER_ID_TYPE_VANITY: $api_interface = new ISteamUser(); return $api_interface->ResolveVanityURL($id); case USER_ID_TYPE_STEAM: return self::steamIdToCommunityId($id); default: return FALSE; } }
php
{ "resource": "" }
q7703
User.getTypeOfId
train
public function getTypeOfId($id) { if (self::validateUserId($id, USER_ID_TYPE_COMMUNITY)) return USER_ID_TYPE_COMMUNITY; if (self::validateUserId($id, USER_ID_TYPE_STEAM)) return USER_ID_TYPE_STEAM; if (self::validateUserId($id, USER_ID_TYPE_VANITY)) return USER_ID_TYPE_VANITY; return FALSE; }
php
{ "resource": "" }
q7704
User.communityIdToSteamId
train
public function communityIdToSteamId($community_id, $is_short = FALSE) { $temp = intval($community_id) - 76561197960265728; $odd_id = $temp % 2; $temp = floor($temp / 2); if ($is_short) { return $odd_id . ':' . $temp; } else { return 'STEAM_0:' . $odd_id . ':' . $temp; } }
php
{ "resource": "" }
q7705
CircularArray.fromArray
train
public static function fromArray($array, $save_indexes = true) { $circular = new self(count($array)); foreach ($array as $key => $value) { $circular[$key] = $value; } return $circular; }
php
{ "resource": "" }
q7706
TimeSlotHelper.contains
train
public static function contains(TimeSlot $a, TimeSlot $b) { $c1 = DateTimeHelper::isBetween($b->getStartDate(), $a->getStartDate(), $a->getEndDate()); $c2 = DateTimeHelper::isBetween($b->getEndDate(), $a->getStartDate(), $a->getEndDate()); return $c1 && $c2; }
php
{ "resource": "" }
q7707
TimeSlotHelper.equals
train
public static function equals(TimeSlot $a, TimeSlot $b) { // Compare the start dates. if (false === DateTimeHelper::equals($a->getStartDate(), $b->getStartDate())) { return false; } // Compare the end dates. if (false === DateTimeHelper::equals($a->getEndDate(), $b->getEndDate())) { return false; } // Compare the time slots count. if (count($a->getTimeSlots()) !== count($b->getTimeSlots())) { return false; } // Handle each time slot. for ($i = count($a->getTimeSlots()) - 1; 0 <= $i; --$i) { if (false === static::equals($a->getTimeSlots()[$i], $b->getTimeSlots()[$i])) { return false; } } // return true; }
php
{ "resource": "" }
q7708
TimeSlotHelper.fullJoin
train
public static function fullJoin(TimeSlot $a, TimeSlot $b) { // Has full join ? if (false === static::hasFullJoin($a, $b)) { return null; } // Initialize the date/times. $startDate = DateTimeHelper::getSmaller($a->getStartDate(), $b->getStartDate()); $endDate = DateTimeHelper::getGreater($a->getEndDate(), $b->getEndDate()); // Return the time slot. return new TimeSlot(clone $startDate, clone $endDate); }
php
{ "resource": "" }
q7709
TimeSlotHelper.fullJoinWithout
train
public static function fullJoinWithout(TimeSlot $a, TimeSlot $b) { // Initialize the time slots. $leftJoins = static::leftJoinWithout($a, $b); $rightJoins = static::rightJoinWithout($a, $b); // Check the time slots. if (null === $leftJoins && null === $rightJoins) { return null; } if (null === $leftJoins) { return $rightJoins; } if (null === $rightJoins) { return $leftJoins; } // Return the time slots. return static::sort(array_merge($leftJoins, $rightJoins)); }
php
{ "resource": "" }
q7710
TimeSlotHelper.hasInnerJoin
train
public static function hasInnerJoin(TimeSlot $a, TimeSlot $b) { $c1 = DateTimeHelper::isBetween($b->getStartDate(), $a->getStartDate(), $a->getEndDate()); $c2 = DateTimeHelper::isBetween($b->getEndDate(), $a->getStartDate(), $a->getEndDate()); $c3 = DateTimeHelper::isBetween($a->getStartDate(), $b->getStartDate(), $b->getEndDate()); $c4 = DateTimeHelper::isBetween($a->getEndDate(), $b->getStartDate(), $b->getEndDate()); return $c1 || $c2 || $c3 || $c4; }
php
{ "resource": "" }
q7711
TimeSlotHelper.innerJoin
train
public static function innerJoin(TimeSlot $a, TimeSlot $b) { // Has inner join ? if (false === static::hasInnerJoin($a, $b)) { return null; } // Initialize the date/times. $startDate = DateTimeHelper::getGreater($a->getStartDate(), $b->getStartDate()); $endDate = DateTimeHelper::getSmaller($a->getEndDate(), $b->getEndDate()); // Return the time slot. return new TimeSlot(clone $startDate, clone $endDate); }
php
{ "resource": "" }
q7712
TimeSlotHelper.leftJoin
train
public static function leftJoin(TimeSlot $a, TimeSlot $b) { // Has inner join ? if (false === static::hasInnerJoin($a, $b)) { return null; } // Return the time slot. return new TimeSlot(clone $a->getStartDate(), clone $a->getEndDate()); }
php
{ "resource": "" }
q7713
TimeSlotHelper.leftJoinWithout
train
public static function leftJoinWithout(TimeSlot $a, TimeSlot $b) { // Has inner join ? if (false === static::hasInnerJoin($a, $b) || true === static::contains($b, $a)) { return null; } // Contains ? if (true === static::contains($a, $b)) { return static::sort([ new TimeSlot(clone $a->getStartDate(), clone $b->getStartDate()), new TimeSlot(clone $b->getEndDate(), clone $a->getEndDate()), ]); } // Initialize the date/times. $startDate = true === DateTimeHelper::isLessThan($a->getStartDate(), $b->getStartDate()) ? $a->getStartDate() : $b->getEndDate(); $endDate = true === DateTimeHelper::isGreaterThan($a->getEndDate(), $b->getEndDate()) ? $a->getEndDate() : $b->getStartDate(); // Return the time slots. return [ new TimeSlot(clone $startDate, clone $endDate), ]; }
php
{ "resource": "" }
q7714
TimeSlotHelper.sort
train
public static function sort(array $timeSlots) { // Initialize a Qucik sort. $sorter = new QuickSort($timeSlots, new TimeSlotFunctor()); $sorter->sort(); // Return the time slots. return $sorter->getValues(); }
php
{ "resource": "" }
q7715
UserSecurityReport.columns
train
public function columns() { $columns = self::config()->columns; if (!Security::config()->get('login_recording')) { unset($columns['LastLoggedIn']); } return $columns; }
php
{ "resource": "" }
q7716
Asset.addAsset
train
public function addAsset(array $Asset) { if (isset($Asset['name']) && ! array_key_exists($Asset['name'], $this->holder)) { $this->holder[$Asset['name']] = $Asset; } }
php
{ "resource": "" }
q7717
Asset.delAsset
train
public function delAsset(array $Asset) { if (isset($Asset['name']) && array_key_exists($Asset['name'], $this->holder)) { unset($this->holder[$Asset['name']]); } }
php
{ "resource": "" }
q7718
Asset.addCss
train
public function addCss($link) { if ( ! empty($link)) { if ( ! is_array($link)) { $link = [$link]; } $this->css = array_merge($this->css, $link); } }
php
{ "resource": "" }
q7719
Asset.addJs
train
public function addJs($link) { if ( ! empty($link)) { if ( ! is_array($link)) { $link = [$link]; } $this->js = array_merge($this->js, $link); } }
php
{ "resource": "" }
q7720
Asset.delCss
train
public function delCss($link) { if ( ! empty($link)) { if ( ! is_array($link)) { $link = [$link]; } if ( ! isset($this->obsolete['css'])) { $this->obsolete['css'] = []; } $this->obsolete['css'] = array_merge($this->obsolete['css'], $link); } }
php
{ "resource": "" }
q7721
Asset.delJs
train
public function delJs($link) { if ( ! empty($link)) { if ( ! is_array($link)) { $link = [$link]; } if ( ! isset($this->obsolete['js'])) { $this->obsolete['js'] = []; } $this->obsolete['js'] = array_merge($this->obsolete['js'], $link); } }
php
{ "resource": "" }
q7722
Asset.addScriptBefore
train
private function addScriptBefore($script) { $script = trim($script); if ($script != '') { if (strpos($this->script, $script) === false) { $this->script = " {$script} {$this->script}"; } } }
php
{ "resource": "" }
q7723
Asset.reset
train
public function reset() { $this->script = ''; $this->style = ''; $this->js = []; $this->css = []; $this->obsolete = []; $this->holder = []; $this->run = false; }
php
{ "resource": "" }
q7724
Asset.runCopy
train
private function runCopy() { if ( ! $this->run) { foreach ($this->holder as $name => $contents) { //checking the copy index if (array_key_exists('copy', $contents)) { //forceCopy flag check if ( ! array_key_exists('forceCopy', $contents)) { $contents['forceCopy'] = false; } //chmod flag check if ( ! array_key_exists('chmod', $contents)) { $contents['chmod'] = 0777; } //iterating foreach ($contents['copy'] as $from => $to) { $this->copy($from, $to, $contents['forceCopy'], $contents['chmod']); } } //some scripts have to initialized before they call statements if (array_key_exists('script', $contents)) { $this->addScriptBefore($contents['script']); } if (array_key_exists('style', $contents)) { $this->addStyle($contents['style']); } if (array_key_exists('css', $contents)) { $this->addCss($contents['css']); } if (array_key_exists('js', $contents)) { $this->addJs($contents['js']); } } //all css if (array_key_exists('css', $this->obsolete)) { $this->css = array_diff($this->css, $this->obsolete['css']); } $this->css = array_unique($this->css); //all js if (array_key_exists('js', $this->obsolete)) { $this->js = array_diff($this->js, $this->obsolete['js']); } $this->js = array_unique($this->js); //all scripts if (array_key_exists('script', $this->obsolete)) { $this->script = str_replace($this->obsolete['script'], '', $this->script); } //all styles if (array_key_exists('style', $this->obsolete)) { $this->style = str_replace($this->obsolete['style'], '', $this->style); } //the copy has been executed! $this->run = true; } }
php
{ "resource": "" }
q7725
Bootstrap._pre_set_site_transient_update_themes
train
public function _pre_set_site_transient_update_themes( $transient ) { $current = wp_get_theme( $this->theme_name ); $api_data = $this->_get_transient_api_data(); if ( is_wp_error( $api_data ) ) { $this->_set_notice_error_about_github_api(); return $transient; } if ( ! isset( $api_data->tag_name ) ) { return $transient; } if ( ! $this->_should_update( $current['Version'], $api_data->tag_name ) ) { return $transient; } $package = $this->_get_zip_url( $api_data ); $http_status_code = $this->_get_http_status_code( $package ); if ( ! $package || ! in_array( $http_status_code, [ 200, 302 ] ) ) { error_log( 'Inc2734_WP_GitHub_Theme_Updater error. zip url not found. ' . $http_status_code . ' ' . $package ); return $transient; } $transient->response[ $this->theme_name ] = [ 'theme' => $this->theme_name, 'new_version' => $api_data->tag_name, 'url' => ( ! empty( $this->fields['homepage'] ) ) ? $this->fields['homepage'] : '', 'package' => $package, ]; return $transient; }
php
{ "resource": "" }
q7726
Bootstrap._set_notice_error_about_github_api
train
protected function _set_notice_error_about_github_api() { $api_data = $this->_get_transient_api_data(); if ( ! is_wp_error( $api_data ) ) { return; } add_action( 'admin_notices', function() use ( $api_data ) { ?> <div class="notice notice-error"> <p> <?php echo esc_html( $api_data->get_error_message() ); ?> </p> </div> <?php } ); }
php
{ "resource": "" }
q7727
Bootstrap._get_zip_url
train
protected function _get_zip_url( $remote ) { $url = false; if ( ! empty( $remote->assets ) && is_array( $remote->assets ) ) { if ( ! empty( $remote->assets[0] ) && is_object( $remote->assets[0] ) ) { if ( ! empty( $remote->assets[0]->browser_download_url ) ) { $url = $remote->assets[0]->browser_download_url; } } } $tag_name = isset( $remote->tag_name ) ? $remote->tag_name : null; if ( ! $url && $tag_name ) { $url = sprintf( 'https://github.com/%1$s/%2$s/archive/%3$s.zip', $this->user_name, $this->repository, $tag_name ); } return apply_filters( sprintf( 'inc2734_github_theme_updater_zip_url_%1$s/%2$s', $this->user_name, $this->repository ), $url, $this->user_name, $this->repository, $tag_name ); }
php
{ "resource": "" }
q7728
Bootstrap._get_transient_api_data
train
protected function _get_transient_api_data() { $transient_name = sprintf( 'wp_github_theme_updater_%1$s', $this->theme_name ); $transient = get_transient( $transient_name ); if ( false !== $transient ) { return $transient; } $api_data = $this->_get_github_api_data(); set_transient( $transient_name, $api_data, 60 * 5 ); return $api_data; }
php
{ "resource": "" }
q7729
Bootstrap._get_github_api_data
train
protected function _get_github_api_data() { $response = $this->_request_github_api(); if ( is_wp_error( $response ) ) { return $response; } $response_code = wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ) ); if ( 200 == $response_code ) { return $body; } return new \WP_Error( $response_code, 'Inc2734_WP_GitHub_Theme_Updater error. ' . $body->message ); }
php
{ "resource": "" }
q7730
Bootstrap._request_github_api
train
protected function _request_github_api() { global $wp_version; $url = sprintf( 'https://api.github.com/repos/%1$s/%2$s/releases/latest', $this->user_name, $this->repository ); return wp_remote_get( apply_filters( sprintf( 'inc2734_github_theme_updater_request_url_%1$s/%2$s', $this->user_name, $this->repository ), $url, $this->user_name, $this->repository ), [ 'user-agent' => 'WordPress/' . $wp_version, 'headers' => [ 'Accept-Encoding' => '', ], ] ); }
php
{ "resource": "" }
q7731
Bootstrap._should_update
train
protected function _should_update( $current_version, $remote_version ) { return version_compare( $this->_sanitize_version( $current_version ), $this->_sanitize_version( $remote_version ), '<' ); }
php
{ "resource": "" }
q7732
Orchestra.isUsingQueue
train
protected function isUsingQueue() { // It impossible to get either the email is sent out straight away // when the mailer is only push to queue, in this case we should // assume that sending is successful when using queue. $queue = false; $driver = 'mail'; if ($this->memory instanceof Provider) { $queue = $this->memory->get('email.queue', false); $driver = $this->memory->get('email.driver'); } return $queue || \in_array($driver, ['mailgun', 'mandrill', 'log']); }
php
{ "resource": "" }
q7733
Main.getMageShippingCountries
train
public function getMageShippingCountries($storeId = null) { return $this ->countryCollection ->loadByStore($this->storeManager->getStore($storeId)) ->getColumnValues('country_id'); }
php
{ "resource": "" }
q7734
Main.getActiveCarriers
train
public function getActiveCarriers($storeId = null) { return $this->carrierConfig->getActiveCarriers($this->storeManager->getStore($storeId)); }
php
{ "resource": "" }
q7735
FieldDescriptor.getPhpType
train
public function getPhpType() { if (isset(self::$_phpTypesByProtobufType[$this->getType()])) { return self::$_phpTypesByProtobufType[$this->getType()]; } else { return null; } }
php
{ "resource": "" }
q7736
GlacierTransporter.delete
train
public function delete($id) { $config = $this->getConfig(); try { $this->getClient()->deleteArchive(array_filter(array( 'vaultName' => $config['vault'], 'accountId' => $config['accountId'], 'archiveId' => $id ))); } catch (GlacierException $e) { return false; } return true; }
php
{ "resource": "" }
q7737
GlacierTransporter.transport
train
public function transport(File $file, array $config = array()) { $config = $config + $this->getConfig(); $response = null; // If larger then 100MB, split upload into parts if ($file->size() >= (100 * Size::MB)) { $uploader = UploadBuilder::newInstance() ->setClient($this->getClient()) ->setSource($file->path()) ->setVaultName($config['vault']) ->setAccountId($config['accountId'] ?: '-') ->setPartSize(10 * Size::MB) ->build(); try { $response = $uploader->upload(); } catch (MultipartUploadException $e) { $uploader->abort(); } } else { $response = $this->getClient()->uploadArchive(array_filter(array( 'vaultName' => $config['vault'], 'accountId' => $config['accountId'], 'body' => EntityBody::factory(fopen($file->path(), 'r')), ))); } // Return archive ID if successful if ($response) { $config['removeLocal'] && $file->delete(); return $response->getPath('archiveId'); } throw new TransportationException(sprintf('Failed to transport %s to Amazon Glacier', $file->basename())); }
php
{ "resource": "" }
q7738
LoggerBridge.preRequest
train
public function preRequest( \SS_HTTPRequest $request, \Session $session, \DataModel $model ) { $this->registerGlobalHandlers(); return true; }
php
{ "resource": "" }
q7739
LoggerBridge.postRequest
train
public function postRequest( \SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model ) { $this->deregisterGlobalHandlers(); return true; }
php
{ "resource": "" }
q7740
LoggerBridge.registerGlobalHandlers
train
public function registerGlobalHandlers() { if (!$this->registered) { // Store the previous error handler if there was any $this->registerErrorHandler(); // Store the previous exception handler if there was any $this->registerExceptionHandler(); // If the shutdown function hasn't been registered register it if ($this->registered === null) { $this->registerFatalErrorHandler(); // If suhosin is relevant then decrease the memory_limit by the reserveMemory amount // otherwise we should be able to increase the memory by our reserveMemory amount without worry if ($this->isSuhosinRelevant()) { $this->ensureSuhosinMemory(); } } $this->registered = true; } }
php
{ "resource": "" }
q7741
LoggerBridge.deregisterGlobalHandlers
train
public function deregisterGlobalHandlers() { if ($this->registered) { // Restore the previous error handler if available set_error_handler( is_callable($this->errorHandler) ? $this->errorHandler : function () { } ); // Restore the previous exception handler if available set_exception_handler( is_callable($this->exceptionHandler) ? $this->exceptionHandler : function () { } ); $this->registered = false; } }
php
{ "resource": "" }
q7742
LoggerBridge.errorHandler
train
public function errorHandler($errno, $errstr, $errfile, $errline) { // Honour error suppression through @ if (($errorReporting = error_reporting()) === 0) { return true; } $logType = null; foreach ($this->errorLogGroups as $candidateLogType => $errorTypes) { if (in_array($errno, $errorTypes)) { $logType = $candidateLogType; break; } } if (is_null($logType)) { throw new \Exception(sprintf( "No log type found for errno '%s'", $errno )); } $exception = $this->createException($errstr, $errno, $errfile, $errline); // Log all errors regardless of type $context = array( 'file' => $errfile, 'line' => $errline ); if ($this->reportBacktrace) { $context['backtrace'] = $this->getBacktraceReporter()->getBacktrace(); } if ($this->exceptionInContext) { $context['exception'] = $exception; } $this->logger->$logType($errstr, $context); // Check the error_reporting level in comparison with the $errno (honouring the environment) // And check that $showErrors is on or the site is live if (($errno & $errorReporting) === $errno && ($this->showErrors || $this->getEnvReporter()->isLive())) { $this->getErrorReporter()->reportError($exception); } if (in_array($errno, $this->terminatingErrors)) { $this->terminate(); } // ignore the usually handling of this type of error return true; }
php
{ "resource": "" }
q7743
LoggerBridge.fatalHandler
train
public function fatalHandler() { $error = $this->getLastError(); if ($this->isRegistered() && $this->isFatalError($error)) { if (defined('FRAMEWORK_PATH')) { chdir(FRAMEWORK_PATH); } if ($this->isMemoryExhaustedError($error)) { // We can safely change the memory limit be the reserve amount because if suhosin is relevant // the memory will have been decreased prior to exhaustion $this->changeMemoryLimit($this->reserveMemory); } $exception = $this->createException( $error['message'], $error['type'], $error['file'], $error['line'] ); $context = array( 'file' => $error['file'], 'line' => $error['line'] ); if ($this->reportBacktrace) { $context['backtrace'] = $this->getBacktraceReporter()->getBacktrace(); } if ($this->exceptionInContext) { $context['exception'] = $exception; } $this->logger->critical($error['message'], $context); // Fatal errors should be reported when live as they stop the display of regular output if ($this->showErrors || $this->getEnvReporter()->isLive()) { $this->getErrorReporter()->reportError($exception); } } }
php
{ "resource": "" }
q7744
LoggerBridge.isMemoryExhaustedError
train
protected function isMemoryExhaustedError($error) { return isset($error['message']) && stripos($error['message'], 'memory') !== false && stripos($error['message'], 'exhausted') !== false; }
php
{ "resource": "" }
q7745
LoggerBridge.translateMemoryLimit
train
protected function translateMemoryLimit($memoryLimit) { $unit = strtolower(substr($memoryLimit, -1, 1)); $memoryLimit = (int) $memoryLimit; switch ($unit) { case 'g': $memoryLimit *= 1024; // intentional case 'm': $memoryLimit *= 1024; // intentional case 'k': $memoryLimit *= 1024; // intentional } return $memoryLimit; }
php
{ "resource": "" }
q7746
Configurable.getItemId
train
public function getItemId() { if ($this->getProductCustomOption()) { return $this->getItem()->getData('product_id') . '-' . $this->getProductCustomOption()->getProduct()->getId(); } return parent::getItemId(); }
php
{ "resource": "" }
q7747
Config.startup
train
public function startup() { /** @var \Shopgate\Base\Helper\Initializer\Config $initializer */ $manager = ObjectManager::getInstance(); $initializer = $manager->get('Shopgate\Base\Helper\Initializer\Config'); $this->storeManager = $initializer->getStoreManager(); $this->logger = $initializer->getLogger(); $this->directory = $initializer->getDirectory(); $this->sgCoreConfig = $initializer->getSgCoreConfig(); $this->coreConfig = $initializer->getCoreConfig(); $this->cache = $initializer->getCache(); $this->configResource = $initializer->getConfigResource(); $this->configMapping = $initializer->getConfigMapping(); $this->configMethods = $initializer->getConfigMethods(); $this->registry = $initializer->getRegistry(); $this->configHelper = $initializer->getHelper(); $this->plugin_name = 'magento2'; $this->configMapping += $this->configHelper->loadUndefinedConfigPaths(); $this->loadArray($this->configMethods); return true; }
php
{ "resource": "" }
q7748
Config.load
train
public function load(array $settings = null) { $classVars = array_keys(get_class_vars(get_class($this))); foreach ($settings as $name => $value) { if (in_array($name, $this->blacklistConfig, true)) { continue; } if (in_array($name, $classVars, true)) { $method = 'set' . SimpleDataObjectConverter::snakeCaseToUpperCamelCase($name); if (method_exists($this, $method)) { $this->configMapping += $this->configHelper->getNewSettingPath($name); $this->{$method}($this->castToType($value, $name)); } else { $this->logger->debug( 'The evaluated method "' . $method . '" is not available in class ' . __CLASS__ ); } } else { if (array_key_exists($name, $this->additionalSettings)) { $this->additionalSettings[$name] = $value; } else { $this->logger->debug( 'The given setting property "' . $name . '" is not available in class ' . __CLASS__ ); } } } }
php
{ "resource": "" }
q7749
Config.castToType
train
protected function castToType($value, $property) { $type = $this->getPropertyType($property); switch ($type) { case 'array': return is_array($value) ? $value : explode(",", $value); case 'bool': case 'boolean': return (boolean) $value; case 'int': case 'integer': return (int) $value; case 'string': return (string) $value; default: return $value; } }
php
{ "resource": "" }
q7750
Config.getPropertyType
train
protected function getPropertyType($property) { if (!array_key_exists($property, get_class_vars('ShopgateConfig'))) { return 'string'; } $r = new \ReflectionProperty('ShopgateConfig', $property); $doc = $r->getDocComment(); preg_match_all('#@var ([a-zA-Z-_]*(\[\])?)(.*?)\n#s', $doc, $annotations); $value = 'string'; if (count($annotations) > 0 && isset($annotations[1][0])) { $value = $annotations[1][0]; } return $value; }
php
{ "resource": "" }
q7751
Config.loadConfig
train
public function loadConfig() { if (!$this->registry->isRedirect()) { $storeId = $this->sgCoreConfig->getStoreId($this->getShopNumber()); $this->storeManager->setCurrentStore($storeId); } $this->loadArray($this->toArray()); $this->setExportTmpAndLogSettings(); }
php
{ "resource": "" }
q7752
Config.getShopNumber
train
public function getShopNumber() { if ($this->shop_number === null) { $this->shop_number = $this->configHelper->getShopNumber(); } return $this->shop_number; }
php
{ "resource": "" }
q7753
Config.setExportTmpAndLogSettings
train
protected function setExportTmpAndLogSettings() { $this->setExportFolderPath( $this->directory->getPath(DirectoryList::TMP) . DS . 'shopgate' . DS . $this->getShopNumber() ); $this->createFolderIfNotExist($this->getExportFolderPath()); $this->setLogFolderPath( $this->directory->getPath(DirectoryList::LOG) . DS . 'shopgate' . DS . $this->getShopNumber() ); $this->createFolderIfNotExist($this->getLogFolderPath()); $this->setCacheFolderPath( $this->directory->getPath(DirectoryList::TMP) . DS . 'shopgate' . DS . $this->getShopNumber() ); $this->createFolderIfNotExist($this->getCacheFolderPath()); }
php
{ "resource": "" }
q7754
Config.methodLoader
train
private function methodLoader(array $classProperties) { $result = []; foreach ($classProperties as $propertyName => $nullVal) { $result[$propertyName] = $this->getPropertyValue($propertyName); } return $result; }
php
{ "resource": "" }
q7755
Config.getPropertyValue
train
private function getPropertyValue($property) { $value = null; $getter = 'get' . SimpleDataObjectConverter::snakeCaseToUpperCamelCase($property); if (method_exists($this, $getter)) { $value = $this->{$getter}(); } elseif ($this->returnAdditionalSetting($property)) { $value = $this->returnAdditionalSetting($property); } return $value; }
php
{ "resource": "" }
q7756
Config.getCoreConfigMap
train
private function getCoreConfigMap(array $map) { $result = []; foreach ($map as $key => $path) { $value = $this->coreConfig->getConfigByPath($path)->getData('value'); if ($value !== null) { $result[$key] = $this->castToType($value, $key); } } return $result; }
php
{ "resource": "" }
q7757
Config.save
train
public function save(array $fieldList, $validate = true) { $this->logger->debug('# setSettings save start'); if ($validate) { $this->validate($fieldList); } foreach ($fieldList as $property) { if (in_array($property, $this->blacklistConfig, true)) { continue; } if (isset($this->configMapping[$property])) { $config = $this->sgCoreConfig->getSaveScope($this->configMapping[$property], $this->getShopNumber()); $this->saveField( $this->configMapping[$property], $property, $config->getScope(), $config->getScopeId() ); } } $this->clearCache(); $this->logger->debug('# setSettings save end'); }
php
{ "resource": "" }
q7758
Config.saveField
train
protected function saveField($path, $property, $scope, $scopeId, $value = null) { if ($value === null) { if (isset($this->configMapping[$property])) { $value = $this->getPropertyValue($property); } else { $this->logger->error('The specified property "' . $property . '" is not in the DI list'); } } if ($value !== null) { $this->logger->debug( ' Saving config field \'' . $property . '\' with value \'' . $value . '\' to scope {\'' . $scope . '\':\'' . $scopeId . '\'}' ); $value = $this->prepareForDatabase($property, $value); $this->configResource->saveConfig($path, $value, $scope, $scopeId); } }
php
{ "resource": "" }
q7759
Config.prepareForDatabase
train
protected function prepareForDatabase($property, $value) { $type = $this->getPropertyType($property); if ($type == 'array' && is_array($value)) { return implode(",", $value); } if (is_bool($value)) { $value = (int) $value; } return $value; }
php
{ "resource": "" }
q7760
Config.clearCache
train
protected function clearCache() { $result = $this->cache->clean([\Magento\Framework\App\Config::CACHE_TAG]); $this->logger->debug( ' Config cache cleared with result: ' . ($result ? '[OK]' : '[ERROR]') ); }
php
{ "resource": "" }
q7761
Order.getByOrderNumber
train
public function getByOrderNumber($number) { $connection = $this->getConnection(); $select = $connection->select()->from($this->getMainTable())->where('shopgate_order_number = :number'); $bind = [':number' => (string) $number]; return $connection->fetchRow($select, $bind); }
php
{ "resource": "" }
q7762
Order.getByOrderId
train
public function getByOrderId($id) { $connection = $this->getConnection(); $select = $connection->select()->from($this->getMainTable())->where('order_id = :internal_order_id'); $bind = [':internal_order_id' => (string) $id]; return $connection->fetchRow($select, $bind); }
php
{ "resource": "" }
q7763
CardParser.parseEntity
train
public function parseEntity(Card $entity) { $output = [ $this->encodeString($entity->getTicketNumber(), 23), $this->encodeInteger($entity->getUserNumber(), 9), $this->encodeInteger($entity->getArticleNumber(), 3), $this->encodeDate($entity->getValidFrom()), $this->encodeDate($entity->getExpires()), $this->encodeBoolean($entity->getBlocked()), $this->encodeDate($entity->getBlockedDate()), $this->encodeInteger($entity->getProductionState(), 1), $this->encodeInteger($entity->getReasonProduction(), 1), $this->encodeInteger($entity->getProductionCounter(), 4), $this->encodeBoolean($entity->getNeutral()), $this->encodeBoolean($entity->getRetainTicketEntry()), $this->encodeBoolean($entity->getEntryBarrierClosed()), $this->encodeBoolean($entity->getExitBarrierClosed()), $this->encodeBoolean($entity->getRetainTicketExit()), $this->encodeBoolean($entity->getDisplayText()), $this->encodeString($entity->getDisplayText1(), 16), $this->encodeString($entity->getDisplayText2(), 16), $this->encodeInteger($entity->getPersonnalNo(), 4), $this->encodeInteger($entity->getResidualValue(), 12), $this->encodeString($entity->getSerialNumberKeyCardSwatch(), 20), $this->encodeString($entity->getCurrencyResidualValue(), 3), $this->encodeInteger($entity->getTicketType(), 1), $this->encodeString($entity->getTicketSubType(), 5), $this->encodeString($entity->getSerialNo(), 30), $this->encodeDate($entity->getSuspendPeriodFrom()), $this->encodeDate($entity->getSuspendPeriodUntil()), $this->encodeBoolean($entity->getUseValidCarParks()), $this->encodeInteger($entity->getProductionFacilityNumber(), 7), ]; return implode(";", $output); }
php
{ "resource": "" }
q7764
Schema.load
train
public function load($schema_shortname, $component_class = 'PatternBuilder\Property\Component\Component') { $cid = $this->getCid($schema_shortname); if ($this->use_cache && $cache = $this->getCache($cid)) { return clone $cache; } else { if (empty($this->schemaFiles)) { $this->schemaFiles = $this->getSchemaFiles(); } if (!isset($this->schemaFiles[$schema_shortname])) { $message = sprintf('JSON shortname of %s was not found.', $schema_shortname); $this->logger->error($message); return false; } // Loading is limited to this branch of the IF to limit disk IO if ($json = $this->loadSchema($this->schemaFiles[$schema_shortname])) { $schema_path = $this->schemaFiles[$schema_shortname]; $component = new $component_class($json, $this->configuration, $schema_shortname, $schema_path); $this->setCache($cid, $component); return $component; } else { return false; } } }
php
{ "resource": "" }
q7765
Schema.getCache
train
protected function getCache($cid) { if (isset($this->localCache[$cid])) { $cache = $this->localCache[$cid]; } else { $cache = $this->loadCache($cid); if ($cache !== false) { $this->localCache[$cid] = $cache; } } return $cache; }
php
{ "resource": "" }
q7766
Schema.setCache
train
protected function setCache($cid, $component_obj) { $this->localCache[$cid] = $component_obj; $this->saveCache($cid, $component_obj); }
php
{ "resource": "" }
q7767
Schema.loadSchema
train
protected function loadSchema($schema_path) { $json = false; if (file_exists($schema_path)) { $contents = file_get_contents($schema_path); $json = json_decode($contents); if ($json == false) { $message = sprintf('Error decoding %s.', $schema_path); $this->logger->error($message); } } else { $message = sprintf('Could not load file %s.', $schema_path); $this->logger->error($message); } return $json; }
php
{ "resource": "" }
q7768
Schema.clearCacheByName
train
public function clearCacheByName($short_name) { $cid = $this->getCid($short_name); unset($this->schemaFiles[$short_name]); $this->clearCache($cid); }
php
{ "resource": "" }
q7769
Schema.warmCache
train
public function warmCache($render_class = 'PatternBuilder\Property\Component\Component') { $this->schemaFiles = $this->getSchemaFiles(); foreach ($this->schemaFiles as $key => $schema_file) { if ($json = $this->loadSchema($schema_file)) { $cid = $this->getCid($key); $component = new $render_class($json); $this->setCache($cid, $component); } } }
php
{ "resource": "" }
q7770
Repository.factory
train
public static function factory($rawFeed) { $repository = new static; $skills = new SkillsRepository(); $exploded = explode("\n", $rawFeed); $spliced = array_splice( $exploded, 0, $skills->count() ); for ($id = 0; $id < count($spliced); $id++) { list($rank, $level, $experience) = explode(',', $spliced[$id]); $skill = $skills->find($id); $repository->push( new Stat( $skill, $level, $rank, $experience ) ); } return $repository; }
php
{ "resource": "" }
q7771
Repository.find
train
public function find($id) { return $this->filter(function (Contract $stat) use ($id) { return $stat->getSkill()->getId() === $id; })->first(); }
php
{ "resource": "" }
q7772
Repository.findByName
train
public function findByName($name) { return $this->filter(function (Contract $stat) use ($name) { return $stat->getSkill()->getName() === $name; })->first(); }
php
{ "resource": "" }
q7773
API.stats
train
public function stats($rsn) { $request = new Request('GET', sprintf($this->endpoints['hiscores'], $rsn)); try { $response = $this->guzzle->send($request); } catch (RequestException $e) { throw new UnknownPlayerException($rsn); } return StatsRepository::factory($response->getBody()); }
php
{ "resource": "" }
q7774
API.calculateCombatLevel
train
public function calculateCombatLevel($attack, $strength, $magic, $ranged, $defence, $constitution, $prayer, $summoning, $float = false) { $highest = max(($attack + $strength), (2 * $magic), (2 * $ranged)); $cmb = floor(0.25 * ((1.3 * $highest) + $defence + $constitution + floor(0.5 * $prayer) + floor(0.5 * $summoning))); return $float ? $cmb : (int) $cmb; }
php
{ "resource": "" }
q7775
Gif.isGifFile
train
public static function isGifFile($filename) { try { $image = new ImageFile($filename); if (strtolower($image->getMime()) !== @image_type_to_mime_type(IMAGETYPE_GIF)) { return false; } return true; } catch (\RuntimeException $ex) { return false; } }
php
{ "resource": "" }
q7776
Lifx.sendRequest
train
public function sendRequest($request, $options = []) { $client = $this->client; $response = $client->send($request, $options); return $response; }
php
{ "resource": "" }
q7777
Lifx.getLights
train
public function getLights($selector = 'all') { $request = new Request('GET', 'lights/' . $selector); $response = $this->sendRequest($request); return $response->getBody(); }
php
{ "resource": "" }
q7778
Lifx.toggleLights
train
public function toggleLights($selector = 'all') { $request = new Request('POST', 'lights/' . $selector . '/toggle'); $response = $this->sendRequest($request); return $response->getBody(); }
php
{ "resource": "" }
q7779
Lifx.setLights
train
public function setLights($selector = 'all', $state = 'on', $duration = 1.0) { $request = new Request('PUT', 'lights/' . $selector . '/state'); $response = $this->sendRequest($request, [ 'query' => [ 'power' => $state, 'duration' => $duration ] ]); return $response->getBody(); }
php
{ "resource": "" }
q7780
Lifx.setColor
train
public function setColor($selector = 'all', $color = 'white', $duration = 1.0, $power_on = true) { $request = new Request('PUT', 'lights/' . $selector . '/state'); $response = $this->sendRequest($request, [ 'query' => [ 'color' => $color, 'duration' => $duration, 'power_on' => $power_on, ] ]); return $response->getBody(); }
php
{ "resource": "" }
q7781
Lifx.breatheLights
train
public function breatheLights( $selector = 'all', $color = 'purple', $from_color = null, $period = 1.0, $cycles = 1.0, $persist = 'false', $power_on = 'true', $peak = 0.5 ) { $request = new Request('POST', 'lights/' . $selector . '/effects/breathe'); $response = $this->sendRequest($request, [ 'query' => [ 'color' => $color, 'from_color' => $from_color, 'period' => $period, 'cycles' => $cycles, 'persist' => $persist, 'power_on' => $power_on, 'peak' => $peak, ] ]); return $response->getBody(); }
php
{ "resource": "" }
q7782
Lifx.pulseLights
train
public function pulseLights( $selector = 'all', $color = 'purple', $from_color = null, $period = 1.0, $cycles = 1.0, $persist = 'false', $power_on = 'true', $duty_cycle = 0.5 ) { $request = new Request('POST', 'lights/' . $selector . '/effects/pulse'); $response = $this->sendRequest($request, [ 'query' => [ 'selector' => $selector, 'color' => $color, 'from_color' => $from_color, 'period' => $period, 'cycles' => $cycles, 'persist' => $persist, 'power_on' => $power_on, 'duty_cycle' => $duty_cycle, ] ]); return $response->getBody(); }
php
{ "resource": "" }
q7783
UrlRewriteObserver.resolveCategoryIds
train
protected function resolveCategoryIds($categoryId, $topLevel = false, $storeViewCode = StoreViewCodes::ADMIN) { // return immediately if this is the absolute root node if ((integer) $categoryId === 1) { return; } // load the data of the category with the passed ID $category = $this->getCategory($categoryId, $storeViewCode); // query whether or not the product has already been related if (!in_array($categoryId, $this->productCategoryIds)) { if ($topLevel) { // relate it, if the category is top level $this->productCategoryIds[] = $categoryId; } elseif ((integer) $category[MemberNames::IS_ANCHOR] === 1) { // also relate it, if the category is not top level, but has the anchor flag set $this->productCategoryIds[] = $categoryId; } else { $this->getSubject() ->getSystemLogger() ->debug(sprintf('Don\'t create URL rewrite for category "%s" because of missing anchor flag', $category[MemberNames::PATH])); } } // load the root category $rootCategory = $this->getRootCategory(); // try to resolve the parent category IDs if ($rootCategory[MemberNames::ENTITY_ID] !== ($parentId = $category[MemberNames::PARENT_ID])) { $this->resolveCategoryIds($parentId, false); } }
php
{ "resource": "" }
q7784
UrlRewriteObserver.prepareUrlRewriteProductCategoryAttributes
train
protected function prepareUrlRewriteProductCategoryAttributes() { // return the prepared product return $this->initializeEntity( array( MemberNames::PRODUCT_ID => $this->entityId, MemberNames::CATEGORY_ID => $this->categoryId, MemberNames::URL_REWRITE_ID => $this->urlRewriteId ) ); }
php
{ "resource": "" }
q7785
UrlRewriteObserver.prepareTargetPath
train
protected function prepareTargetPath(array $category) { // query whether or not, the category is the root category if ($this->isRootCategory($category)) { $targetPath = sprintf('catalog/product/view/id/%d', $this->entityId); } else { $targetPath = sprintf('catalog/product/view/id/%d/category/%d', $this->entityId, $category[MemberNames::ENTITY_ID]); } // return the target path return $targetPath; }
php
{ "resource": "" }
q7786
UrlRewriteObserver.prepareMetadata
train
protected function prepareMetadata(array $category) { // initialize the metadata $metadata = array(); // query whether or not, the passed category IS the root category if ($this->isRootCategory($category)) { return; } // if not, set the category ID in the metadata $metadata[UrlRewriteObserver::CATEGORY_ID] = (integer) $category[MemberNames::ENTITY_ID]; // return the metadata return $metadata; }
php
{ "resource": "" }
q7787
UrlRewriteObserver.isRootCategory
train
protected function isRootCategory(array $category) { // load the root category $rootCategory = $this->getRootCategory(); // compare the entity IDs and return the result return $rootCategory[MemberNames::ENTITY_ID] === $category[MemberNames::ENTITY_ID]; }
php
{ "resource": "" }
q7788
Client.fwrite
train
private function fwrite($stream, $bytes) { if (!\strlen($bytes)) { return 0; } $result = @fwrite($stream, $bytes); if (0 !== $result) { // In cases where some bytes are witten (`$result > 0`) or // an error occurs (`$result === false`), the behavior of fwrite() is // correct. We can return the value as-is. return $result; } // If we make it here, we performed a 0-length write. Try to distinguish // between EAGAIN and EPIPE. To do this, we're going to `stream_select()` // the stream, write to it again if PHP claims that it's writable, and // consider the pipe broken if the write fails. $read = []; $write = [$stream]; $except = []; @stream_select($read, $write, $except, 0); if (!$write) { // The stream isn't writable, so we conclude that it probably really is // blocked and the underlying error was EAGAIN. Return 0 to indicate that // no data could be written yet. return 0; } // If we make it here, PHP **just** claimed that this stream is writable, so // perform a write. If the write also fails, conclude that these failures are // EPIPE or some other permanent failure. $result = @fwrite($stream, $bytes); if (0 !== $result) { // The write worked or failed explicitly. This value is fine to return. return $result; } // We performed a 0-length write, were told that the stream was writable, and // then immediately performed another 0-length write. Conclude that the pipe // is broken and return `false`. return false; }
php
{ "resource": "" }
q7789
GettersSetters.&
train
public function & GetFilters () { $filters = []; foreach ($this->filters as $direction => $handler) $filters[$direction] = $handler[1]; return $filters; }
php
{ "resource": "" }
q7790
GettersSetters.&
train
public function & SetFilters (array $filters = []) { foreach ($filters as $direction => $handler) $this->SetFilter($handler, $direction); /** @var $this \MvcCore\Route */ return $this; }
php
{ "resource": "" }
q7791
GettersSetters.GetFilter
train
public function GetFilter ($direction = \MvcCore\IRoute::CONFIG_FILTER_IN) { return isset($this->filters[$direction]) ? $this->filters[$direction] : NULL; }
php
{ "resource": "" }
q7792
GettersSetters.&
train
public function & SetFilter ($handler, $direction = \MvcCore\IRoute::CONFIG_FILTER_IN) { // there is possible to call any `callable` as closure function in variable // except forms like `'ClassName::methodName'` and `['childClassName', 'parent::methodName']` // and `[$childInstance, 'parent::methodName']`. $closureCalling = ( (is_string($handler) && strpos($handler, '::') !== FALSE) || (is_array($handler) && strpos($handler[1], '::') !== FALSE) ) ? FALSE : TRUE; /** @var $this \MvcCore\Route */ $this->filters[$direction] = [$closureCalling, $handler]; return $this; }
php
{ "resource": "" }
q7793
Flip.setDirection
train
public function setDirection($direction) { if (!in_array($direction, self::$supportedFlipDirection)) { throw new \InvalidArgumentException(sprintf( '"%s" Is Not Valid Flip Direction', (string) $direction )); } $this->flipDirection = $direction; return $this; }
php
{ "resource": "" }
q7794
Facet.buildParam
train
public function buildParam($facetParam, $field) { $param = ''; // Parameter is per-field if ($field !== null) { $param .= 'f.' . $field . '.'; } $param .= $facetParam; return $param; }
php
{ "resource": "" }
q7795
UrlRewriteUpdateObserver.removeExistingUrlRewrite
train
protected function removeExistingUrlRewrite(array $urlRewrite) { // load request path $requestPath = $urlRewrite[MemberNames::REQUEST_PATH]; // query whether or not the URL rewrite exists and remove it, if available if (isset($this->existingUrlRewrites[$requestPath])) { unset($this->existingUrlRewrites[$requestPath]); } }
php
{ "resource": "" }
q7796
UrlRewriteUpdateObserver.getCategoryIdFromMetadata
train
protected function getCategoryIdFromMetadata(array $attr) { // load the metadata of the passed URL rewrite entity $metadata = $this->getMetadata($attr); // return the category ID from the metadata return (integer) $metadata[UrlRewriteObserver::CATEGORY_ID]; }
php
{ "resource": "" }
q7797
UrlRewriteUpdateObserver.initializeUrlRewriteProductCategory
train
protected function initializeUrlRewriteProductCategory($attr) { // try to load the URL rewrite product category relation if ($urlRewriteProductCategory = $this->loadUrlRewriteProductCategory($attr[MemberNames::URL_REWRITE_ID])) { return $this->mergeEntity($urlRewriteProductCategory, $attr); } // simple return the URL rewrite product category return $attr; }
php
{ "resource": "" }
q7798
UrlRewriteUpdateObserver.getMetadata
train
protected function getMetadata($urlRewrite) { // initialize the array with the metaddata $metadata = array(); // try to unserialize the metadata from the passed URL rewrite if (isset($urlRewrite[MemberNames::METADATA])) { $metadata = json_decode($urlRewrite[MemberNames::METADATA], true); } // query whether or not a category ID has been found if (isset($metadata[UrlRewriteObserver::CATEGORY_ID])) { // if yes, return the metadata return $metadata; } // if not, append the ID of the root category $rootCategory = $this->getRootCategory(); $metadata[UrlRewriteObserver::CATEGORY_ID] = (integer) $rootCategory[MemberNames::ENTITY_ID]; // and return the metadata return $metadata; }
php
{ "resource": "" }
q7799
VersionCollection.getNextVersion
train
public function getNextVersion($from) { $found = false; foreach (array_keys($this->versions) as $timestamp) { if ($from === null) { return $timestamp; } if ($timestamp == $from) { $found = true; continue; } if ($found) { return $timestamp; } } return; }
php
{ "resource": "" }