_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 33 8k | 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 | php | {
"resource": ""
} |
q13101 | AbstractModule.getServices | train | final public function getServices()
{
if (is_null($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);
| php | {
"resource": ""
} |
q13103 | DependencyInjectionContainer.registerCollection | train | public function registerCollection(array $collection)
{
foreach ($collection as | php | {
"resource": ""
} |
q13104 | DependencyInjectionContainer.get | train | public function get($name)
{
if ($this->exists($name)) {
return $this->container[$name];
} else {
| php | {
"resource": ""
} |
q13105 | Thumb.makeDestination | train | private function makeDestination($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);
| php | {
"resource": ""
} |
q13107 | Country.getCountryNames | train | protected function getCountryNames($language)
{
$event = new LoadLanguageFileEvent('countries', $language, true);
| 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 | 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] | php | {
"resource": ""
} |
q13110 | Country.getCountryLabel | train | public function getCountryLabel($strCountry)
{
$countries = $this->getCountries();
| 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(),
| 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)) {
| php | {
"resource": ""
} |
q13113 | Kernel.bootstrap | train | public function bootstrap()
{
$this->tweak();
$serviceLocator = new ServiceLocator();
$serviceLocator->registerArray($this->getServices());
| 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)) {
| 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']);
}
| 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
);
| 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);
}
| php | {
"resource": ""
} |
q13118 | DateFormatMatch.isValidFormat | train | private function isValidFormat($date)
{
foreach ($this->formats as $format) {
if (date($format, strtotime($date)) == $date) {
| php | {
"resource": ""
} |
q13119 | Put.getCommand | train | public function getCommand()
{
return sprintf(
"put %d %d %d %d",
$this->_priority,
$this->_delay,
| php | {
"resource": ""
} |
q13120 | Parser.parse | train | public function parse()
{
$results = [];
foreach ($this->output as $account) {
| 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) {
| 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.
| 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);
| php | {
"resource": ""
} |
q13124 | GridWidgetBoxService.countNews | train | public function countNews() {
$news = 0;
foreach ($this->getDefinitionsBlockGrid() as | php | {
"resource": ""
} |
q13125 | PhpClassDiscovery.addSearchLocation | train | public function addSearchLocation($location)
{
if (!file_exists($location)) {
throw new \InvalidArgumentException(
| 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, | php | {
"resource": ""
} |
q13127 | PhpClassDiscovery.doFileSearch | train | protected function doFileSearch()
{
if (empty($this->searchLocations)) {
throw new \RuntimeException(
'No search locations have been defined.'
);
}
return (new | php | {
"resource": ""
} |
q13128 | PhpClassDiscovery.requireClasses | train | protected function requireClasses(array $classes)
{
if ($this->loadClasses) {
foreach ($classes as $classpath => $classname) {
if (class_exists($classname)) {
| 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:
| 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;
}
| 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) {
| 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(),
| php | {
"resource": ""
} |
q13133 | ArrayConfig.remove | train | public function remove($module, $name)
{
$index = 0;
if ($this->has($module, $name, $index)) | php | {
"resource": ""
} |
q13134 | ArrayConfig.removeAllByModule | train | public function removeAllByModule($module)
{
foreach ($this->getIndexesByModule($module) as $index) {
if (isset($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) {
| 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];
| php | {
"resource": ""
} |
q13137 | ArrayConfig.get | train | public function get($module, $name, $default)
{
$index = 0;
if ($this->has($module, $name, $index)) | php | {
"resource": ""
} |
q13138 | ArrayConfig.add | train | public function add($module, $name, $value)
{
array_push($this->data, array(
ConstProviderInterface::CONFIG_PARAM_MODULE => | 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) {
| php | {
"resource": ""
} |
q13140 | ArrayConfig.hasModule | train | public function hasModule($module)
{
foreach ($this->data as $index => $row) {
if ($row[ConstProviderInterface::CONFIG_PARAM_MODULE] == $module) {
| 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) {
| 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);
| 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());
}
| 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] = | 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), | php | {
"resource": ""
} |
q13146 | ReplaceConverter.replace | train | private function replace(array $number, $fractions = false)
{
return $this->zeroTrim($this->target->splitString(strtr(implode('', $this->zeroPad(
| 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);
| php | {
"resource": ""
} |
q13148 | ReplaceConverter.zeroTrim | train | private function zeroTrim(array $number, $right)
{
$zero = $this->target->getDigit(0);
while (($right ? end($number) : reset($number)) === $zero) {
| 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);
| php | {
"resource": ""
} |
q13150 | ModuleManager.getCoreBag | train | private function getCoreBag()
{
static $coreBag = null;
if (is_null($coreBag)) { | php | {
"resource": ""
} |
q13151 | ModuleManager.validateCoreModuleNames | train | private function validateCoreModuleNames()
{
if (!empty($this->coreModules)) {
$coreBag = $this->getCoreBag();
if (!$coreBag->hasAllCoreModules()) {
throw new LogicException(sprintf(
| php | {
"resource": ""
} |
q13152 | ModuleManager.getModule | train | public function getModule($name)
{
if ($this->isLoaded($name)) {
return $this->loaded[$name];
| php | {
"resource": ""
} |
q13153 | ModuleManager.getUnloadedModules | train | public function getUnloadedModules(array $modules)
{
$unloaded = array();
foreach ($modules as $module) | 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
| 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 = | php | {
"resource": ""
} |
q13156 | ModuleManager.removeFromCacheDir | train | public function removeFromCacheDir($module)
{
// Create a path
$path | php | {
"resource": ""
} |
q13157 | ModuleManager.removeFromUploadsDir | train | public function removeFromUploadsDir($module)
{
// Create a path
$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
));
} | php | {
"resource": ""
} |
q13159 | ModuleManager.loadAllTranslations | train | public function loadAllTranslations($language)
{
foreach ($this->loaded as | 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) {
| 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 . | 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;
}
| 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')) {
| php | {
"resource": ""
} |
q13164 | FilterInvoker.getPaginationUrl | train | private function getPaginationUrl($page, $sort, $desc)
{
$placeholder = '(:var)';
$data = array(
self::FILTER_PARAM_PAGE => $placeholder, | 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 {
| 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));
| 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()
| 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':
| 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,
| php | {
"resource": ""
} |
q13170 | CurlHttplCrawler.post | train | public function post($url, $data = array(), array $extra = array())
{
$curl = new Curl(array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => | 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',
| 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,
| 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(
| 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
| php | {
"resource": ""
} |
q13175 | StringDecryptor.decode | train | public function decode()
{
// Fix plus to space conversion issue
$this->data = str_replace(' ', '+', $this->data);
// Do decoding
| 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
| 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;
}
| 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 ) {
| 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 ) {
| php | {
"resource": ""
} |
q13180 | ImageFile.getImageInfo | train | final protected function getImageInfo($file)
{
$image = getimagesize($file);
if ($image !== false) {
return array(
'width' => $image[0],
| 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:
| 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'];
| 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:
| 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, | 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:');
| 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)
| 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)
| 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)
| 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, ' ', '_')),
| 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 = [];
| 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'])) {
| php | {
"resource": ""
} |
q13192 | GitHubTasks.formatLabelNames | train | protected function formatLabelNames(array $labels)
{
if (empty($labels)) {
return;
}
$names = [];
foreach ($labels as $label) {
if (!isset($label['name'])) {
| php | {
"resource": ""
} |
q13193 | PSR4.addNamespaces | train | public function addNamespaces(array $namespaces)
{
foreach ($namespaces as $prefix => $baseDir) {
| php | {
"resource": ""
} |
q13194 | Env.init | train | public static function init($locale, $environment, $version)
{
$envFilename = Registry::get('applicationPath') . '/.env';
if (file_exists($envFilename)) {
| php | {
"resource": ""
} |
q13195 | Stream.register | train | static public function register(BlobRestProxy $proxy, $name = 'azure')
{
| 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 | 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 (! | php | {
"resource": ""
} |
q13198 | Stream.stream_write | train | public function stream_write($data)
{
if (! $this->temporaryFileHandle) {
return 0;
}
$len = strlen($data);
| 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()
| php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.