_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q13100
AbstractModule.hasConfig
train
final public function hasConfig($key = null) { $config = $this->getConfig(); if (is_null($key)) { return !empty($config); } else { return array_key_exists($key, $config); } }
php
{ "resource": "" }
q13101
AbstractModule.getServices
train
final public function getServices() { if (is_null($this->serviceProviders)) { $this->serviceProviders = $this->getServiceProviders(); } return $this->serviceProviders; }
php
{ "resource": "" }
q13102
DependencyInjectionContainer.register
train
public function register($name, $handler) { if (is_callable($handler)) { $params = array_merge(array($this), $this->params); $this->container[$name] = call_user_func_array($handler, $params); } else { $this->container[$name] = $handler; } return $this; }
php
{ "resource": "" }
q13103
DependencyInjectionContainer.registerCollection
train
public function registerCollection(array $collection) { foreach ($collection as $name => $handler) { $this->register($name, $handler); } return $this; }
php
{ "resource": "" }
q13104
DependencyInjectionContainer.get
train
public function get($name) { if ($this->exists($name)) { return $this->container[$name]; } else { throw new RuntimeException(sprintf('Attempted to retrieve non-existing dependency "%s"', $name)); } }
php
{ "resource": "" }
q13105
Thumb.makeDestination
train
private function makeDestination($id, $width, $height) { return sprintf('%s/%s/%sx%s', $this->dir, $id, $width, $height); }
php
{ "resource": "" }
q13106
Thumb.upload
train
public function upload($id, array $files) { foreach ($files as $file) { if ($file instanceof FileEntity) { foreach ($this->dimensions as $index => $dimension) { $width = (int) $dimension[0]; $height = (int) $dimension[1]; $destination = $this->makeDestination($id, $width, $height); // Ensure that destination actually exists if (!is_dir($destination)) { mkdir($destination, 0777, true); } $to = sprintf('%s/%s', $destination, $file->getUniqueName()); $imageProcessor = new ImageProcessor($file->getTmpName()); $imageProcessor->thumb($width, $height); // This might fail sometimes $imageProcessor->save($to, $this->quality); } } } return true; }
php
{ "resource": "" }
q13107
Country.getCountryNames
train
protected function getCountryNames($language) { $event = new LoadLanguageFileEvent('countries', $language, true); $this->eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event); return $GLOBALS['TL_LANG']['CNT']; }
php
{ "resource": "" }
q13108
Country.restoreLanguage
train
protected function restoreLanguage() { // Switch back to the original FE language to not disturb the frontend. if ($this->getMetaModel()->getActiveLanguage() != $GLOBALS['TL_LANGUAGE']) { $event = new LoadLanguageFileEvent('countries', null, true); $this->eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event); } }
php
{ "resource": "" }
q13109
Country.getCountries
train
protected function getCountries() { $loadedLanguage = $this->getMetaModel()->getActiveLanguage(); if (isset($this->countryCache[$loadedLanguage])) { return $this->countryCache[$loadedLanguage]; } $languageValues = $this->getCountryNames($loadedLanguage); $countries = $this->getRealCountries(); $keys = \array_keys($countries); $aux = []; $real = []; // Fetch real language values. foreach ($keys as $key) { if (isset($languageValues[$key])) { $aux[$key] = Utf8::toAscii($languageValues[$key]); $real[$key] = $languageValues[$key]; } } // Add needed fallback values. $keys = \array_diff($keys, \array_keys($aux)); if ($keys) { $loadedLanguage = $this->getMetaModel()->getFallbackLanguage(); $fallbackValues = $this->getCountryNames($loadedLanguage); foreach ($keys as $key) { if (isset($fallbackValues[$key])) { $aux[$key] = Utf8::toAscii($fallbackValues[$key]); $real[$key] = $fallbackValues[$key]; } } } $keys = \array_diff($keys, \array_keys($aux)); if ($keys) { foreach ($keys as $key) { $aux[$key] = $countries[$key]; $real[$key] = $countries[$key]; } } \asort($aux); $return = []; foreach (\array_keys($aux) as $key) { $return[$key] = $real[$key]; } $this->restoreLanguage(); $this->countryCache[$loadedLanguage] = $return; return $return; }
php
{ "resource": "" }
q13110
Country.getCountryLabel
train
public function getCountryLabel($strCountry) { $countries = $this->getCountries(); return isset($countries[$strCountry]) ? $countries[$strCountry] : null; }
php
{ "resource": "" }
q13111
Kernel.getComponents
train
private function getComponents() { // Order of components being registered is extremely important! return array( new Component\Request(), new Component\Paginator(), new Component\Db(), new Component\MapperFactory(), new Component\SessionBag(), new Component\AuthManager(), new Component\AuthAttemptLimit(), new Component\ParamBag(), new Component\AppConfig(), new Component\Config(), new Component\ModuleManager(), new Component\Translator(), new Component\Response(), new Component\FlashBag(), new Component\FormAttribute(), new Component\ValidatorFactory(), new Component\WidgetFactory(), new Component\UrlBuilder(), new Component\View(), new Component\Profiler(), new Component\Cache(), new Component\CsrfProtector(), new Component\Captcha(), // Dispatcher always must be very last component to be registered new Component\Dispatcher() ); }
php
{ "resource": "" }
q13112
Kernel.getServices
train
private function getServices() { $container = new DependencyInjectionContainer(); $components = $this->getComponents(); foreach ($components as $component) { // Sometimes on failures due to invalid configuration, components might return void if (is_object($component)) { $container->register($component->getName(), $component->getInstance($container, $this->config, $this->input)); } } return $container->getAll(); }
php
{ "resource": "" }
q13113
Kernel.bootstrap
train
public function bootstrap() { $this->tweak(); $serviceLocator = new ServiceLocator(); $serviceLocator->registerArray($this->getServices()); // Constant that tells that the framework is launched define('KRYSTAL', true); return $serviceLocator; }
php
{ "resource": "" }
q13114
Kernel.run
train
public function run() { // Firstly make sure, default is set if (!isset($this->config['components']['router']['default'])) { throw new RuntimeException('You should provide default controller for router'); } $sl = $this->bootstrap(); // Grab required services to run the application $request = $sl->get('request'); $dispatcher = $sl->get('dispatcher'); $response = $sl->get('response'); // Do we need to perform SSL redirect? if (isset($this->config['components']['router']['ssl']) && $this->config['components']['router']['ssl'] == true) { $request->sslRedirect(); } // We will start from route matching firstly $router = new Router(); // Returns RouteMatch on success, false on failure $route = $router->match($request->getURI(), $dispatcher->getURIMap()); $notFound = false; // $route is false on failure, otherwise RouteMatch is returned when found if ($route !== false) { $content = null; try { $content = $dispatcher->render($route->getMatchedURITemplate(), $route->getVariables()); } catch(\DomainException $e){ $notFound = true; } if ($content === false) { // Returning false from an action, will trigger 404 $notFound = true; } } else { $notFound = true; } // Handle now found now if ($notFound === true) { $default = $this->config['components']['router']['default']; if (is_string($default)) { $notation = new RouteNotation(); $args = $notation->toArgs($default); // Extract controller and action from $args $controller = $args[0]; $action = $args[1]; // Finally call it $content = $dispatcher->call($controller, $action); } else if (is_callable($default)) { $content = call_user_func($default, $sl); } else { throw new LogicException(sprintf( 'Default route must be either callable or a string that represents default controller, not %s', gettype($default) )); } $response->setStatusCode(404); } $response->send($content); }
php
{ "resource": "" }
q13115
Kernel.tweak
train
private function tweak() { // Ignore recoverable GD errors ini_set('gd.jpeg_ignore_warning', 1); // Handle error reporting if (isset($this->config['production']) && false === $this->config['production']) { // Custom exception handler should be registered on NON-AJAX requests only $server = $this->input->getServer(); if (!isset($server['HTTP_X_REQUESTED_WITH'])) { // Custom exception handler $excepetionHandler = new ExceptionHandler(); $excepetionHandler->register(); } error_reporting(self::ERR_LEVEL_MAX); ini_set('display_errors', 1); } else { error_reporting(self::ERR_LEVEL_NONE); } // In most cases, we require UTF-8 as a default charset if (!isset($this->config['charset'])) { ini_set('default_charset', self::DEFAULT_CHARSET); mb_internal_encoding(self::DEFAULT_CHARSET); } else { ini_set('default_charset', $this->config['charset']); mb_internal_encoding($this->config['charset']); } mb_substitute_character('none'); // Locale if (isset($this->config['locale'])) { setlocale(LC_ALL, $this->config['locale']); } // Timezone if (isset($this->config['timezone'])) { date_default_timezone_set($this->config['timezone']); } // And lastly, magic quotes filter $mg = new MagicQuotesFilter(); if ($mg->enabled()) { $mg->deactivate(); $this->input->setQuery($mg->filter($this->input->getQuery())); $this->input->setPost($mg->filter($this->input->getPost())); $this->input->setCookie($mg->filter($this->input->getCookie())); // Third party libraries might use $_REQUEST as well, so we'd better filter this one too $this->input->setRequest($mg->filter($this->input->getRequest())); } }
php
{ "resource": "" }
q13116
AbstractRequest.sendData
train
public function sendData($data) { if ($this->sendData === null) { $this->sendData = $this->getData(); } $data = $this->createSOAPEnvelope( $this->prepareParameters( $this->sendData ) ); $headers = array( 'Content-Type' => 'text/xml; charset=utf-8', 'SOAPAction' => $this->method ); $httpResponse = $this->httpClient->post( $this->getEndpoint(), $headers, $data )->send(); return $this->response = new Response($this, $httpResponse->getBody()); }
php
{ "resource": "" }
q13117
AzureSDKCommandBuilder.buildPackageCmd
train
public function buildPackageCmd(ServiceDefinition $serviceDefinition, $outputDir, $isDevFabric) { $args = array( $this->getAzureSdkBinaryFolder() . 'cspack.exe', $serviceDefinition->getPath() ); foreach ($serviceDefinition->getWebRoleNames() as $roleName) { $args[] = $this->getRoleArgument($roleName, $serviceDefinition); } foreach ($serviceDefinition->getWorkerRoleNames() as $roleName) { $args[] = $this->getRoleArgument($roleName, $serviceDefinition); } $args[] = sprintf('/out:%s', $outputDir); if ($isDevFabric) { $args[] = '/copyOnly'; } return $args; }
php
{ "resource": "" }
q13118
DateFormatMatch.isValidFormat
train
private function isValidFormat($date) { foreach ($this->formats as $format) { if (date($format, strtotime($date)) == $date) { return true; } } return false; }
php
{ "resource": "" }
q13119
Put.getCommand
train
public function getCommand() { return sprintf( "put %d %d %d %d", $this->_priority, $this->_delay, $this->_ttr, strlen($this->_message) ); }
php
{ "resource": "" }
q13120
Parser.parse
train
public function parse() { $results = []; foreach ($this->output as $account) { if ($account = $this->parseAccount($account)) { $results[] = $account; } } return $results; }
php
{ "resource": "" }
q13121
Parser.parseAccount
train
protected function parseAccount($account) { // Separate the account by it's account and permission list. $parts = explode(':', trim($account)); // We should receive exactly two parts of a permission // listing, otherwise we'll return null. if (count($parts) === 2) { $account = new Account($parts[0]); $acl = $this->parseAccessControlList($parts[1]); $account->setPermissions($acl); return $account; } return null; }
php
{ "resource": "" }
q13122
Parser.parseAccessControlList
train
protected function parseAccessControlList($list) { $permissions = []; // Matches between two parenthesis. preg_match_all('/\((.*?)\)/', $list, $matches); // Make sure we have resulting matches. if (is_array($matches) && count($matches) > 0) { // Matches inside the first key will have parenthesis // already removed, so we need to verify it exists. if (array_key_exists(1, $matches) && is_array($matches[1])) { // We'll go through each match and see if the ACE // exists inside the permissions definition list. foreach ($matches[1] as $definition) { // We'll merge the permissions list so we have a flat array // of all of the rights for the current account. $permissions = array_merge($permissions, $this->parseDefinitionRights($definition)); } } } return $permissions; }
php
{ "resource": "" }
q13123
Parser.parseDefinitionRights
train
protected function parseDefinitionRights($definition) { $permissions = []; // We need to explode the definition in case it contains // multiple rights, for example: (GR,GE). $rights = explode(',', $definition); foreach ($rights as $right) { // We'll make sure the right exists inside the definitions // array before we try to instantiate it. if (array_key_exists($right, static::$definitions)) { $permissions[] = new static::$definitions[$right]; } } return $permissions; }
php
{ "resource": "" }
q13124
GridWidgetBoxService.countNews
train
public function countNews() { $news = 0; foreach ($this->getDefinitionsBlockGrid() as $grid) { $news += $grid->countNews(); } return $news; }
php
{ "resource": "" }
q13125
PhpClassDiscovery.addSearchLocation
train
public function addSearchLocation($location) { if (!file_exists($location)) { throw new \InvalidArgumentException( sprintf("The location path %s is not valid.", $location) ); } $this->searchLocations[] = $location; return $this; }
php
{ "resource": "" }
q13126
PhpClassDiscovery.discover
train
public function discover() { $classes = []; foreach ($this->doFileSearch() as $file) { $classinfo = $this->parse($file); $classname = $classinfo['class']; $classpath = $file->getRealPath() ?: "$classname.php"; if (!empty($this->searchMatches)) { foreach ($this->searchMatches as $type => $value) { if (!isset($classinfo[$type])) { continue; } $instances = !is_array($classinfo[$type]) ? [$classinfo[$type]] : $classinfo[$type]; $matches = array_intersect($value, $instances); if (empty($matches)) { continue; } $classes[$classpath] = $classname; } } else { $classes[$classpath] = $classname; } } $this->requireClasses($classes); return $classes; }
php
{ "resource": "" }
q13127
PhpClassDiscovery.doFileSearch
train
protected function doFileSearch() { if (empty($this->searchLocations)) { throw new \RuntimeException( 'No search locations have been defined.' ); } return (new Finder()) ->name($this->searchPattern) ->in($this->searchLocations) ->depth($this->searchDepth) ->files(); }
php
{ "resource": "" }
q13128
PhpClassDiscovery.requireClasses
train
protected function requireClasses(array $classes) { if ($this->loadClasses) { foreach ($classes as $classpath => $classname) { if (class_exists($classname)) { continue; } require_once "$classpath"; } } }
php
{ "resource": "" }
q13129
PhpClassDiscovery.parse
train
protected function parse(\SplFileInfo $file) { if ($file->getExtension() !== 'php') { throw new \InvalidArgumentException( 'Invalid file type.' ); } $info = []; $tokens = token_get_all($file->getContents()); for ($i = 0; $i < count($tokens); ++$i) { $token = is_array($tokens[$i]) ? $tokens[$i][0] : $tokens[$i]; switch ($token) { case T_NAMESPACE: $info[$tokens[$i][1]] = $this->getTokenValue( $tokens, [';'], $i ); continue; case T_USE: $info[$tokens[$i][1]][] = $this->getTokenValue( $tokens, [';', '{', T_AS], $i ); continue; case T_CLASS: $classname = $this->getTokenValue( $tokens, [T_EXTENDS, T_IMPLEMENTS, '{'], $i ); // Resolve the class fully qualified namespace. $info[$tokens[$i][1]] = $this->resolveNamespace( $info, $classname ); continue; case T_EXTENDS: $classname = $this->getTokenValue( $tokens, [T_IMPLEMENTS, '{'], $i ); // Resolve the extends class fully qualified namespace. $info[$tokens[$i][1]] = $this->resolveNamespace( $info, $classname ); continue; case T_IMPLEMENTS: $interface = $this->getTokenValue( $tokens, ['{'], $i ); // Resolve the interface fully qualified namespace. $info[$tokens[$i][1]][] = $this->resolveNamespace( $info, $interface ); continue; } } return $info; }
php
{ "resource": "" }
q13130
PhpClassDiscovery.resolveNamespace
train
protected function resolveNamespace(array $token_info, $classname) { // Resolve the namespace based on the use directive. if (isset($token_info['use']) && !empty($token_info['use']) && strpos($classname, DIRECTORY_SEPARATOR) === false) { foreach ($token_info['use'] as $use) { if (strpos($use, "\\{$classname}") === false) { continue; } return $use; } } // Prefix the classname with the class namespace if defined. if (isset($token_info['namespace'])) { $classname = $token_info['namespace'] . "\\$classname"; } return $classname; }
php
{ "resource": "" }
q13131
PhpClassDiscovery.getTokenValue
train
protected function getTokenValue(array $tokens, array $endings, $iteration, $skip_whitespace = true) { $value = null; $count = count($tokens); for ($i = $iteration + 1; $i < $count; ++$i) { $token = is_array($tokens[$i]) ? $tokens[$i][0] : trim($tokens[$i]); if ($token === T_WHITESPACE && $skip_whitespace) { continue; } if (in_array($token, $endings)) { break; } $value .= isset($tokens[$i][1]) ? $tokens[$i][1] : $token; } return $value; }
php
{ "resource": "" }
q13132
Replacements.getReplacementsFor
train
public function getReplacementsFor($address) { $organism = $this->manager->getRepository('LibrinfoCRMBundle:Organism')->findOneBy(array('email' => $address)); if ($organism) { if ($organism->isIndividual()) { return array( '{prenom}' => $organism->getFirstName(), '{nom}' => $organism->getLastName(), '{titre}' => $organism->getTitle(), ); } else { return array( '{nom}' => $organism->getName(), ); } } }
php
{ "resource": "" }
q13133
ArrayConfig.remove
train
public function remove($module, $name) { $index = 0; if ($this->has($module, $name, $index)) { unset($this->data[$index]); } }
php
{ "resource": "" }
q13134
ArrayConfig.removeAllByModule
train
public function removeAllByModule($module) { foreach ($this->getIndexesByModule($module) as $index) { if (isset($this->data[$index])) { unset($this->data[$index]); } } }
php
{ "resource": "" }
q13135
ArrayConfig.getIndexesByModule
train
private function getIndexesByModule($module) { // Indexes to be removed $indexes = array(); foreach ($this->data as $index => $row) { if (isset($row[ConstProviderInterface::CONFIG_PARAM_MODULE]) && $row[ConstProviderInterface::CONFIG_PARAM_MODULE] == $module) { array_push($indexes, $index); } } return $indexes; }
php
{ "resource": "" }
q13136
ArrayConfig.getAllByModule
train
public function getAllByModule($module) { if (!$this->hasModule($module)) { return false; } else { $result = array(); foreach ($this->data as $index => $row) { if (isset($row[ConstProviderInterface::CONFIG_PARAM_MODULE]) && $row[ConstProviderInterface::CONFIG_PARAM_MODULE] == $module) { $name = $row[ConstProviderInterface::CONFIG_PARAM_NAME]; $value = $row[ConstProviderInterface::CONFIG_PARAM_VALUE]; $result[$name] = $value; } } return $result; } }
php
{ "resource": "" }
q13137
ArrayConfig.get
train
public function get($module, $name, $default) { $index = 0; if ($this->has($module, $name, $index)) { return $this->data[$index][ConstProviderInterface::CONFIG_PARAM_VALUE]; } else { return $default; } }
php
{ "resource": "" }
q13138
ArrayConfig.add
train
public function add($module, $name, $value) { array_push($this->data, array( ConstProviderInterface::CONFIG_PARAM_MODULE => $module, ConstProviderInterface::CONFIG_PARAM_NAME => $name, ConstProviderInterface::CONFIG_PARAM_VALUE => $value )); }
php
{ "resource": "" }
q13139
ArrayConfig.update
train
public function update($module, $name, $value) { foreach ($this->data as $index => $row) { if ($row[ConstProviderInterface::CONFIG_PARAM_MODULE] == $module && $row[ConstProviderInterface::CONFIG_PARAM_NAME] == $name) { // Alter found index's value $this->data[$index][ConstProviderInterface::CONFIG_PARAM_VALUE] = $value; } } }
php
{ "resource": "" }
q13140
ArrayConfig.hasModule
train
public function hasModule($module) { foreach ($this->data as $index => $row) { if ($row[ConstProviderInterface::CONFIG_PARAM_MODULE] == $module) { return true; } } return false; }
php
{ "resource": "" }
q13141
ArrayConfig.has
train
public function has($module, $name, &$position = false) { foreach ($this->data as $index => $row) { if ($row[ConstProviderInterface::CONFIG_PARAM_MODULE] == $module && $row[ConstProviderInterface::CONFIG_PARAM_NAME] == $name) { if ($position !== false) { $position = $index; } return true; } } return false; }
php
{ "resource": "" }
q13142
ReplaceConverter.getRoot
train
private function getRoot(NumberBase $source, NumberBase $target) { if ($source->hasStringConflict() || $target->hasStringConflict()) { throw new InvalidNumberBaseException('Number bases do not support string presentation'); } $root = $source->findCommonRadixRoot($target); if ($root === false) { throw new InvalidNumberBaseException('No common root exists between number bases'); } return $root; }
php
{ "resource": "" }
q13143
ReplaceConverter.buildConversionTable
train
private function buildConversionTable() { if ($this->source->getRadix() > $this->target->getRadix()) { return $this->createTable($this->source->getDigitList(), $this->target->getDigitList()); } return array_flip($this->createTable($this->target->getDigitList(), $this->source->getDigitList())); }
php
{ "resource": "" }
q13144
ReplaceConverter.createTable
train
private function createTable($source, $target) { $last = count($target) - 1; $size = (int) log(count($source), count($target)); $number = array_fill(0, $size, $target[0]); $next = array_fill(0, $size, 0); $limit = count($source); $table = [$source[0] => implode('', $number)]; for ($i = 1; $i < $limit; $i++) { for ($j = $size - 1; $next[$j] === $last; $j--) { $number[$j] = $target[0]; $next[$j] = 0; } $number[$j] = $target[++$next[$j]]; $table[$source[$i]] = implode('', $number); } return $table; }
php
{ "resource": "" }
q13145
ReplaceConverter.convert
train
private function convert(array $number, $fractions = false) { if (!isset($this->conversionTable)) { return $this->targetConverter->replace( $this->sourceConverter->replace($number, $fractions), $fractions ); } return $this->replace($number, $fractions); }
php
{ "resource": "" }
q13146
ReplaceConverter.replace
train
private function replace(array $number, $fractions = false) { return $this->zeroTrim($this->target->splitString(strtr(implode('', $this->zeroPad( $this->source->canonizeDigits($number), $fractions )), $this->conversionTable)), $fractions); }
php
{ "resource": "" }
q13147
ReplaceConverter.zeroPad
train
private function zeroPad(array $number, $right) { $log = (int) log($this->target->getRadix(), $this->source->getRadix()); if ($log > 1 && count($number) % $log) { $pad = count($number) + ($log - count($number) % $log); $number = array_pad($number, $right ? $pad : -$pad, $this->source->getDigit(0)); } return $number; }
php
{ "resource": "" }
q13148
ReplaceConverter.zeroTrim
train
private function zeroTrim(array $number, $right) { $zero = $this->target->getDigit(0); while (($right ? end($number) : reset($number)) === $zero) { unset($number[key($number)]); } return empty($number) ? [$zero] : array_values($number); }
php
{ "resource": "" }
q13149
ModuleManager.initialize
train
public function initialize() { $modules = $this->loader->getModules(); if (empty($modules)) { throw new RuntimeException('No modules found. Initialization halted'); } else { $this->loadAll($modules); $this->modules = $modules; // Validate on demand $this->validateCoreModuleNames(); } }
php
{ "resource": "" }
q13150
ModuleManager.getCoreBag
train
private function getCoreBag() { static $coreBag = null; if (is_null($coreBag)) { $coreBag = new CoreBag($this->getLoadedModuleNames(), $this->coreModules); } return $coreBag; }
php
{ "resource": "" }
q13151
ModuleManager.validateCoreModuleNames
train
private function validateCoreModuleNames() { if (!empty($this->coreModules)) { $coreBag = $this->getCoreBag(); if (!$coreBag->hasAllCoreModules()) { throw new LogicException(sprintf( 'The framework can not start without defined core modules: %s', implode(', ', $coreBag->getMissingCoreModules()) )); } } }
php
{ "resource": "" }
q13152
ModuleManager.getModule
train
public function getModule($name) { if ($this->isLoaded($name)) { return $this->loaded[$name]; } else { return $this->loadModuleByName($name); } }
php
{ "resource": "" }
q13153
ModuleManager.getUnloadedModules
train
public function getUnloadedModules(array $modules) { $unloaded = array(); foreach ($modules as $module) { if (!$this->isLoaded($module)) { array_push($unloaded, $module); } } return $unloaded; }
php
{ "resource": "" }
q13154
ModuleManager.prepareRoutes
train
private function prepareRoutes($module, array $routes) { $result = array(); foreach ($routes as $uriTemplate => $options) { // Controller is the special case if (isset($options['controller'])) { // Override with module-compliant $options['controller'] = sprintf('%s:%s', $this->grabModuleName($module), $options['controller']); } $result[$uriTemplate] = $options; } return $result; }
php
{ "resource": "" }
q13155
ModuleManager.loadModuleByName
train
private function loadModuleByName($name) { // First of all, make sure a valid module name is being processed if (!$this->nameValid($name)) { throw new LogicException(sprintf( 'Invalid module name "%s" is being processed. Module name must start from a capital letter and contain only alphabetic characters', $name )); } // Prepare PSR-0 compliant name $moduleNamespace = sprintf('%s\%s', $name, self::MODULE_CONFIG_FILE); // Ensure a module exists if (!class_exists($moduleNamespace)) { return false; } $pathProvider = new PathProvider($this->appConfig->getModulesDir(), $name); $sl = new ServiceLocator(); $sl->registerArray($this->services); // Build module instance $module = new $moduleNamespace($this, $sl, $this->appConfig, $pathProvider, $name); // Routes must be global, so we'd extract them if (method_exists($module, 'getRoutes')) { $this->appendRoutes($this->prepareRoutes($moduleNamespace, $module->getRoutes())); } $this->loaded[$name] = $module; return $module; }
php
{ "resource": "" }
q13156
ModuleManager.removeFromCacheDir
train
public function removeFromCacheDir($module) { // Create a path $path = $this->appConfig->getModuleCacheDir($module); return $this->performRemoval($path); }
php
{ "resource": "" }
q13157
ModuleManager.removeFromUploadsDir
train
public function removeFromUploadsDir($module) { // Create a path $path = $this->appConfig->getModuleUploadsDir($module); return $this->performRemoval($path); }
php
{ "resource": "" }
q13158
ModuleManager.removeFromFileSysem
train
public function removeFromFileSysem($module) { if ($this->isCoreModule($module)) { throw new LogicException(sprintf( 'Trying to remove core module "%s". This is not allowed by design', $module )); } $path = sprintf('%s/%s', $this->appConfig->getModulesDir(), $module); return $this->performRemoval($path); }
php
{ "resource": "" }
q13159
ModuleManager.loadAllTranslations
train
public function loadAllTranslations($language) { foreach ($this->loaded as $module) { $this->loadModuleTranslation($module, $language); } }
php
{ "resource": "" }
q13160
ModuleManager.loadModuleTranslation
train
private function loadModuleTranslation(AbstractModule $module, $language) { // Translations are optional if (method_exists($module, 'getTranslations')) { $translations = $module->getTranslations($language); // Only array must be provided, otherwise ignore another type if (is_array($translations)) { // If that's an array, then append translations foreach ($translations as $string => $translation) { $this->translations[$string] = $translation; } // And indicate success return true; } } // Failure by default return false; }
php
{ "resource": "" }
q13161
BuildNumber.createInDirectory
train
static public function createInDirectory($dir) { if (! is_dir($dir) || ! is_writable($dir)) { throw new \InvalidArgumentException("Directory to load build number from is not writable or does not exist: " . $dir); } $buildFile = $dir . DIRECTORY_SEPARATOR . "azure_build_number.yml"; if (! file_exists($buildFile)) { file_put_contents($buildFile, "parameters:\n azure_build: 0"); } return new self($buildFile); }
php
{ "resource": "" }
q13162
UnitType.findUnit
train
protected function findUnit($unitName, $validUnits = null) { $units = $this->getUnits(); $nunits = count($units); for ($i = 0; $i < $nunits; $i++) { if (($validUnits != null) && (!array_search($units[$i]['name'], $validUnits) )){ continue; } if (($units[$i]['name'] == $unitName) || ($this->aliasMatch($units[$i], $unitName) )){ return $i; } } throw new \InvalidArgumentException(sprintf('Invalid unit "%s" for type "%s"',$unitName, $this->getType())); }
php
{ "resource": "" }
q13163
FilterInvoker.invoke
train
public function invoke(FilterableServiceInterface $service, $perPageCount, array $parameters = array()) { $page = $this->getPageNumber(); $sort = $this->getSortingColumn(); $desc = $this->getDesc(); $records = $service->filter($this->getData(), $page, $perPageCount, $sort, $desc, $parameters); // Tweak pagination if available if (method_exists($service, 'getPaginator')) { $paginator = $service->getPaginator(); if ($paginator instanceof PaginatorInterface) { $paginator->setUrl($this->getPaginationUrl($page, $sort, $desc)); } } return $records; }
php
{ "resource": "" }
q13164
FilterInvoker.getPaginationUrl
train
private function getPaginationUrl($page, $sort, $desc) { $placeholder = '(:var)'; $data = array( self::FILTER_PARAM_PAGE => $placeholder, self::FILTER_PARAM_DESC => $desc, self::FILTER_PARAM_SORT => $sort ); return self::createUrl(array_merge($this->input, $data), $this->route); }
php
{ "resource": "" }
q13165
FilterInvoker.getData
train
private function getData() { if (isset($this->input[self::FILTER_PARAM_NS])) { $data = $this->input[self::FILTER_PARAM_NS]; } else { $data = array(); } return new InputDecorator($data); }
php
{ "resource": "" }
q13166
ProjectXDiscovery.performSearch
train
protected function performSearch() { $filename = self::CONFIG_FILENAME . '.yml'; $directories = array_filter(explode('/', getcwd())); $count = count($directories); for ($offset = 0; $offset < $count; ++$offset) { $next_path = '/' . implode('/', array_slice($directories, 0, $count - $offset)); if (file_exists("{$next_path}/{$filename}")) { $this->projectXPath = "{$next_path}/{$filename}"; break; } } }
php
{ "resource": "" }
q13167
Engine.decide
train
public function decide(GameState $state): GameState { if (!$state->getNextPlayer()->equals($this->objectivePlayer)) { throw new BadMethodCallException('It is not this players turn'); } if (empty($state->getPossibleMoves())) { throw new RuntimeException('There are no possible moves'); } $rootNode = new DecisionNode( $this->objectivePlayer, $state, $this->maxDepth, NodeType::MAX(), AlphaBeta::initial() ); $moveWithEvaluation = $rootNode->traverseGameTree(); $this->analytics = $moveWithEvaluation->analytics; if ($moveWithEvaluation->move === null) { throw new LogicException('Could not find move even though there are moves. Is the maxdepth parameter correct?'); } return $moveWithEvaluation->move; }
php
{ "resource": "" }
q13168
CurlHttplCrawler.request
train
public function request($method, $url, array $data = array(), array $extra = array()) { switch (strtoupper($method)) { case 'POST': return $this->post($url, $data, $extra); case 'GET': return $this->get($url, $data, $extra); case 'PATCH': return $this->patch($url, $data, $extra); case 'HEAD': return $this->head($url, $data, $extra); case 'PUT': return $this->put($url, $data, $extra); case 'DELETE': return $this->delete($url, $data, $extra); default: throw new UnexpectedValueException(sprintf('Unsupported or unknown HTTP method provided "%s"', $method)); } }
php
{ "resource": "" }
q13169
CurlHttplCrawler.get
train
public function get($url, array $data = array(), array $extra = array()) { if (!empty($data)) { $url = $url . '?' . http_build_query($data); } $curl = new Curl(array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false ), $extra); return $curl->exec(); }
php
{ "resource": "" }
q13170
CurlHttplCrawler.post
train
public function post($url, $data = array(), array $extra = array()) { $curl = new Curl(array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_POST => count($data), CURLOPT_POSTFIELDS => http_build_query($data) ), $extra); return $curl->exec(); }
php
{ "resource": "" }
q13171
CurlHttplCrawler.delete
train
public function delete($url, array $data = array(), array $extra = array()) { $curl = new Curl(array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_POSTFIELDS => http_build_query($data) ), $extra); return $curl->exec(); }
php
{ "resource": "" }
q13172
CurlHttplCrawler.head
train
public function head($url, array $data = array(), array $extra = array()) { if (!empty($data)) { $url = $url . '?' . http_build_query($data); } $curl = new Curl(array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_NOBODY => true, CURLOPT_POSTFIELDS => http_build_query($data) ), $extra); return $curl->exec(); }
php
{ "resource": "" }
q13173
Utils.loadJsonFromFile
train
public static function loadJsonFromFile($filePath) { if (!file_exists($filePath)) { throw new \RuntimeException("File '{$filePath}' doesn't exist"); } $content = json_decode(file_get_contents($filePath)); if (json_last_error() !== JSON_ERROR_NONE) { throw new JsonDecodeException(sprintf( 'Cannot decode JSON from file "%s" (error: %s)', $filePath, static::lastJsonErrorMessage() )); } return $content; }
php
{ "resource": "" }
q13174
CryptoHelper.getUniqueToken
train
public static function getUniqueToken(int $length = 40): string { $token = ''; $codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz'; $codeAlphabet .= '0123456789'; $max = strlen($codeAlphabet); // edited for ($i = 0; $i < $length; $i++) { $token .= $codeAlphabet[self::getSecureRandomInt(0, $max - 1)]; } return $token; }
php
{ "resource": "" }
q13175
StringDecryptor.decode
train
public function decode() { // Fix plus to space conversion issue $this->data = str_replace(' ', '+', $this->data); // Do decoding $this->data = base64_decode($this->data); return $this; }
php
{ "resource": "" }
q13176
StringDecryptor.simplexor
train
private function simplexor() { $KeyList = array(); $output = ""; // Convert $Key into array of ASCII values for ($i = 0; $i < strlen($this->hash); $i++) { $KeyList[$i] = ord(substr($this->hash, $i, 1)); } // Step through string a character at a time for ($i = 0; $i < strlen($this->data); $i++) { $output.= chr(ord(substr($this->data, $i, 1)) ^ ($KeyList[$i % strlen($this->hash)])); } // Return the result return $output; }
php
{ "resource": "" }
q13177
Page_Templates.get
train
public function get() { foreach ( $this->page_template_files as $name => $page_template_path ) { if ( isset( $this->wrappers[ $name ] ) ) { continue; } if ( ! isset( $this->wrapper_files[ $name ] ) ) { continue; } $label = $this->_get_template_label( $page_template_path ); if ( ! $label ) { continue; } // @codingStandardsIgnoreStart $this->wrappers[ $name ] = translate( $label, wp_get_theme( get_template() )->get( 'TextDomain' ) ); // @codingStandardsIgnoreEnd } return $this->wrappers; }
php
{ "resource": "" }
q13178
Page_Templates._get_wrapper_files
train
protected function _get_wrapper_files() { $wrapper_files = []; foreach ( WP_View_Controller\Helper\config( 'layout' ) as $wrapper_dir ) { foreach ( glob( get_theme_file_path( $wrapper_dir . '/*' ) ) as $wrapper_path ) { $name = basename( $wrapper_path, '.php' ); if ( 'blank' === $name || 'blank-fluid' === $name ) { continue; } if ( isset( $wrapper_files[ $name ] ) ) { continue; } $wrapper_files[ $name ] = $wrapper_path; } } return $wrapper_files; }
php
{ "resource": "" }
q13179
Page_Templates._get_page_template_files
train
protected function _get_page_template_files() { $page_template_files = []; foreach ( WP_View_Controller\Helper\config( 'page-templates' ) as $page_template_dir ) { foreach ( glob( get_theme_file_path( $page_template_dir . '/*' ) ) as $page_template_path ) { $name = basename( $page_template_path, '.php' ); if ( 'blank' === $name || 'blank-fluid' === $name ) { continue; } if ( isset( $page_template_files[ $name ] ) ) { continue; } $page_template_files[ $name ] = $page_template_path; } } return $page_template_files; }
php
{ "resource": "" }
q13180
ImageFile.getImageInfo
train
final protected function getImageInfo($file) { $image = getimagesize($file); if ($image !== false) { return array( 'width' => $image[0], 'height' => $image[1], 'type' => $image[2], 'mime' => $image['mime'], 'bits' => isset($image['bits']) ? $image['bits'] : null ); } else { return false; } }
php
{ "resource": "" }
q13181
ImageFile.createImageFromFile
train
final protected function createImageFromFile($file, $type) { switch ($type) { case \IMAGETYPE_GIF: return imagecreatefromgif($file); case \IMAGETYPE_JPEG: return imagecreatefromjpeg($file); case \IMAGETYPE_PNG: return imagecreatefrompng($file); default: throw new LogicException(sprintf('Can not create image from "%s"', $file)); } }
php
{ "resource": "" }
q13182
ImageFile.load
train
final protected function load($file) { $info = $this->getImageInfo($file); if ($info !== false) { $this->image = $this->createImageFromFile($file, $info['type']); $this->width = $info['width']; $this->height = $info['height']; $this->type = $info['type']; $this->mime = $info['mime']; // Calculate required memory space in bytes $this->requiredMemorySpace = $info['width'] * $info['height'] * $info['bits']; return true; } else { return false; } }
php
{ "resource": "" }
q13183
ImageFile.save
train
final public function save($path, $quality = 75, $type = null) { // If no optional type is provided, then use current one if ($type === null) { $type = $this->type; } switch ($type) { case \IMAGETYPE_GIF: $result = imagegif($this->image, $path); break; case \IMAGETYPE_JPEG: $result = imagejpeg($this->image, $path, $quality); break; case \IMAGETYPE_PNG: $result = imagepng($this->image, $path, 9); break; default: throw new LogicException(sprintf( 'Can not save image format (%s) to %s', $type, $path )); } $this->done(); // Returns boolean value indicating success or failure return $result; }
php
{ "resource": "" }
q13184
ImageFile.render
train
final public function render($quality = 75) { header("Content-type: ".image_type_to_mime_type($this->type)); switch ($this->type) { case \IMAGETYPE_GIF: imagegif($this->image, null); break; case \IMAGETYPE_JPEG: imagejpeg($this->image, null, $quality); break; case \IMAGETYPE_PNG: imagepng($this->image, null, 9); break; default: throw new LogicException(sprintf('Can not create image from "%s"', $this->file)); } $this->done(); exit(1); }
php
{ "resource": "" }
q13185
GitHubTasks.githubAuth
train
public function githubAuth() { if ($this->hasAuth()) { $this->io()->warning( 'A personal GitHub access token has already been setup.' ); return; } $this->io()->note("A personal GitHub access token is required.\n\n" . 'If you need help setting up a access token follow the GitHub guide:' . ' https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/'); $user = $this->ask('GitHub username:'); $pass = $this->askHidden('GitHub token (hidden):'); $status = $this->gitHubUserAuth() ->setUser($user) ->setToken($pass) ->save(); if (!$status) { $this->io()->success( "You've successfully added your personal GitHub access token." ); } }
php
{ "resource": "" }
q13186
GitHubTasks.githubIssueStart
train
public function githubIssueStart() { $listings = $this ->getIssueListing(); $issue = $this->doAsk( new ChoiceQuestion('Select GitHub issue:', $listings) ); $user = $this->getUser(); $number = array_search($issue, $listings); $this ->taskGitHubIssueAssignees($this->getToken()) ->setAccount($this->getAccount()) ->setRepository($this->getRepository()) ->number($number) ->addAssignee($user) ->run(); $this->say( sprintf('GH-%d issue was assigned to %s on GitHub.', $number, $user) ); if ($this->ask('Create Git branch? (yes/no) [no] ')) { $branch = $this->normailizeBranchName("$number-$issue"); $command = $this->hasGitFlow() ? "flow feature start '$branch'" : "checkout -b '$branch'"; $this->taskGitStack() ->stopOnFail() ->exec($command) ->run(); } }
php
{ "resource": "" }
q13187
GitHubTasks.githubLighthouseStatus
train
public function githubLighthouseStatus($sha, $opts = [ 'hostname' => null, 'protocol' => 'http', 'performance' => false, 'performance-score' => 50, 'accessibility' => false, 'accessibility-score' => 50, 'best-practices' => false, 'best-practices-score' => 50, 'progressive-web-app' => false, 'progressive-web-app-score' => 50, ]) { $host = ProjectX::getProjectConfig() ->getHost(); $protocol = $opts['protocol']; $hostname = isset($opts['hostname']) ? $opts['hostname'] : (isset($host['name']) ? $host['name'] : 'localhost'); $url = "$protocol://$hostname"; $path = new \SplFileInfo("/tmp/projectx-lighthouse-$sha.json"); $this->taskGoogleLighthouse() ->setUrl($url) ->chromeFlags([ '--headless', '--no-sandbox' ]) ->setOutput('json') ->setOutputPath($path) ->run(); if (!file_exists($path)) { throw new \RuntimeException( 'Unable to locate the Google lighthouse results.' ); } $selected = array_filter([ 'performance', 'accessibility', 'best-practices', 'progressive-web-app' ], function ($key) use ($opts) { return $opts[$key] === true; }); $report_data = $this->findLighthouseScoreReportData( $path, $selected ); $state = $this->determineLighthouseState($report_data, $opts); $this->taskGitHubRepoStatusesCreate($this->getToken()) ->setAccount($this->getAccount()) ->setRepository($this->getRepository()) ->setSha($sha) ->setParamState($state) ->setParamDescription('Google Lighthouse Tests') ->setParamContext('project-x/lighthouse') ->run(); }
php
{ "resource": "" }
q13188
GitHubTasks.determineLighthouseState
train
protected function determineLighthouseState(array $values, array $opts) { $state = 'success'; foreach ($values as $key => $info) { $required_score = isset($opts["$key-score"]) ? ($opts["$key-score"] <= 100 ? $opts["$key-score"] : 100) : 50; if ($info['score'] < $required_score && $info['score'] !== $required_score) { return 'failure'; } } return $state; }
php
{ "resource": "" }
q13189
GitHubTasks.findLighthouseScoreReportData
train
protected function findLighthouseScoreReportData(\SplFileInfo $path, array $selected) { $data = []; $json = json_decode(file_get_contents($path), true); foreach ($json['reportCategories'] as $report) { if (!isset($report['name']) || !isset($report['score'])) { continue; } $label = $report['name']; $key = Utility::cleanString( strtolower(strtr($label, ' ', '_')), '/[^a-zA-Z\_]/' ); if (!in_array($key, $selected)) { continue; } $data[$key] = [ 'name' => $label, 'score' => round($report['score']) ]; } return $data; }
php
{ "resource": "" }
q13190
GitHubTasks.outputGitHubIssues
train
protected function outputGitHubIssues() { $issues = $this ->taskGitHubIssueList( $this->getToken(), $this->getAccount(), $this->getRepository() ) ->run(); unset($issues['time']); $table = (new Table($this->output)) ->setHeaders(['Issue', 'Title', 'State', 'Assignee', 'Labels', 'Author']); $rows = []; foreach ($issues as $issue) { $labels = isset($issue['labels']) ? $this->formatLabelNames($issue['labels']) : null; $assignee = isset($issue['assignee']['login']) ? $issue['assignee']['login'] : 'none'; $rows[] = [ $issue['number'], $issue['title'], $issue['state'], $assignee, $labels, $issue['user']['login'], ]; } $table->setRows($rows); $table->render(); return $this; }
php
{ "resource": "" }
q13191
GitHubTasks.getIssueListing
train
protected function getIssueListing() { $issues = $this ->taskGitHubIssueList( $this->getToken(), $this->getAccount(), $this->getRepository() ) ->run(); $listing = []; foreach ($issues as $issue) { if (!isset($issue['title'])) { continue; } $number = $issue['number']; $listing[$number] = $issue['title']; } return $listing; }
php
{ "resource": "" }
q13192
GitHubTasks.formatLabelNames
train
protected function formatLabelNames(array $labels) { if (empty($labels)) { return; } $names = []; foreach ($labels as $label) { if (!isset($label['name'])) { continue; } $names[] = $label['name']; } return implode(', ', $names); }
php
{ "resource": "" }
q13193
PSR4.addNamespaces
train
public function addNamespaces(array $namespaces) { foreach ($namespaces as $prefix => $baseDir) { $this->addNamespace($prefix, $baseDir); } }
php
{ "resource": "" }
q13194
Env.init
train
public static function init($locale, $environment, $version) { $envFilename = Registry::get('applicationPath') . '/.env'; if (file_exists($envFilename)) { $env = Ini::parse($envFilename, true, $locale . '-' . $environment . '-' . $version, 'common', false); $env = self::mergeEnvVariables($env); } else { $env = new \StdClass(); } self::$data = Ini::bindArrayToObject($env); }
php
{ "resource": "" }
q13195
Stream.register
train
static public function register(BlobRestProxy $proxy, $name = 'azure') { stream_register_wrapper($name, __CLASS__); self::$clients[$name] = $proxy; }
php
{ "resource": "" }
q13196
Stream.getClient
train
static public function getClient($name) { if (! isset(self::$clients[$name])) { throw new BlobException("There is no client registered for stream type '" . $name . "://"); } return self::$clients[$name]; }
php
{ "resource": "" }
q13197
Stream.getStorageClient
train
private function getStorageClient($path = '') { if ($this->storageClient === null) { $url = explode(':', $path); if (! $url) { throw new BlobException('Could not parse path "' . $path . '".'); } $this->storageClient = self::getClient($url[0]); if (! $this->storageClient) { throw new BlobException('No storage client registered for stream type "' . $url[0] . '://".'); } } return $this->storageClient; }
php
{ "resource": "" }
q13198
Stream.stream_write
train
public function stream_write($data) { if (! $this->temporaryFileHandle) { return 0; } $len = strlen($data); fwrite($this->temporaryFileHandle, $data, $len); return $len; }
php
{ "resource": "" }
q13199
Stream.url_stat
train
public function url_stat($path, $flags) { $stat = array(); $stat['dev'] = 0; $stat['ino'] = 0; $stat['mode'] = 0; $stat['nlink'] = 0; $stat['uid'] = 0; $stat['gid'] = 0; $stat['rdev'] = 0; $stat['size'] = 0; $stat['atime'] = 0; $stat['mtime'] = 0; $stat['ctime'] = 0; $stat['blksize'] = 0; $stat['blocks'] = 0; $info = null; try { $metadata = $this->getStorageClient($path)->getBlobProperties($this->getContainerName($path), $this->getFileName($path)); $stat['size'] = $metadata->getProperties()->getContentLength(); // Set the modification time and last modified to the Last-Modified header. $lastmodified = $metadata->getProperties() ->getLastModified() ->format('U'); $stat['mtime'] = $lastmodified; $stat['ctime'] = $lastmodified; // Entry is a regular file. $stat['mode'] = 0100000; return array_values($stat) + $stat; } catch (Exception $ex) { // Unexisting file... return false; } }
php
{ "resource": "" }