_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q27400
Builder.build
train
protected function build( array $data, $depth = 0, $prevKey = null ) { $valueOutput = ""; $arrayOutput = ""; if( $depth > 2 ) { throw new ExceededMaxDepthException("Max INI Depth of 2 Exceeded"); } $position = 0; foreach( $data as $key => $val ) { if( $this->skipNullValues && $val === null ) { c...
php
{ "resource": "" }
q27401
Builder.escape
train
public function escape( $value ) { $value = (string)$value; if( $this->enableBool ) { if( $value == '' ) { return 'false'; } elseif( $value == '1' ) { return 'true'; } } if( $this->enableNumeric && is_numeric($value) ) { return (string)$value; } if( $this->enableAlphaNumeric && is_str...
php
{ "resource": "" }
q27402
Partials.load
train
public static function load($directoryName = 'filters'): array { $files = static::getFilePattern($directoryName); return collect(glob($files)) ->map(function ($filename) { return include $filename; }) ->flatten(1) ->toArray(); }
php
{ "resource": "" }
q27403
JmsExtractor.getNestedTypeInArray
train
private function getNestedTypeInArray(PropertyMetadata $item) { if (isset($item->type['name']) && in_array($item->type['name'], array('array', 'ArrayCollection'))) { if (isset($item->type['params'][1]['name'])) { // E.g. array<string, MyNamespaceMyObject> return $...
php
{ "resource": "" }
q27404
RelationProcessor.queue
train
public function queue($relation, array $args) { $this->queue[] = array( self::PARAM_RELATION => $relation, self::PARAM_ARGS => $args ); }
php
{ "resource": "" }
q27405
RelationProcessor.process
train
public function process(array $rows) { foreach ($this->queue as $queue) { // Just references $relation = $queue[self::PARAM_RELATION]; $args = $queue[self::PARAM_ARGS]; switch ($relation) { case 'asOneToMany': $relation = n...
php
{ "resource": "" }
q27406
RelationProcessor.extractPkName
train
private function extractPkName($table) { if (is_null($this->pk)) { // This has been tested only in MySQL so far $row = $this->db->showKeys() ->from($table) ->whereEquals('Key_name', 'PRIMARY') ->getSt...
php
{ "resource": "" }
q27407
TSQLQueryBuilderBasic.build
train
protected function build() { $sql = "SELECT\n\t" . $this->columns . "\n" . $this->from . "\n" . ($this->join ? $this->join : null) . ($this->where ? $this->where . "\n" : null) . ($this->groupby ? $this->groupby . "\n" : null) ...
php
{ "resource": "" }
q27408
TSQLQueryBuilderBasic.createJoin
train
private function createJoin($table, $condition, $type) { $this->join .= $type . " JOIN " . $this->prefix . $table . "\n\tON " . $condition . "\n"; return $this; }
php
{ "resource": "" }
q27409
CaptchaFactory.build
train
public static function build(array $options = array(), $sessionBag = null) { if (is_null($sessionBag)) { $sessionBag = new StandaloneSessionBag(); } // Default fonts directory $fontsDir = __DIR__ . '/Fonts/'; $fontFile = isset($options['font']) ? $options['font']...
php
{ "resource": "" }
q27410
AjaxChoiceLoader.resetSearchChoices
train
protected function resetSearchChoices() { $filteredChoices = []; foreach ($this->choices as $key => $choice) { if (\is_array($choice)) { $this->resetSearchGroupChoices($filteredChoices, $key, $choice); } else { $this->resetSearchSimpleChoices(...
php
{ "resource": "" }
q27411
AjaxChoiceLoader.resetSearchGroupChoices
train
protected function resetSearchGroupChoices(array &$filteredChoices, $group, array $choices) { foreach ($choices as $key => $choice) { list($id, $label) = $this->getIdAndLabel($key, $choice); if (false !== stripos($label, $this->search) && !\in_array($id, $this->getIds())) { ...
php
{ "resource": "" }
q27412
AjaxChoiceLoader.resetSearchSimpleChoices
train
protected function resetSearchSimpleChoices(array &$filteredChoices, $key, $choice) { list($id, $label) = $this->getIdAndLabel($key, $choice); if (false !== stripos($label, $this->search) && !\in_array($id, $this->getIds())) { $filteredChoices[$key] = $choice; } }
php
{ "resource": "" }
q27413
HttpCache.configure
train
public function configure($timestamp, $ttl) { if ($this->isModified($timestamp)) { $this->appendLastModified($timestamp, $ttl); } else { $this->appendNotModified($ttl); } }
php
{ "resource": "" }
q27414
HttpCache.appendLastModified
train
private function appendLastModified($timestamp, $maxAge) { $headers = array( 'Cache-Control' => sprintf('public, max-age=%s', $maxAge), 'Last-Modified' => gmdate('D, j M Y H:i:s', $timestamp).' GMT' ); $this->headerBag->setStatusCode(200) ->ap...
php
{ "resource": "" }
q27415
HttpCache.isModified
train
private function isModified($timestamp) { $target = 'If-Modified-Since'; if ($this->headerBag->hasRequestHeader($target)) { $sinceTimestamp = strtotime($this->headerBag->getRequestHeader($target)); if ($sinceTimestamp != false && $timestamp <= $sinceTimestamp) { ...
php
{ "resource": "" }
q27416
FilterBlockRepository.findByArea
train
public function findByArea($area) { $qb = $this->getQueryBuilder(); $qb ->addSelect("fb_fa") ->addSelect("fb_fa_f") ->innerJoin("fb.filterAddeds", "fb_fa") ->innerJoin("fb_fa.filter", "fb_fa_f") ->andWhere("fb.area = :area") ->s...
php
{ "resource": "" }
q27417
DotArray.add
train
public static function add(array $subjectArray, $newElementKey, $newElementValue) { if (!is_null(self::get($subjectArray, $newElementKey))) { return $subjectArray; } self::set($subjectArray, $newElementKey, $newElementValue); return $subjectArray; }
php
{ "resource": "" }
q27418
DotArray.exists
train
public static function exists($arrayOrArrayAccess, $keyOrOffset) { if ($arrayOrArrayAccess instanceof ArrayAccess) { return $arrayOrArrayAccess->offsetExists($keyOrOffset); } return array_key_exists($keyOrOffset, $arrayOrArrayAccess); }
php
{ "resource": "" }
q27419
DotArray.flatten
train
public static function flatten(array $subjectArray, $depth = INF) { $flattenArray = []; foreach ($subjectArray as $value) { if (!is_array($value)) { $flattenArray[] = $value; } elseif ($depth === 1) { $flattenArray = array_merge($flattenArray,...
php
{ "resource": "" }
q27420
DotArray.flattenIntoDots
train
public static function flattenIntoDots(array $subjectArray, $keyPrefix = '') { $flattenArray = []; foreach ($subjectArray as $key => $value) { $newKey = $keyPrefix . $key; if (is_array($value) && !empty($value)) { $flattenArray = array_merge($flattenArray, s...
php
{ "resource": "" }
q27421
DotArray.get
train
public static function get($subjectArrayOrObject, $dotNotationKeys, $defaultValue = null) { if (is_null($dotNotationKeys)) { return $subjectArrayOrObject; } return self::walkArrayOrObject($subjectArrayOrObject, $dotNotationKeys, $defaultValue); }
php
{ "resource": "" }
q27422
DotArray.initEmptyArray
train
protected static function initEmptyArray(array &$subjectArray, $key) { if (!isset($subjectArray[$key]) || !is_array($subjectArray[$key])) { $subjectArray[$key] = []; } return $subjectArray; }
php
{ "resource": "" }
q27423
DotArray.isArrayElementValidArray
train
protected static function isArrayElementValidArray(array $array, $key, $validIfNotEmpty = true) { if (!isset($array[$key])) { return false; } if (!is_array($array[$key])) { return false; } return (!$validIfNotEmpty || !empty($array[$key])); }
php
{ "resource": "" }
q27424
DotArray.removeSegments
train
protected static function removeSegments(array &$array, $key) { $parts = self::explodeDotNotationKeys($key); while (count($parts) > 1) { $part = array_shift($parts); if (isset($array[$part]) && is_array($array[$part])) { $array =& $array[$part]; }...
php
{ "resource": "" }
q27425
Comment.fieldLabels
train
public function fieldLabels($includerelations = true) { $labels = parent::fieldLabels($includerelations); $commentLabels = array( 'Title' => _t('Comment.TITLE', 'Subject'), 'Name' => _t('Comment.NAME', 'Name'), 'Email' => _t('Comment.EMAIL...
php
{ "resource": "" }
q27426
Comment.getFrontEndFields
train
public function getFrontEndFields($params = null) { $fields = parent::getFrontEndFields($params); $fields->removeByName(array( 'MD5Email', 'AkismetMarked', 'Visible', 'ShowGravatar', 'News', )); $fields->replaceField('Email'...
php
{ "resource": "" }
q27427
Comment.onBeforeWrite
train
public function onBeforeWrite() { parent::onBeforeWrite(); $siteConfig = SiteConfig::current_site_config(); if ($siteConfig->MustApprove) { $this->Visible = false; } if (substr($this->URL, 0, 4) != 'http' && $this->URL != '') { $this->URL = 'http://' ....
php
{ "resource": "" }
q27428
Comment.getGravatar
train
public function getGravatar() { $siteConfig = SiteConfig::current_site_config(); $default = ''; $gravatarSize = '32'; if ($siteConfig->DefaultGravatarImageID != 0) { $default = urlencode(Director::absoluteBaseURL() . $siteConfig->DefaultGravatarImage()->Link()); }...
php
{ "resource": "" }
q27429
Comment.onAfterWrite
train
public function onAfterWrite() { $SiteConfig = SiteConfig::current_site_config(); /** No, really, I mean it. Change this. When spambots find your site, 30 e-mails an hour is NORMAL! */ /** @var Email $mail */ $mail = Email::create(); $mail->setTo($SiteConfig->NewsEmail); ...
php
{ "resource": "" }
q27430
Comment.checkAkismet
train
private function checkAkismet(SiteConfig $siteConfig) { try { $akismet = new Akismet(Director::absoluteBaseURL(), $siteConfig->AkismetKey); $akismet->setCommentAuthor($this->Name); $akismet->setCommentContent($this->Comment); $akismet->setCommentAuthorEmail($t...
php
{ "resource": "" }
q27431
AzureDeployment.create
train
public function create() { $filesystem = new Filesystem(); if (! file_exists($this->configDir)) { $filesystem->mkdir($this->configDir, 0777); $filesystem->copy(__DIR__ . '/../Resources/role_template/ServiceConfiguration.cscfg', $this->configDir . '/ServiceConfiguration.cscfg'...
php
{ "resource": "" }
q27432
AzureDeployment.createRole
train
public function createRole($name, $type = self::ROLE_WEB, $override = false) { $serviceDefinition = $this->getServiceDefinition(); $serviceConfig = $this->getServiceConfiguration(); switch ($type) { case self::ROLE_WEB: $serviceDefinition->addWebRole($nam...
php
{ "resource": "" }
q27433
RpcClient.configure
train
public function configure(array $config = []):void { $config = array_intersect_key($config, array_flip(['rpcHost', 'rpcPort', 'rpcPassword', 'rpcBaseRoute'])); foreach ($config as $key => $value) { $this->{$key} = $value; } }
php
{ "resource": "" }
q27434
AntiCaptcha.solve
train
public function solve(string $challengeUrl) : string { $result = $this->createTask($challengeUrl); if ($result['errorId'] !== 0) { $this->getLogger()->error( "Received AntiCaptcha ErrorId: {ErrorId}: {ErrorDescription}", [ 'ErrorId' ...
php
{ "resource": "" }
q27435
AntiCaptcha.checkResult
train
protected function checkResult($taskId) { $this->getLogger()->debug("Requesting Task Status for task {TaskId}", ['TaskId' => $taskId]); $postData = [ 'clientKey' => $this->apiKey, 'taskId' => $taskId ]; try { $response = $this->getClient()->po...
php
{ "resource": "" }
q27436
Node.accept
train
public function accept(NodeElementVisitorInterface $visitor) { $visitor->visitNodeFirst($this); foreach ($this->elements as $element) { $element->accept($visitor); } $visitor->visitNode($this); }
php
{ "resource": "" }
q27437
SourceTrait.source
train
public static function source(): DocumentSource { /** * Container to be received via global scope. * * @var ContainerInterface $container */ //Via global scope $container = self::staticContainer(); if (empty($container)) { //Via global...
php
{ "resource": "" }
q27438
HttpService.setCurlProxyOptions
train
protected function setCurlProxyOptions($adapter) { $adapter->setCurlOption(CURLOPT_PROXY, $this->proxyConfig['proxy_host']); if (!empty($this->proxyConfig['proxy_port'])) { $adapter ->setCurlOption(CURLOPT_PROXYPORT, $this->proxyConfig['proxy_port']); } }
php
{ "resource": "" }
q27439
HttpService.proxify
train
public function proxify(\Zend\Http\Client $client, array $options = []) { if ($this->proxyConfig) { $host = $client->getUri()->getHost(); if (!$this->isLocal($host)) { $proxyType = $this->proxyConfig['proxy_type'] ?? 'default'; if ($proxyType == 'soc...
php
{ "resource": "" }
q27440
HttpService.get
train
public function get($url, array $params = [], $timeout = null, array $headers = [] ) { if ($params) { $query = $this->createQueryString($params); if (strpos($url, '?') !== false) { $url .= '&' . $query; } else { $url .= '?' . $query...
php
{ "resource": "" }
q27441
HttpService.post
train
public function post($url, $body = null, $type = 'application/octet-stream', $timeout = null, array $headers = [] ) { $client = $this->createClient($url, \Zend\Http\Request::METHOD_POST, $timeout); $client->setRawBody($body); $client->setHeaders( array_merge( ...
php
{ "resource": "" }
q27442
HttpService.postForm
train
public function postForm($url, array $params = [], $timeout = null) { $body = $this->createQueryString($params); return $this->post($url, $body, \Zend\Http\Client::ENC_URLENCODED, $timeout); }
php
{ "resource": "" }
q27443
HttpService.createClient
train
public function createClient($url = null, $method = \Zend\Http\Request::METHOD_GET, $timeout = null ) { $client = new \Zend\Http\Client(); $client->setMethod($method); if (!empty($this->defaults)) { $client->setOptions($this->defaults); } if (null !== $thi...
php
{ "resource": "" }
q27444
HttpService.send
train
protected function send(\Zend\Http\Client $client) { try { $response = $client->send(); } catch (\Zend\Http\Client\Exception\RuntimeException $e) { throw new Exception\RuntimeException( sprintf('Zend HTTP Client exception: %s', $e), -1, ...
php
{ "resource": "" }
q27445
TypeResolver.getArrayType
train
public static function getArrayType(string $type): ?string { if (substr($type, -2) !== '[]' || strlen($type) === 2) { return null; } return substr($type, 0, -2); }
php
{ "resource": "" }
q27446
TypeResolver.resolveType
train
public static function resolveType($value): string { if (is_array($value)) { if (count($value) === 0) { return 'array'; } return self::resolveType($value[0]) . '[]'; } return is_object($value) ? get_class($value) : gettype($value); }
php
{ "resource": "" }
q27447
RequestTrait.makeRequest
train
public function makeRequest( string $relativeUrl, array $variables = [], string $httpMethod = ClientInterface::HTTP_GET, bool $shouldCache = true, string $contentType = ClientInterface::CONTENT_TYPE_JSON ) : BookboonResponse { if (strpos($relativeUrl, '/') !== 0) { ...
php
{ "resource": "" }
q27448
DecisionNode.makeLeafEvaluation
train
private function makeLeafEvaluation(): Evaluation { $result = new Evaluation(); $result->age = $this->depthLeft; $result->score = $this->state->evaluateScore($this->objectivePlayer); return $result; }
php
{ "resource": "" }
q27449
DecisionNode.getChildResult
train
private function getChildResult(GameState $stateAfterMove): TraversalResult { $nextPlayerIsFriendly = $stateAfterMove->getNextPlayer()->isFriendsWith($this->objectivePlayer); $nextDecisionPoint = new static( $this->objectivePlayer, $stateAfterMove, $this->depthLef...
php
{ "resource": "" }
q27450
DecisionNode.isIdealOver
train
private function isIdealOver(Evaluation $a, Evaluation $b): bool { $ideal = $this->type == NodeType::MIN() ? Evaluation::getWorstComparator() : Evaluation::getBestComparator(); $idealEvaluationResult = $ideal($a, $b); return $idealEvaluationResult > 0; }
php
{ "resource": "" }
q27451
ExporterManager.addChainModel
train
public function addChainModel(ChainModel $chainModel) { if(isset($this->chainModels[$chainModel->getId()])){ throw new InvalidArgumentException(sprintf("The chain model to '%s' is already added, please add you model to tag '%s'",$chainModel->getClassName(),$chainModel->getClassName())); } ...
php
{ "resource": "" }
q27452
ExporterManager.getChainModel
train
protected function getChainModel($id) { if(!isset($this->chainModels[$id])){ throw new InvalidArgumentException(sprintf("The chain model is not added or the id '%s' is invalid.",$id)); } return $this->chainModels[$id]; }
php
{ "resource": "" }
q27453
ExporterManager.getOption
train
public function getOption($name) { if(!isset($this->options[$name])){ throw new InvalidArgumentException(sprintf("The option name '%s' is invalid, available are %s.",$name, implode(",",array_keys($this->options)))); } return $this->options[$name]; }
php
{ "resource": "" }
q27454
ExporterManager.generate
train
public function generate($idChain,$name,array $options = []) { $chainModel = $this->resolveChainModel($idChain, $options); $modelDocument = $chainModel->getModel($name); if(isset($options["fileName"]) && !empty($options["fileName"])){ $modelDocument->setFileName($options["fi...
php
{ "resource": "" }
q27455
ExporterManager.generateWithSource
train
public function generateWithSource($id,$idChain,$name,$output,array $options = []) { if(!$this->adapter){ throw new RuntimeException(sprintf("The adapter must be set for enable this feature.")); } $chainModel = $this->getChainModel($idChain); $className = $chainModel->getClas...
php
{ "resource": "" }
q27456
ExporterManager.resolveChainModel
train
public function resolveChainModel($idChain,array $options = []) { $resolver = new OptionsResolver(); $resolver->setDefaults([ "base_path" => null, "sub_path" => null, "data" => [], "fileName" => null, ]); $resolver->setAllowedTypes("data","...
php
{ "resource": "" }
q27457
TaskSubTypeResolver.getOptions
train
public function getOptions() { $types = $this->types(); array_walk($types, function (&$classname) { $classname = $classname::getLabel(); }); return $types; }
php
{ "resource": "" }
q27458
TaskSubTypeResolver.getClassname
train
public function getClassname($type) { $types = $this->types(); if (isset($types[$type])) { return $types[$type]; } return static::DEFAULT_CLASSNAME; }
php
{ "resource": "" }
q27459
TaskSubTypeResolver.getPluginTypes
train
protected function getPluginTypes($pattern, $plugin_path) { $types = []; $project_root = ProjectX::projectRoot(); foreach ($this->getInstalledPluginNamespaces() as $name => $namespace) { $plugin_dir = "$project_root/vendor/$name"; if (!file_exists($plugin_dir)) { ...
php
{ "resource": "" }
q27460
TaskSubTypeResolver.getInstalledPluginNamespaces
train
protected function getInstalledPluginNamespaces() { $cache_item = $this->cache->getItem('plugins.installed'); $project_root = ProjectX::projectRoot(); $installed_file = "$project_root/vendor/composer/installed.json"; if (!$cache_item->isHit() && file_exists($installed_f...
php
{ "resource": "" }
q27461
Commands.handleCommand
train
public static function handleCommand() { try { global $argv; $tokens = array_slice($argv, 1); if (empty($tokens)) { throw new RuntimeException("Command name is required !!"); } $commandName = (string)$tokens[0]; $commandTo...
php
{ "resource": "" }
q27462
Commands.executeCommand
train
public static function executeCommand($commandName, array $commandParameters) { if (isset(self::$commands[$commandName])) { $commandAction = self::$commands[$commandName]; } else { $commandsBaseNamespace = get_property("cli.commands_base_namespace"); if (!empt...
php
{ "resource": "" }
q27463
Helper.get_templates_for_class
train
public static function get_templates_for_class($classname) { $classes = ClassInfo::ancestry($classname); $classes = array_reverse($classes); $remove_classes = self::config()->classes_to_remove; $return = array(); array_push($classes, "Catalogue", "Page"); foreach ($...
php
{ "resource": "" }
q27464
Helper.generate_no_image
train
public static function generate_no_image() { // See if the image is already in the DB $no_image = "no-image.png"; $image = File::find($no_image); // If not, create new record if (!isset($image)) { $reflector = new ReflectionClass(self::class); $curr_f...
php
{ "resource": "" }
q27465
CookieAuth.onBeforeSend
train
private function onBeforeSend(RequestInterface $request, array &$options) { $base_uri = null; if (isset($options['base_uri']) && $options['base_uri']) { if ($options['base_uri'] instanceof UriInterface) { $base_uri = $options['base_uri']; } } ...
php
{ "resource": "" }
q27466
CookieAuth.onReceive
train
public function onReceive(RequestInterface $request, ResponseInterface $response) { $this->coockieJar->extractCookies($request, $response); return $response; }
php
{ "resource": "" }
q27467
CookieAuth.getCookieJar
train
public function getCookieJar(array &$options, $base_uri = null) { if ($this->coockieJar->count() <= 0 || !$this->loginMade) { $this->obtainCookies($options, $base_uri); } if (isset($options['auth-cookie'])) { unset($options['auth-cookie']); } return ...
php
{ "resource": "" }
q27468
CookieAuth.obtainCookies
train
protected function obtainCookies(array &$options, $base_uri = null) { $client = new Client(); $loginOptions = [ 'debug' => isset($options['debug']) && $options['debug'] ? true : false, 'allow_redirects' => false, 'cookies' => $this->coockieJar ]; ...
php
{ "resource": "" }
q27469
Http.setCacheable
train
public function setCacheable($minutes) { if ($minutes <= 0) { $this->setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate'); $this->setHeader('Expires', '-1'); $this->setHeader('Pragma', 'no-cache'); } else { $this->setHeader('Expir...
php
{ "resource": "" }
q27470
Formula.parse
train
public function parse() { $parser = $this->getParser(); $parser->parse($this); return $parser->getTokenCollector() ->build($this->getRenderer()); }
php
{ "resource": "" }
q27471
ForeignChars.romanize
train
public static function romanize($string) { foreach (self::$chars as $regex => $replacement) { // u enables Unicode $string = preg_replace($regex . 'u', $replacement, $string); } return $string; }
php
{ "resource": "" }
q27472
PSR0.addDir
train
public function addDir($dir) { if (!is_dir($dir)) { throw new LogicException(sprintf( 'Provided path "%s" is not a directory', $dir )); } array_push($this->dirs, $dir); return $this; }
php
{ "resource": "" }
q27473
Connection.connect
train
public function connect() { list($host, $port) = explode(':', $this->getServer()); if ($this->stream->open($host, $port, $this->getTimeout()) === false) { throw new Exception(sprintf('Cannot connect to server %s', $this->getServer()), Exception::SERVER_OFFLINE); } return...
php
{ "resource": "" }
q27474
Connection.pauseTube
train
public function pauseTube($tube, $delay) { $this->dispatch(new Command\PauseTube($tube, $delay)); return true; }
php
{ "resource": "" }
q27475
Connection.validateResponse
train
public function validateResponse($response) { if ($response === false) { throw new Exception( 'Error reading data from the server.', Exception::SERVER_READ ); } if ($response === 'BAD_FORMAT') { throw new Exception( ...
php
{ "resource": "" }
q27476
Connection.dispatch
train
protected function dispatch(Command $command) { // re-connect if we have timed out if ($this->isTimedOut() === true) { $this->close(); $this->connect(); } // construct message $message = $command->getCommand() . "\r\n"; if (($data = $command-...
php
{ "resource": "" }
q27477
IntroService.newLog
train
public function newLog($introId,$user) { $introClass = $this->config['intro_class']; $em = $this->doctrine->getManager(); $intro = $em->getRepository($introClass)->find($introId); $introLog = null; if($intro){ $introLogClass = $this->config['intro_log_class']; ...
php
{ "resource": "" }
q27478
TextUtils.strModified
train
public static function strModified($target, Closure $callback) { $modified = $callback($target); return md5($target) !== md5($modified); }
php
{ "resource": "" }
q27479
TextUtils.serial
train
public static function serial($id, $unique = true, $upper = true, $length = 25, $portion = 5) { // If unique is defined if ($unique === true) { $salt = substr(sha1(mt_rand()), 0, 20); $id .= $salt; } // MD5 is great enough $hash = md5($id); /...
php
{ "resource": "" }
q27480
TextUtils.normalizeColumn
train
public static function normalizeColumn($string) { $parts = explode('_', $string); foreach ($parts as &$part) { $part = ucfirst($part); } return join(' ', $parts); }
php
{ "resource": "" }
q27481
TextUtils.randomString
train
public static function randomString($length, $method = 'alnum') { $types = array( 'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'numeric' => '0123456789' ); ...
php
{ "resource": "" }
q27482
TextUtils.getNeedlePositions
train
public static function getNeedlePositions($haystack, $needle) { $start = 0; $result = array(); $needleLength = strlen($needle); while (($pos = strpos($haystack, $needle, $start)) !== false) { $start = $pos + 1; // Calculate starting and ending positions ...
php
{ "resource": "" }
q27483
TextUtils.sluggify
train
public static function sluggify($string, $romanize = true) { $generator = new SlugGenerator($romanize); return $generator->generate($string); }
php
{ "resource": "" }
q27484
TextUtils.studly
train
public static function studly($input) { $input = mb_convert_case($input, \MB_CASE_TITLE, 'UTF-8'); $input = str_replace(array('-', '_'), ' ', $input); $input = str_replace(' ', '', $input); return $input; }
php
{ "resource": "" }
q27485
TextUtils.explodeText
train
public static function explodeText($text, $carriage = "\r") { // Default delimiters $delimiters = array('!', '?', '.'); if ($carriage !== null) { array_push($delimiters, $carriage); } return self::multiExplode($text, $delimiters); }
php
{ "resource": "" }
q27486
TextUtils.multiExplode
train
public static function multiExplode($string, array $delimiters, $keepDelimiters = true) { if ($keepDelimiters === true) { // Ensure special characters are escaped foreach ($delimiters as &$delimiter) { $delimiter = preg_quote($delimiter); } //...
php
{ "resource": "" }
q27487
Aoe_Api2_Model_Resource.mapAttributes
train
protected function mapAttributes(array &$data) { $map = $this->attributeMap; $out = []; foreach ($data as $key => &$value) { if (isset($map[$key])) { $key = $map[$key]; } $out[$key] = $value; } return $out; }
php
{ "resource": "" }
q27488
Aoe_Api2_Model_Resource.unmapAttributes
train
protected function unmapAttributes(array &$data) { $map = array_flip($this->attributeMap); $out = []; foreach ($data as $key => &$value) { if (isset($map[$key])) { $key = $map[$key]; } $out[$key] = $value; } return $out; ...
php
{ "resource": "" }
q27489
Aoe_Api2_Model_Resource.fixTypes
train
protected function fixTypes(array $data, array $typeMap, $currencyCode) { if (empty($typeMap)) { $typeMap = $this->attributeTypeMap; } if (empty($currencyCode)) { $currencyCode = $this->_getStore()->getDefaultCurrencyCode(); } foreach ($typeMap as $c...
php
{ "resource": "" }
q27490
DirectoryBag.getPath
train
public function getPath($id, $file = null) { if (is_null($file)) { return sprintf('%s/%s/', $this->baseDir, $id); } else { return sprintf('%s/%s/%s', $this->baseDir, $id, $file); } }
php
{ "resource": "" }
q27491
DirectoryBag.upload
train
public function upload($id, array $files) { if (!empty($files)) { $uploader = new FileUploader(); foreach ($files as $file) { if (!$uploader->upload($this->getPath($id), $files)) { return false; } } return ...
php
{ "resource": "" }
q27492
DirectoryBag.remove
train
public function remove($id, $filename = null) { if ($filename == null) { return FileManager::rmdir($this->getPath($id)); } else { return FileManager::rmfile($this->getPath($id, $filename)); } }
php
{ "resource": "" }
q27493
ImageGenerator.generate
train
private function generate($text) { // The implementation of generation algorithm is base on this: // https://github.com/yiisoft/yii/blob/master/framework/web/widgets/captcha/CCaptchaAction.php // First and foremost we need to create a resource $image = imagecreatetruecolor($this->pa...
php
{ "resource": "" }
q27494
CacheEngine.initialize
train
public function initialize() { // Load data from a file file $this->storage->load(); $data = $this->storage->getContent(); // Set initial array signature $this->arraySignature->setData($data); $this->arrayCache->setData($data); // Run garbage collection ...
php
{ "resource": "" }
q27495
CacheEngine.save
train
public function save() { $data = $this->arrayCache->getData(); // Do save in case we have at least one change in configuration if ($this->arraySignature->hasChanged($data)) { if (!$this->write()) { return false; } } return true; }
php
{ "resource": "" }
q27496
CacheEngine.set
train
public function set($key, $value, $ttl) { $this->arrayCache->set($key, $value, $ttl, time()); return $this; }
php
{ "resource": "" }
q27497
ClassMapLoader.getClassNameByPath
train
private function getClassNameByPath($path) { foreach ($this->map as $key => $value) { if ($value === $path) { return $key; } } return null; }
php
{ "resource": "" }
q27498
Timer.getSummary
train
public function getSummary() { $this->stop(); if ($this->start !== null) { $summary = $this->end - $this->start; $summary = round($summary, 2); return $summary; } else { throw new LogicException('Timer was not started'); } }
php
{ "resource": "" }
q27499
FormAttribute.getOldAttribute
train
private function getOldAttribute($name) { if ($this->hasOldAttribute($name)) { $collection = $this->getOldAttributes(); return $collection[$name]; } else { // Error } }
php
{ "resource": "" }