_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12200 | CDatabaseBasic.saveHistory | train | public function saveHistory($extra = null)
{
if (!is_null($extra)) {
self::$queries[] = $extra;
self::$params[] = null;
}
self::$queries[] = 'Saved query-history to session.';
self::$params[] = null;
$key = $this->options['session_key'];
$_SESSION[$key]['numQueries'] = self::$numQueries;
$_SESSION[$key]['queries'] = self::$queries;
$_SESSION[$key]['params'] = self::$params;
} | php | {
"resource": ""
} |
q12201 | CDatabaseBasic.executeFetchAll | train | public function executeFetchAll(
$query = null,
$params = []
) {
$this->execute($query, $params);
return $this->fetchAll();
} | php | {
"resource": ""
} |
q12202 | CDatabaseBasic.executeFetchOne | train | public function executeFetchOne(
$query = null,
$params = []
) {
$this->execute($query, $params);
return $this->fetchOne();
} | php | {
"resource": ""
} |
q12203 | CDatabaseBasic.fetchInto | train | public function fetchInto($object)
{
$this->stmt->setFetchMode(\PDO::FETCH_INTO, $object);
return $this->stmt->fetch();
} | php | {
"resource": ""
} |
q12204 | Utility.machineName | train | public static function machineName($string, $pattern = '/[^a-zA-Z0-9\-]/')
{
if (!is_string($string)) {
throw new \InvalidArgumentException(
'A non string argument has been given.'
);
}
$string = strtr($string, ' ', '-');
return strtolower(self::cleanString($string, $pattern));
} | php | {
"resource": ""
} |
q12205 | CsvManager.hasDuplicates | train | public function hasDuplicates($target)
{
if ($this->exists($target)) {
$duplicates = $this->getDuplicates();
return (int) $duplicates[$target] > 1;
} else {
throw new RuntimeException(sprintf(
'Attempted to read non-existing value %s', $target
));
}
} | php | {
"resource": ""
} |
q12206 | CsvManager.append | train | public function append($value)
{
if (strpos($value, self::SEPARATOR) !== false) {
throw new LogicException('A value cannot contain delimiter');
}
array_push($this->collection, $value);
return $this;
} | php | {
"resource": ""
} |
q12207 | CsvManager.exists | train | public function exists()
{
foreach (func_get_args() as $value) {
if (!in_array($value, $this->collection)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q12208 | CsvManager.delete | train | public function delete($target, $keepDuplicates = true)
{
// We need a copy of $this->collection, not itself:
$array = $this->collection;
foreach ($array as $index => $value) {
if ($value == $target) {
unset($array[$index]);
if ($keepDuplicates === true) {
break;
}
}
}
// Now override original stack with replaced one
$this->collection = $array;
} | php | {
"resource": ""
} |
q12209 | CsvManager.loadFromString | train | public function loadFromString($string)
{
$target = array();
$array = explode(self::SEPARATOR, $string);
foreach ($array as $index => $value) {
// Additional check
if (!empty($value)) {
// Ensure we have only clean values
if (strpos(self::SEPARATOR, $value) === false) {
array_push($target, $value);
}
}
}
// Override with modified one
$this->collection = $target;
} | php | {
"resource": ""
} |
q12210 | AbstractMediaElement.createSourceElements | train | final protected function createSourceElements(array $sources)
{
// To be returned
$output = array();
foreach ($sources as $type => $src) {
$output[] = $this->createSourceElement($type, $src);
}
return $output;
} | php | {
"resource": ""
} |
q12211 | AbstractMediaElement.createSourceElement | train | final protected function createSourceElement($type, $src)
{
// Tag attributes
$attrs = array(
'src' => $src,
'type' => $type
);
$node = new NodeElement();
return $node->openTag('source')
->addAttributes($attrs)
->finalize(true);
} | php | {
"resource": ""
} |
q12212 | Module.getViews | train | public function getViews()
{
$config = $this->config;
$directories = array();
$dir = $this->directory;
if (isset($config['app']['views'])) {
$directoriesTmp = $config['app']['views'];
if (!is_array($directoriesTmp)) {
$directoriesTmp = array($directoriesTmp);
}
foreach ($directoriesTmp as $directory) {
$this->addFolder($directories, $dir . '/' . $directory);
}
}
return $directories;
} | php | {
"resource": ""
} |
q12213 | ObjectEncoder.addIgnoredProperty | train | public function addIgnoredProperty(string $type, $propertyNames): void
{
if (!is_string($propertyNames) && !is_array($propertyNames)) {
throw new InvalidArgumentException('Property name must be a string or array of strings');
}
if (!isset($this->ignoredEncodedPropertyNamesByType[$type])) {
$this->ignoredEncodedPropertyNamesByType[$type] = [];
}
foreach ((array)$propertyNames as $propertyName) {
$this->ignoredEncodedPropertyNamesByType[$type][$this->normalizePropertyName($propertyName)] = true;
}
} | php | {
"resource": ""
} |
q12214 | ObjectEncoder.decodeArrayOrVariadicConstructorParamValue | train | protected function decodeArrayOrVariadicConstructorParamValue(
ReflectionParameter $constructorParam,
$constructorParamValue,
EncodingContext $context
) {
if (!is_array($constructorParamValue)) {
throw new EncodingException('Value must be an array');
}
if (count($constructorParamValue) === 0) {
return [];
}
if ($constructorParam->isVariadic() && $constructorParam->hasType()) {
$type = $constructorParam->getType() . '[]';
return $this->encoders->getEncoderForType($type)
->decode($constructorParamValue, $type, $context);
}
if (is_object($constructorParamValue[0])) {
$type = get_class($constructorParamValue[0]) . '[]';
return $this->encoders->getEncoderForType($type)
->decode($constructorParamValue, $type, $context);
}
$type = gettype($constructorParamValue[0]) . '[]';
return $this->encoders->getEncoderForType($type)
->decode($constructorParamValue, $type, $context);
} | php | {
"resource": ""
} |
q12215 | ObjectEncoder.decodeConstructorParamValue | train | private function decodeConstructorParamValue(
ReflectionParameter $constructorParam,
$constructorParamValue,
ReflectionClass $reflectionClass,
string $normalizedHashPropertyName,
EncodingContext $context
) {
if ($constructorParam->hasType() && !$constructorParam->isArray() && !$constructorParam->isVariadic()) {
$constructorParamType = (string)$constructorParam->getType();
return $this->encoders->getEncoderForType($constructorParamType)
->decode($constructorParamValue, $constructorParamType, $context);
}
if ($constructorParam->isVariadic() || $constructorParam->isArray()) {
return $this->decodeArrayOrVariadicConstructorParamValue(
$constructorParam,
$constructorParamValue,
$context
);
}
$decodedValue = null;
if (
$this->tryDecodeValueFromGetterType(
$reflectionClass,
$normalizedHashPropertyName,
$constructorParamValue,
$context,
$decodedValue
)
) {
return $decodedValue;
}
// At this point, let's just check if the value we're trying to decode is a scalar, and if so, just return it
if (is_scalar($constructorParamValue)) {
$type = gettype($constructorParamValue);
return $this->encoders->getEncoderForType($type)
->decode($constructorParamValue, $type, $context);
}
throw new EncodingException("Failed to decode constructor parameter {$constructorParam->getName()}");
} | php | {
"resource": ""
} |
q12216 | ObjectEncoder.normalizeHashProperties | train | private function normalizeHashProperties(array $objectHash): array
{
$encodedHashProperties = [];
foreach ($objectHash as $propertyName => $propertyValue) {
$encodedHashProperties[$this->normalizePropertyName($propertyName)] = $propertyName;
}
return $encodedHashProperties;
} | php | {
"resource": ""
} |
q12217 | ObjectEncoder.propertyIsIgnored | train | private function propertyIsIgnored(string $type, string $propertyName): bool
{
return isset($this->ignoredEncodedPropertyNamesByType[$type][$this->normalizePropertyName($propertyName)]);
} | php | {
"resource": ""
} |
q12218 | ObjectEncoder.tryDecodeValueFromGetterType | train | private function tryDecodeValueFromGetterType(
ReflectionClass $reflectionClass,
string $normalizedPropertyName,
$encodedValue,
EncodingContext $context,
&$decodedValue
): bool {
// Check if we can infer the type from any getters or setters
foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
if (
!$reflectionMethod->hasReturnType() ||
$reflectionMethod->getReturnType() === 'array' ||
$reflectionMethod->isConstructor() ||
$reflectionMethod->isDestructor() ||
$reflectionMethod->getNumberOfRequiredParameters() > 0
) {
continue;
}
$propertyName = null;
// Try to extract the property name from the getter/has-er/is-er
if (strpos($reflectionMethod->name, 'get') === 0 || strpos($reflectionMethod->name, 'has') === 0) {
$propertyName = lcfirst(substr($reflectionMethod->name, 3));
} elseif (strpos($reflectionMethod->name, 'is') === 0) {
$propertyName = lcfirst(substr($reflectionMethod->name, 2));
}
if ($propertyName === null) {
continue;
}
$encodedPropertyName = $this->normalizePropertyName($propertyName);
// This getter matches the property name we're looking for
if ($encodedPropertyName === $normalizedPropertyName) {
try {
$reflectionMethodReturnType = (string)$reflectionMethod->getReturnType();
$decodedValue = $this->encoders->getEncoderForType($reflectionMethodReturnType)
->decode($encodedValue, $reflectionMethodReturnType, $context);
return true;
} catch (EncodingException $ex) {
return false;
}
}
}
return false;
} | php | {
"resource": ""
} |
q12219 | MagicQuotesFilter.filter | train | public function filter($value)
{
return is_array($value) ? array_map(array($this, __FUNCTION__), $value) : stripslashes($value);
} | php | {
"resource": ""
} |
q12220 | LastCategoryKeeper.getLastCategoryId | train | public function getLastCategoryId()
{
$value = $this->getData();
if ($this->flashed === true) {
// Clear data
$this->clearData();
}
return $value;
} | php | {
"resource": ""
} |
q12221 | EnhancementConfigProvider.getDefaultPaymentConfig | train | public function getDefaultPaymentConfig()
{
$configuration = [];
$isActive = $this->enhancementHelper->isActiveDefaultPayment();
$configuration['isActiveDefaultPayment'] = $isActive;
if ($isActive) {
$configuration['defaultMethod'] = $this->enhancementHelper->getDefaultMethod();
}
return $configuration;
} | php | {
"resource": ""
} |
q12222 | EnhancementConfigProvider.getGoogleAddressConfig | train | public function getGoogleAddressConfig()
{
$configuration = [];
$isActive = $this->enhancementHelper->isActiveGoogleAddress();
$configuration['isActiveGoogleAddress'] = $isActive;
if ($isActive) {
$configuration['googleAddressCountry'] = $this->enhancementHelper->getGoogleMapAddressCountries();
}
return $configuration;
} | php | {
"resource": ""
} |
q12223 | PartialBag.getPartialFile | train | public function getPartialFile($name)
{
$file = $this->findPartialFile($name);
if (is_file($file)) {
return $file;
} else if ($this->hasStaticPartial($name)) {
return $this->getStaticFile($name);
} else {
throw new LogicException(sprintf('Could not find a registered partial called %s', $name));
}
} | php | {
"resource": ""
} |
q12224 | PartialBag.addStaticPartial | train | public function addStaticPartial($baseDir, $name)
{
$file = $this->createPartialPath($baseDir, $name);
if (!is_file($file)) {
throw new LogicException(sprintf('Invalid base directory or file name provided "%s"', $file));
}
$this->staticPartials[$name] = $file;
return $this;
} | php | {
"resource": ""
} |
q12225 | PartialBag.addStaticPartials | train | public function addStaticPartials(array $collection)
{
foreach ($collection as $baseDir => $name) {
$this->addStaticPartial($baseDir, $name);
}
return $this;
} | php | {
"resource": ""
} |
q12226 | PartialBag.findPartialFile | train | private function findPartialFile($name)
{
foreach ($this->partialDirs as $dir) {
$file = $this->createPartialPath($dir, $name);
if (is_file($file)) {
return $file;
}
}
return false;
} | php | {
"resource": ""
} |
q12227 | Aoe_Api2_Model_Acl._setRules | train | protected function _setRules()
{
$resources = $this->getResources();
/** @var Mage_Api2_Model_Resource_Acl_Global_Rule_Collection $rulesCollection */
$rulesCollection = Mage::getResourceModel('api2/acl_global_rule_collection');
foreach ($rulesCollection as $rule) {
/** @var Mage_Api2_Model_Acl_Global_Rule $rule */
if (Mage_Api2_Model_Acl_Global_Rule::RESOURCE_ALL === $rule->getResourceId()) {
if (in_array($rule->getRoleId(), Mage_Api2_Model_Acl_Global_Role::getSystemRoles())) {
/** @var Mage_Api2_Model_Acl_Global_Role $role */
$role = $this->_getRolesCollection()->getItemById($rule->getRoleId());
$privileges = $this->_getConfig()->getResourceUserPrivileges(
$this->_resourceType,
$role->getConfigNodeName()
);
if (!array_key_exists($this->_operation, $privileges)) {
continue;
}
}
$this->allow($rule->getRoleId());
} elseif (in_array($rule->getResourceId(), $resources)) {
$this->allow($rule->getRoleId(), $rule->getResourceId(), $rule->getPrivilege());
}
}
return $this;
} | php | {
"resource": ""
} |
q12228 | HeaderBag.getRequestHeader | train | public function getRequestHeader($header, $default = false)
{
if ($this->hasRequestHeader($header)) {
$headers = $this->getAllRequestHeaders();
return $headers[$header];
} else {
return $default;
}
} | php | {
"resource": ""
} |
q12229 | HeaderBag.setStatusCode | train | public function setStatusCode($code)
{
static $sg = null;
if (is_null($sg)) {
$sg = new StatusGenerator();
}
$status = $sg->generate($code);
if ($status !== false) {
$this->append($status);
}
return $this;
} | php | {
"resource": ""
} |
q12230 | HeaderBag.setMany | train | public function setMany(array $headers)
{
$this->clear();
foreach ($headers as $header) {
$this->append($header);
}
return $this;
} | php | {
"resource": ""
} |
q12231 | HeaderBag.appendPair | train | public function appendPair($key, $value)
{
$header = sprintf('%s: %s', $key, $value);
$this->append($header);
return $this;
} | php | {
"resource": ""
} |
q12232 | HeaderBag.appendPairs | train | public function appendPairs(array $headers)
{
foreach ($headers as $key => $value) {
$this->appendPair($key, $value);
}
return $this;
} | php | {
"resource": ""
} |
q12233 | Response.display | train | public function display()
{
\http_response_code($this->getResponseCode());
if ($this->contentType) {
header('Content-Type: ' . $this->contentType);
}
// header('Content-Length: ' . strlen($this->content));
if ($this->redirection) {
header('Location: ' . $this->redirection);
}
Events::dispatch('beforeResponseSend', array($this));
session_write_close();
print $this->content;
Profiler::dump();
Events::dispatch('afterResponseSend', array($this));
} | php | {
"resource": ""
} |
q12234 | HtmlCompressor.compress | train | public function compress($content)
{
// Increment recursion level only before doing a compression
ini_set('pcre.recursion_limit', '16777');
$content = $this->removeSpaces($content);
$content = $this->removeComments($content);
return $content;
} | php | {
"resource": ""
} |
q12235 | DrushCommand.findDrupalDocroot | train | protected function findDrupalDocroot()
{
/** @var EngineType $engine */
$engine = $this->engineInstance();
/** @var DrupalProjectType $project */
$project = $this->projectInstance();
if ($engine instanceof DockerEngineType && !$this->localhost) {
return "/var/www/html/{$project->getInstallRoot(true)}";
}
return $project->getInstallPath();
} | php | {
"resource": ""
} |
q12236 | NewsAdmin.getEditForm | train | public function getEditForm($id = null, $fields = null)
{
$form = parent::getEditForm($id, $fields);
$siteConfig = SiteConfig::current_site_config();
/**
* SortOrder is ignored unless sortable is enabled.
*/
if ($this->modelClass === "Tag" && $siteConfig->AllowTags) {
$form->Fields()
->fieldByName('Tag')
->getConfig()
->addComponent(
new GridFieldOrderableRows(
'SortOrder'
)
);
}
if ($this->modelClass === "News" && !$siteConfig->AllowExport) {
$form->Fields()
->fieldByName("News")
->getConfig()
->removeComponentsByType('GridFieldExportButton')
->addComponent(
new GridfieldNewsPublishAction()
);
}
return $form;
} | php | {
"resource": ""
} |
q12237 | NewsAdmin.getList | train | public function getList()
{
/** @var DataList $list */
$list = parent::getList();
if ($this->modelClass === 'News' && class_exists('Subsite') && Subsite::currentSubsiteID() > 0) {
$pages = NewsHolderPage::get()->filter(array('SubsiteID' => (int)Subsite::currentSubsiteID()));
$filter = $pages->column('ID');
/* Manual join needed because otherwise no items are found. Unknown why. */
$list = $list->innerJoin('NewsHolderPage_Newsitems', 'NewsHolderPage_Newsitems.NewsID = News.ID')
->filter(array('NewsHolderPage_Newsitems.NewsHolderPageID' => $filter));
}
return $list;
} | php | {
"resource": ""
} |
q12238 | ArrayDigitList.validateDigits | train | private function validateDigits(& $digits)
{
ksort($digits);
if (count($digits) < 2) {
throw new \InvalidArgumentException('Number base must have at least 2 digits');
} elseif (array_keys($digits) !== range(0, count($digits) - 1)) {
throw new \InvalidArgumentException('Invalid digit values in the number base');
} elseif ($this->detectDuplicates($digits)) {
throw new \InvalidArgumentException('Number base cannot have duplicate digits');
}
} | php | {
"resource": ""
} |
q12239 | ArrayDigitList.detectDuplicates | train | private function detectDuplicates(array $digits)
{
for ($i = count($digits); $i > 0; $i--) {
if (array_search(array_pop($digits), $digits) !== false) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q12240 | ArrayDigitList.detectConflict | train | private function detectConflict(array $digits, callable $detect)
{
foreach ($digits as $digit) {
if ($this->inDigits($digit, $digits, $detect)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q12241 | ArrayDigitList.inDigits | train | private function inDigits($digit, array $digits, callable $detect)
{
foreach ($digits as $haystack) {
if ($digit !== $haystack && $detect($haystack, $digit) !== false) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q12242 | BaseDataContext.setKernel | train | public function setKernel(KernelInterface $kernel) {
$this->kernel = $kernel;
$this->container = $kernel->getContainer();
} | php | {
"resource": ""
} |
q12243 | BaseDataContext.createClient | train | public function createClient() {
$this->client = $this->getKernel()->getContainer()->get('test.client');
$client = $this->client;
return $client;
} | php | {
"resource": ""
} |
q12244 | BaseDataContext.parseScenarioParameters | train | public function parseScenarioParameters(array &$parameters, $checkExp = false) {
foreach ($parameters as $key => $value) {
if ($this->isScenarioParameter($value, $checkExp)) {
$parameters[$key] = $this->getScenarioParameter($value);
}
}
return $parameters;
} | php | {
"resource": ""
} |
q12245 | BaseDataContext.isScenarioParameter | train | public function isScenarioParameter($value, $checkExp = false) {
if ($this->scenarioParameters === null) {
$this->initParameters();
}
$result = isset($this->scenarioParameters[$value]);
if (!$result) {
if (substr($value, 0, 1) === "%" && substr($value, strlen($value) - 1, 1) === "%") {
$result = true;
}
}
if (!$result && $checkExp === true) {
foreach ($this->scenarioParameters as $key => $v) {
if (preg_match("/" . $key . "/", $value)) {
$result = true;
break;
}
}
}
return $result;
} | php | {
"resource": ""
} |
q12246 | BaseDataContext.getScenarioParameter | train | public function getScenarioParameter($key, $checkExp = false) {
$parameters = $this->getScenarioParameters();
// var_dump(array_keys($parameters));
$user = null;
if ($this->currentUser) {
$user = $this->find($this->userClass, $this->currentUser->getId());
}
$value = null;
if (empty($key)) {
xdebug_print_function_stack();
throw new Exception("The scenario parameter can not be empty.");
}
if (isset($parameters[$key])) {
if (is_callable($parameters[$key])) {
$value = call_user_func_array($parameters[$key], [$user, $this]);
} else {
$value = $parameters[$key];
}
} else {
$found = false;
if ($checkExp === true) {
foreach ($parameters as $k => $v) {
if (preg_match("/" . $k . "/", $key)) {
$value = str_replace($k, $this->getScenarioParameter($k), $key);
$found = true;
break;
}
}
}
if (!$found) {
throw new Exception(sprintf("The scenario parameter '%s' is not defined", $key));
}
}
return $value;
} | php | {
"resource": ""
} |
q12247 | BaseDataContext.iSetConfigurationKeyWithValue | train | public function iSetConfigurationKeyWithValue($wrapperName, $key, $value) {
if ($value === "false") {
$value = false;
} else if ($value === "true") {
$value = true;
}
$configurationManager = $this->container->get($this->container->getParameter("tecnocreaciones_tools.configuration_manager.name"));
$wrapper = $configurationManager->getWrapper($wrapperName);
$success = false;
if ($this->accessor->isWritable($wrapper, $key) === true) {
$success = $this->accessor->setValue($wrapper, $key, $value);
} else {
$success = $configurationManager->set($key, $value, $wrapperName, null, true);
}
if ($success === false) {
throw new Exception(sprintf("The value of '%s' can not be update with value '%s'.", $key, $value));
}
$configurationManager->flush(true);
if ($this->accessor->isReadable($wrapper, $key)) {
$newValue = $this->accessor->getValue($wrapper, $key);
} else {
$newValue = $configurationManager->get($key, $wrapperName, null);
}
if ($value != $newValue) {
throw new Exception(sprintf("Failed to update '%s' key '%s' with '%s' configuration.", $wrapperName, $key, $value));
}
} | php | {
"resource": ""
} |
q12248 | BaseDataContext.aClearEntityTable | train | public function aClearEntityTable($className, $andWhere = null) {
$doctrine = $this->getDoctrine();
$em = $doctrine->getManager();
if ($em->getFilters()->isEnabled('softdeleteable')) {
$em->getFilters()->disable('softdeleteable');
}
if ($className === \Pandco\Bundle\AppBundle\Entity\User\DigitalAccount\TimeWithdraw::class) {
$query = $em->createQuery("UPDATE " . \Pandco\Bundle\AppBundle\Entity\App\User\DigitalAccount\DigitalAccountConfig::class . " dac SET dac.timeWithdraw = null");
$query->execute();
}
$query = $em->createQuery("DELETE FROM " . $className . " " . $andWhere);
$query->execute();
$em->flush();
$em->clear();
} | php | {
"resource": ""
} |
q12249 | BaseDataContext.theQuantityOfElementInEntityIs | train | public function theQuantityOfElementInEntityIs($className, $expresion) {
$doctrine = $this->getDoctrine();
$em = $doctrine->getManager();
$query = $em->createQuery('SELECT COUNT(u.id) FROM ' . $className . ' u');
$count = $query->getSingleScalarResult();
$expAmount = explode(" ", $expresion);
$amount2 = \Pandco\Bundle\AppBundle\Service\Util\CurrencyUtil::fotmatToNumber($expAmount[1]);
if (version_compare($count, $amount2, $expAmount[0]) === false) {
throw new Exception(sprintf("Expected '%s' but there quantity is '%s'.", $expresion, $count));
}
} | php | {
"resource": ""
} |
q12250 | BaseDataContext.findOneElement | train | public function findOneElement($class, UserInterface $user = null) {
$em = $this->getDoctrine()->getManager();
$alias = "o";
$qb = $em->createQueryBuilder()
->select($alias)
->from($class, $alias);
if ($user !== null) {
$qb
->andWhere("o.user = :user")
->setParameter("user", $user)
;
}
$qb->orderBy("o.createdAt", "DESC");
$entity = $qb->setMaxResults(1)->getQuery()->getOneOrNullResult();
return $entity;
} | php | {
"resource": ""
} |
q12251 | BaseDataContext.arrayReplaceRecursiveValue | train | private function arrayReplaceRecursiveValue(&$array, $parameters) {
foreach ($array as $key => $value) {
// create new key in $array, if it is empty or not an array
if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key]))) {
$array[$key] = array();
}
// overwrite the value in the base array
if (is_array($value)) {
$value = $this->arrayReplaceRecursiveValue($array[$key], $parameters);
} else {
$value = $this->parseParameter($value, $parameters);
}
$array[$key] = $value;
}
return $array;
} | php | {
"resource": ""
} |
q12252 | BaseDataContext.aExecuteCommandTo | train | public function aExecuteCommandTo($command) {
$this->restartKernel();
$kernel = $this->getKernel();
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);
$exploded = explode(" ", $command);
$commandsParams = [
];
foreach ($exploded as $value) {
if (!isset($commandsParams["command"])) {
$commandsParams["command"] = $value;
} else {
$e2 = explode("=", $value);
// var_dump($e2);
if (count($e2) == 1) {
$commandsParams[] = $e2[0];
} else if (count($e2) == 2) {
$commandsParams[$e2[0]] = $e2[1];
}
}
}
foreach ($commandsParams as $key => $value) {
$commandsParams[$key] = $value;
}
$input = new \Symfony\Component\Console\Input\ArrayInput($commandsParams);
if ($output === null) {
$output = new \Symfony\Component\Console\Output\ConsoleOutput();
}
$application->run($input, $output);
// $content = $output->fetch();
} | php | {
"resource": ""
} |
q12253 | CreditCardDetector.detect | train | public function detect($number)
{
foreach (self::$cardPatterns as $name => $pattern) {
if (preg_match($pattern, $number)) {
return $name;
}
}
return false;
} | php | {
"resource": ""
} |
q12254 | CacheFile.load | train | public function load()
{
// Check for existence only once and save the result
$exists = is_file($this->file);
if ($this->autoCreate == false && !$exists) {
throw new RuntimeException('File does not exist');
} else if ($this->autoCreate == true && !$exists) {
// Create new empty file
touch($this->file);
$this->loaded = true;
// There's no need to fetch content from the empty file
return array();
}
$content = file_get_contents($this->file);
$content = $this->serializer->unserialize($content);
if (!$content) {
$content = array();
}
$this->content = $content;
$this->loaded = true;
} | php | {
"resource": ""
} |
q12255 | CacheFile.save | train | public function save(array $data)
{
return (bool) file_put_contents($this->file, $this->serializer->serialize($data));
} | php | {
"resource": ""
} |
q12256 | Scanner.getAccounts | train | public function getAccounts()
{
if ($output = $this->execute('icacls', $this->path)) {
// The first element will always include the path, we'll
// remove it before passing the output to the parser.
$output[0] = str_replace($this->path, '', $output[0]);
// The last element will always contain the success / failure message.
array_pop($output);
// We'll also remove blank lines from the output array.
$output = array_filter($output);
// Finally, we'll pass the output to the parser.
return $this->newParser($output)->parse();
}
return false;
} | php | {
"resource": ""
} |
q12257 | Scanner.getId | train | public function getId()
{
if ($output = $this->execute('fsutil file queryfileid', $this->path)) {
if ((bool) preg_match('/(\d{1}[x].*)/', $output[0], $matches)) {
return $matches[0];
}
}
} | php | {
"resource": ""
} |
q12258 | Geo.calculateNewCoordinates | train | public static function calculateNewCoordinates(float $initialLatitude, float $initialLongitude, float $distance, int $bearing)
{
$bearing = deg2rad($bearing);
$latitude = deg2rad($initialLatitude);
$longitude = deg2rad($initialLongitude);
$earth = self::EARTH_RADIUS_METERS / 1000;
$newLatitude = asin(
sin($latitude) * cos($distance/$earth) +
cos($latitude) * sin($distance/$earth) * cos($bearing)
);
$newLongitude = $longitude + atan2(
sin($bearing) * sin($distance/$earth) * cos($latitude),
cos($distance/$earth)-sin($latitude)*sin($newLatitude)
);
return [rad2deg($newLatitude), rad2deg($newLongitude)];
} | php | {
"resource": ""
} |
q12259 | Geo.calculateDistance | train | public static function calculateDistance(float $sourceLatitude, float $sourceLongitude, float $targetLatitude, float $targetLongitude) : float
{
$radSourceLat = deg2rad($sourceLatitude);
$radSourceLon = deg2rad($sourceLongitude);
$radTargetLat = deg2rad($targetLatitude);
$radTargetLon = deg2rad($targetLongitude);
$latitudeDelta = $radTargetLat - $radSourceLat;
$longitudeDelta = $radTargetLon - $radSourceLon;
$angle = 2 * asin(
sqrt(
pow(sin($latitudeDelta / 2), 2) +
cos($radSourceLat) * cos($radTargetLat) * pow(sin($longitudeDelta / 2), 2)
)
);
return $angle * Geo::EARTH_RADIUS_METERS;
} | php | {
"resource": ""
} |
q12260 | Checkbox.createHiddenNode | train | private function createHiddenNode(array $attrs)
{
$attrs = array(
'type' => 'hidden',
'name' => $attrs['name'],
'value' => '0'
);
$node = new NodeElement();
$node->openTag('input')
->addAttributes($attrs)
->finalize(true);
return $node;
} | php | {
"resource": ""
} |
q12261 | Checkbox.createCheckboxNode | train | private function createCheckboxNode(array $attrs)
{
$defaults = array(
'type' => 'checkbox',
'value' => '1'
);
$attrs = array_merge($defaults, $attrs);
$node = new NodeElement();
$node->openTag('input')
->addAttributes($attrs);
// Check if active
if ($this->active == $defaults['value'] || $this->active === true) {
$node->addProperty('checked');
}
$node->finalize(true);
return $node;
} | php | {
"resource": ""
} |
q12262 | AbstractArray.has | train | public function has($needle, bool $strict = true): bool
{
foreach ($this->values as $value) {
if ($strict && $value === $needle) {
return true;
}
if ($strict && $value == $needle) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q12263 | AbstractArray.addValues | train | protected function addValues($values)
{
if (!is_array($values) && !$values instanceof \Traversable) {
//Unable to process values
return;
}
foreach ($values as $value) {
//Passing every value thought the filter
$value = $this->filterValue($value);
if (!is_null($value)) {
$this->values[] = $value;
}
}
} | php | {
"resource": ""
} |
q12264 | Assets.generate_script_dependencies | train | public static function generate_script_dependencies( $maybe_dependencies ) {
$dependencies = [];
foreach ( $maybe_dependencies as $dependency ) {
if ( ! wp_script_is( $dependency, 'enqueued' ) && ! wp_script_is( $dependency, 'registered' ) ) {
continue;
}
$dependencies[] = $dependency;
}
return $dependencies;
} | php | {
"resource": ""
} |
q12265 | Assets.generate_style_dependencies | train | public static function generate_style_dependencies( $maybe_dependencies ) {
$dependencies = [];
foreach ( $maybe_dependencies as $dependency ) {
if ( ! wp_style_is( $dependency, 'enqueued' ) && ! wp_style_is( $dependency, 'registered' ) ) {
continue;
}
$dependencies[] = $dependency;
}
return $dependencies;
} | php | {
"resource": ""
} |
q12266 | MapperFactory.createArgs | train | private function createArgs()
{
$args = array($this->db);
if (is_object($this->paginator)) {
array_push($args, $this->paginator);
}
array_push($args, $this->prefix);
return $args;
} | php | {
"resource": ""
} |
q12267 | LabelManager.loadLabels | train | public function loadLabels($locale, $force = false)
{
if (!$this->labelsLoaded || $force) {
if (file_exists(\Nf\Registry::get('applicationPath') . '/labels/' . $locale . '.ini')) {
$this->labels=parse_ini_file(\Nf\Registry::get('applicationPath') . '/labels/' . $locale . '.ini', true);
$this->labelsLoaded=true;
} else {
throw new \Exception('Cannot load labels for this locale (' . $locale . ')');
}
}
} | php | {
"resource": ""
} |
q12268 | YmlCommandLine.fromYamlString | train | public static function fromYamlString($yml, $config_yml = null)
{
$parser = new sfYamlParser();
$yml_tree = $parser->parse($yml);
if ($config_yml) {
$yml_config_tree = $parser->parse($config_yml);
self::mergeDefaultsIntoYml($yml_tree, $yml_config_tree);
}
$cmd = self::ymlToCmd($yml_tree);
$cmd = self::ymlParseOptions($yml_tree, $cmd);
$cmd = self::ymlParseArguments($yml_tree, $cmd);
$cmd = self::ymlParseCommands($yml_tree, $cmd);
return $cmd;
} | php | {
"resource": ""
} |
q12269 | RouteNotation.toArgs | train | public function toArgs($notation)
{
$target = $this->toClassPath($notation);
return explode(self::ROUTE_SYNTAX_SEPARATOR, $target);
} | php | {
"resource": ""
} |
q12270 | RouteNotation.toCompliant | train | public function toCompliant($notation)
{
$chunks = explode(self::ROUTE_SYNTAX_SEPARATOR, $notation);
// Save the action into a variable
$action = $chunks[1];
// Break what we have according to separators now
$parts = explode(':', $chunks[0]);
// Take a module and save it now
$module = array_shift($parts);
// It's time to build PSR-0 compliant path
$path = sprintf('/%s/%s/%s', $module, self::ROUTE_CONTROLLER_DIR, implode('/', $parts));
return array($path => $action);
} | php | {
"resource": ""
} |
q12271 | RouteNotation.toClassPath | train | public function toClassPath($class)
{
$parts = explode(self::ROUTE_SYNTAX_DELIMITER, $class);
$module = $parts[0];
unset($parts[0]);
$path = sprintf('/%s/%s/%s', $module, self::ROUTE_CONTROLLER_DIR, implode('/', $parts));
return $path;
} | php | {
"resource": ""
} |
q12272 | CwsCrypto.hashPassword | train | public function hashPassword($password)
{
if ($this->mode == self::MODE_BCRYPT) {
return $this->hashModeBcrypt($password);
} elseif ($this->mode == self::MODE_PBKDF2) {
return $this->hashModePbkdf2($password);
}
$this->error = 'You have to set the mode...';
$this->cwsDebug->error($this->error);
} | php | {
"resource": ""
} |
q12273 | CwsCrypto.hashModePbkdf2 | train | private function hashModePbkdf2($password)
{
$this->cwsDebug->titleH2('Create password hash using PBKDF2');
$this->cwsDebug->labelValue('Password', $password);
$salt = $this->random(self::PBKDF2_RANDOM_BYTES);
$this->cwsDebug->labelValue('Salt', $salt);
$algorithm = $this->encode(self::PBKDF2_ALGORITHM);
$this->cwsDebug->labelValue('Algorithm', self::PBKDF2_ALGORITHM);
$ite = rand(self::PBKDF2_MIN_ITE, self::PBKDF2_MAX_ITE);
$this->cwsDebug->labelValue('Iterations', $ite);
$ite = $this->encode(rand(self::PBKDF2_MIN_ITE, self::PBKDF2_MAX_ITE));
$params = $algorithm.self::PBKDF2_SEPARATOR;
$params .= $ite.self::PBKDF2_SEPARATOR;
$params .= $salt.self::PBKDF2_SEPARATOR;
$hash = $this->getPbkdf2($algorithm, $password, $salt, $ite, self::PBKDF2_HASH_BYTES, true);
$this->cwsDebug->labelValue('Hash', $hash);
$this->cwsDebug->labelValue('Length', strlen($hash));
$finalHash = $params.base64_encode($hash);
$this->cwsDebug->dump('Encoded hash (length : '.strlen($finalHash).')', $finalHash);
if (strlen($finalHash) == self::PBKDF2_LENGTH) {
return $finalHash;
}
$this->error = 'Cannot generate the PBKDF2 password hash...';
$this->cwsDebug->error($this->error);
} | php | {
"resource": ""
} |
q12274 | CwsCrypto.checkPassword | train | public function checkPassword($password, $hash)
{
if ($this->mode == self::MODE_BCRYPT) {
return $this->checkModeBcrypt($password, $hash);
} elseif ($this->mode == self::MODE_PBKDF2) {
return $this->checkModePbkdf2($password, $hash);
}
$this->error = 'You have to set the mode...';
$this->cwsDebug->error($this->error);
return false;
} | php | {
"resource": ""
} |
q12275 | CwsCrypto.checkModeBcrypt | train | private function checkModeBcrypt($password, $hash)
{
$this->cwsDebug->titleH2('Check password hash in BCRYPT mode');
$this->cwsDebug->labelValue('Password', $password);
$this->cwsDebug->labelValue('Hash', $hash);
$checkHash = crypt($password, $hash);
$this->cwsDebug->labelValue('Check hash', $checkHash);
$result = $this->slowEquals($hash, $checkHash);
$this->cwsDebug->labelValue('Valid?', ($result ? 'YES!' : 'NO...'));
return $result;
} | php | {
"resource": ""
} |
q12276 | CwsCrypto.checkModePbkdf2 | train | private function checkModePbkdf2($password, $hash)
{
$this->cwsDebug->titleH2('Check password hash in PBKDF2 mode');
$this->cwsDebug->labelValue('Password', $password);
$this->cwsDebug->dump('Hash', $hash);
$params = explode(self::PBKDF2_SEPARATOR, $hash);
if (count($params) < self::PBKDF2_SECTIONS) {
return false;
}
$algorithm = $params[self::PBKDF2_ALGORITHM_INDEX];
$salt = $params[self::PBKDF2_SALT_INDEX];
$ite = $params[self::PBKDF2_ITE_INDEX];
$hash = base64_decode($params[self::PBKDF2_HASH_INDEX]);
$this->cwsDebug->labelValue('Decoded hash', $hash);
$checkHash = $this->getPbkdf2($algorithm, $password, $salt, $ite, strlen($hash), true);
$this->cwsDebug->labelValue('Check hash', $checkHash);
$result = $this->slowEquals($hash, $checkHash);
$this->cwsDebug->labelValue('Valid?', ($result ? 'YES!' : 'NO...'));
return $result;
} | php | {
"resource": ""
} |
q12277 | CwsCrypto.encrypt | train | public function encrypt($data)
{
$this->cwsDebug->titleH2('Encrypt data');
if (empty($this->encryptionKey)) {
$this->error = 'You have to set the encryption key...';
$this->cwsDebug->error($this->error);
return;
}
if (empty($data)) {
$this->error = 'Data empty...';
$this->cwsDebug->error($this->error);
return;
}
$this->cwsDebug->labelValue('Encryption key', $this->encryptionKey);
$this->cwsDebug->dump('Data', $data);
$td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CFB, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = mcrypt_create_iv($ivsize, MCRYPT_DEV_URANDOM);
$key = $this->validateKey($this->encryptionKey, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, $iv);
$encryptedData = mcrypt_generic($td, $this->encode($data));
mcrypt_generic_deinit($td);
$result = $iv.$encryptedData;
$this->cwsDebug->dump('Encrypted data', $result);
return $result;
} | php | {
"resource": ""
} |
q12278 | CwsCrypto.decrypt | train | public function decrypt($data)
{
$this->cwsDebug->titleH2('Decrypt data');
if (empty($this->encryptionKey)) {
$this->error = 'You have to set the encryption key...';
$this->cwsDebug->error($this->error);
return;
}
if (empty($data)) {
$this->error = 'Data empty...';
$this->cwsDebug->error($this->error);
return;
}
$this->cwsDebug->labelValue('Encryption key', $this->encryptionKey);
$this->cwsDebug->dump('Encrypted data', strval($data));
$result = null;
$td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CFB, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($data, 0, $ivsize);
$key = $this->validateKey($this->encryptionKey, mcrypt_enc_get_key_size($td));
if ($iv) {
$data = substr($data, $ivsize);
mcrypt_generic_init($td, $key, $iv);
$decryptData = mdecrypt_generic($td, $data);
$result = $this->decode($decryptData);
}
$this->cwsDebug->dump('Data', $result);
return $result;
} | php | {
"resource": ""
} |
q12279 | CwsCrypto.encode | train | private function encode($data)
{
$rdm = $this->random();
$data = base64_encode($data);
$startIndex = rand(1, strlen($rdm));
$params = base64_encode($startIndex).self::ENC_SEPARATOR;
$params .= base64_encode(strlen($data)).self::ENC_SEPARATOR;
return $params.substr_replace($rdm, $data, $startIndex, 0);
} | php | {
"resource": ""
} |
q12280 | CwsCrypto.decode | train | private function decode($encData)
{
$params = explode(self::ENC_SEPARATOR, $encData);
if (count($params) < self::ENC_SECTIONS) {
return false;
}
$startIndex = intval(base64_decode($params[self::ENC_STARTINDEX_INDEX]));
$dataLength = intval(base64_decode($params[self::ENC_DATALENGTH_INDEX]));
if (empty($startIndex) || empty($dataLength)) {
return false;
}
$data = $params[self::ENC_DATA_INDEX];
return base64_decode(substr($data, $startIndex, $dataLength));
} | php | {
"resource": ""
} |
q12281 | CwsCrypto.validateKey | train | private static function validateKey($key, $size)
{
$length = strlen($key);
if ($length < $size) {
$key = str_pad($key, $size, $key);
} elseif ($length > $size) {
$key = substr($key, 0, $size);
}
return $key;
} | php | {
"resource": ""
} |
q12282 | AuthManager.getData | train | public function getData($key, $default = false)
{
if ($this->sessionBag->has($key)){
return $this->sessionBag->get($key);
} else {
return $default;
}
} | php | {
"resource": ""
} |
q12283 | AuthManager.loggenIn | train | private function loggenIn()
{
if (!$this->has()) {
if (!($this->authService instanceof UserAuthServiceInterface)) {
// Not logged in
return false;
}
// Now try to find only in cookies, if found prepare a bag
if ($this->reAuth->isStored() && (!$this->has())) {
$userBag = $this->reAuth->getUserBag();
}
// If session namespace is filled up and at the same time data stored in cookies
if (($this->has() && $this->reAuth->isStored()) || $this->has()) {
$data = $this->sessionBag->get(self::AUTH_NAMESPACE);
$userBag = new UserBag();
$userBag->setLogin($data['login'])
->setPasswordHash($data['passwordHash']);
}
// If $userBag wasn't created so far, that means user isn't logged at all
if (!isset($userBag)) {
return false;
}
// Now let's invoke our defined match visitor
$authResult = $this->authService->authenticate($userBag->getLogin(), $userBag->getPasswordHash(), false, false);
if ($authResult == true) {
// Remember success, in order not to query on each request
$this->login($userBag->getLogin(), $userBag->getPasswordHash());
return true;
}
return false;
} else {
return true;
}
} | php | {
"resource": ""
} |
q12284 | AuthManager.login | train | public function login($login, $passwordHash, $remember = false)
{
if ((bool) $remember == true) {
// Write to client's cookies
$this->reAuth->store($login, $passwordHash);
}
// Store it
$this->sessionBag->set(self::AUTH_NAMESPACE, array(
'login' => $login,
'passwordHash' => $passwordHash
));
} | php | {
"resource": ""
} |
q12285 | AuthManager.logout | train | public function logout()
{
if ($this->has()) {
$this->sessionBag->remove(self::AUTH_NAMESPACE);
}
if ($this->reAuth->isStored()) {
$this->reAuth->clear();
}
} | php | {
"resource": ""
} |
q12286 | ControllersRouteGenerator.generateRoute | train | public function generateRoute($method, array $path) : ?Route {
$pathPartsSize = sizeof($path);
//Obtención del nombre de la clase de controlador
$controllerClassName = $this->namespace;
if ($pathPartsSize > 1) {
for ($i = 0; $i < $pathPartsSize - 1; $i++) {
if (!empty($controllerClassName)) {
$controllerClassName .= '\\';
}
$requestPathPart = $path[$i];
$requestPathPart = str_replace(' ', '', ucwords(str_replace('_', ' ', $requestPathPart)));
$controllerClassName .= $requestPathPart;
}
}
else {
if (!empty($controllerClassName)) {
$controllerClassName .= '\\';
}
$controllerClassName .= 'Main';
}
$controllerClassName .= get_property('routes.controllers_suffix', 'Controller');
$route = null;
if (class_exists($controllerClassName)) {
//Obtención del nombre de la metodo del controlador
$controllerAction = (empty($path) || empty($path[$pathPartsSize - 1])) ? 'index' : $path[$pathPartsSize - 1];
$controllerAction = str_replace(' ', '', ucwords(str_replace('_', ' ', $controllerAction)));
$controllerAction .= get_property('routes.actions_suffix', 'Action');
$controllerAction[0] = strtolower($controllerAction[0]);
//Obtención del nombre de la acción
$action = $controllerClassName . '@' . $controllerAction;
$route = new Route($action);
}
return $route;
} | php | {
"resource": ""
} |
q12287 | Select2Util.convertToDynamicLoader | train | public static function convertToDynamicLoader(ChoiceListFactoryInterface $choiceListFactory, Options $options, $value)
{
if ($value instanceof DynamicChoiceLoaderInterface) {
return $value;
}
if (!\is_array($options['choices'])) {
throw new InvalidConfigurationException('The "choice_loader" option must be an instance of DynamicChoiceLoaderInterface or the "choices" option must be an array');
}
if ($options['select2']['ajax']) {
return new AjaxChoiceLoader(self::getChoices($options, $value),
$choiceListFactory);
}
return new DynamicChoiceLoader(self::getChoices($options, $value),
$choiceListFactory);
} | php | {
"resource": ""
} |
q12288 | CommentReport.parameterFields | train | public function parameterFields()
{
$return = FieldList::create(
$title = TextField::create(
'Title', _t('CommentReport.NEWSSEARCHTITLE', 'Search newsitem')
), $count = DropdownField::create(
'Comment', _t('CommentReport.COUNTFILTER', 'Comment count filter'), array(
'' => _t('CommentReport.ANY', 'All'),
'SPAMCOUNT' => _t('CommentReport.SPAMCOUNT', 'One or more spam comments'),
'HIDDENCOUNT' => _t('CommentReport.HIDDENCOUNT', 'One or more hidden comments'),
)
)
);
return $return;
} | php | {
"resource": ""
} |
q12289 | Query.get_related_posts_query | train | public static function get_related_posts_query( $post_id ) {
$_post = get_post( $post_id );
if ( ! isset( $_post->ID ) ) {
return;
}
$tax_query = [];
$taxonomies = get_object_taxonomies( get_post_type( $post_id ), 'object' );
foreach ( $taxonomies as $taxonomy ) {
if ( false === $taxonomy->public || false === $taxonomy->show_ui ) {
continue;
}
$term_ids = wp_get_object_terms( $post_id, $taxonomy->name, [ 'fields' => 'ids' ] );
if ( ! $term_ids ) {
continue;
}
$tax_query[] = [
'taxonomy' => $taxonomy->name,
'field' => 'term_id',
'terms' => $term_ids,
'operator' => 'IN',
];
}
$related_posts_args = [
'post_type' => get_post_type( $post_id ),
'posts_per_page' => 4,
'orderby' => 'rand',
'post__not_in' => [ $post_id ],
'tax_query' => array_merge(
[
'relation' => 'AND',
],
$tax_query
),
];
$related_posts_args = apply_filters( 'mimizuku_related_posts_args', $related_posts_args );
return new \WP_Query(
array_merge(
$related_posts_args,
[
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'suppress_filters' => true,
]
)
);
} | php | {
"resource": ""
} |
q12290 | CsrfProtector.prepare | train | public function prepare()
{
if (!$this->sessionBag->has(self::CSRF_TKN_NAME)) {
$this->sessionBag->set(self::CSRF_TKN_NAME, $this->generateToken());
$this->sessionBag->set(self::CSRF_TKN_TIME, time());
}
$this->prepared = true;
} | php | {
"resource": ""
} |
q12291 | CsrfProtector.isExpired | train | public function isExpired()
{
$this->validatePrepared();
if (!$this->sessionBag->has(self::CSRF_TKN_TIME)) {
return true;
} else {
$age = time() - $this->sessionBag->get(self::CSRF_TKN_TIME);
return $age >= $this->ttl;
}
} | php | {
"resource": ""
} |
q12292 | CsrfProtector.isValid | train | public function isValid($token)
{
$this->validatePrepared();
return $this->sessionBag->has(self::CSRF_TKN_NAME) &&
$this->sessionBag->has(self::CSRF_TKN_TIME) &&
$this->sessionBag->get(self::CSRF_TKN_NAME) === $token;
} | php | {
"resource": ""
} |
q12293 | Template.getQuery | train | public function getQuery()
{
$properties = array(
'data' => $this,
);
$wrapper = new \stdClass();
$collection = new \StdClass();
foreach ($properties as $name => $value) {
if (is_array( $value )) {
foreach ($value as &$val) {
if (is_object( $val )) {
$val = $val->output();
}
}
}
if (is_object( $value ) && !$value instanceof \StdClass) {
$value = $value->output();
}
$collection->$name = $value;
}
$wrapper->template = $collection;
return json_encode($wrapper);
} | php | {
"resource": ""
} |
q12294 | Template.importItem | train | public function importItem(Item $item)
{
foreach ($this->data as $templateData) {
foreach ($item->getData() as $itemData) {
if ($itemData->getName() === $templateData->getName()) {
$templateData->setName($itemData->getName());
$templateData->setValue($itemData->getValue());
$templateData->setPrompt($itemData->getPrompt());
}
}
}
return $this;
} | php | {
"resource": ""
} |
q12295 | Math.roundCollection | train | public static function roundCollection(array $data, $precision = 2)
{
$output = array();
foreach ($data as $key => $value){
$output[$key] = round($value, $precision);
}
return $output;
} | php | {
"resource": ""
} |
q12296 | Math.average | train | public static function average($values)
{
$sum = array_sum($values);
$count = count($values);
// Avoid useless calculations
if ($count == 0) {
return 0;
}
return $sum / $count;
} | php | {
"resource": ""
} |
q12297 | Math.percentage | train | public static function percentage($total, $actual, $round = 1)
{
// Avoid useless calculations
if ($total == 0 || $actual == 0) {
return 0;
}
$value = 100 * $actual / $total;
if (is_integer($round)) {
$value = round($value, $round);
}
return $value;
} | php | {
"resource": ""
} |
q12298 | ConfigProvider.get | train | public function get($key = null, $default = null)
{
if (is_null($key)) {
return Config::get($this->configKey());
}
return Config::get($this->configKey() . '.' . $key, $default);
} | php | {
"resource": ""
} |
q12299 | SickRage.episode | train | public function episode($tvdbId, $season, $episode, $fullPath = 0)
{
$uri = 'episode';
$uriData = [
'tvdbid' => $tvdbId,
'season' => $season,
'episode' => $episode,
'full_path' => $fullPath
];
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.