_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q240100
|
DateTime.mdate
|
train
|
function mdate($date_format = '', $time = '') {
if ($date_format == '') {
$date_format = $this->dateFormat;
}
if ($time == '') {
$time = $this->now();
}
return date($date_format, $time);
}
|
php
|
{
"resource": ""
}
|
q240101
|
DateTime.mdatetime
|
train
|
function mdatetime($time = '', $timezone = '', $datetime_format = '') {
if ($datetime_format == '') {
$datetime_format = $this->dateFormat . ' ' . $this->timeFormat;
}
if ($time == '') {
$time = 'now';
}
if ($timezone == '') {
$timezone = $this->timeZone;
}
$utc = new \DateTimeZone($timezone);
$dt = new \DateTime($time, $utc);
return $dt->format($datetime_format);
}
|
php
|
{
"resource": ""
}
|
q240102
|
DateTime.get_first_date_last_month
|
train
|
function get_first_date_last_month($m=1) {
return $this->mdate($this->dateFormat, mktime(0, 0, 0, $this->mdate("m")-$m, 1, $this->mdate("Y")));
}
|
php
|
{
"resource": ""
}
|
q240103
|
DateTime.get_last_date_last_month
|
train
|
function get_last_date_last_month($m=1) {
return $this->mdate($this->dateFormat, mktime(24, 0, 0, $this->mdate("m")-($m-1), -1, $this->mdate("Y")));
}
|
php
|
{
"resource": ""
}
|
q240104
|
DateTime.get_first_date_last_year
|
train
|
function get_first_date_last_year($y=1) {
return $this->mdate($this->dateFormat, mktime(0, 0, 0, 1, 1, $this->mdate("Y")-$y));
}
|
php
|
{
"resource": ""
}
|
q240105
|
DateTime.get_last_date_last_year
|
train
|
function get_last_date_last_year($y=1) {
return $this->mdate($this->dateFormat, mktime(24, 0, 0, 1, -1, $this->mdate("Y")-($y-1)));
}
|
php
|
{
"resource": ""
}
|
q240106
|
Sources.createNew
|
train
|
public function createNew(
string $name,
array $tags
) : array {
$array = [
'name' => $name,
'tags' => $tags
];
return $this->sendPost(
sprintf('/profiles/%s/sources', $this->userName),
[],
$array
);
}
|
php
|
{
"resource": ""
}
|
q240107
|
Sources.updateOne
|
train
|
public function updateOne(int $sourceId, array $tags, int $otpCode = null, string $ipaddr = '') : array {
$array = [
'tags' => $tags
];
if ($otpCode !== null) {
$array['otpCode'] = $otpCode;
}
return $this->sendPatch(
sprintf('/profiles/%s/sources/%s', $this->userName, $sourceId),
[],
$array
);
}
|
php
|
{
"resource": ""
}
|
q240108
|
Datetime.setMin
|
train
|
public function setMin(string $min) : Datetime
{
$min = date($this->format, strtotime($min));
$this->attributes['min'] = $min;
return $this->addTest('min', function ($value) use ($min) {
return $value >= $min;
});
}
|
php
|
{
"resource": ""
}
|
q240109
|
Datetime.setMax
|
train
|
public function setMax(string $max) : Datetime
{
$max = date($this->format, strtotime($max));
$this->attributes['max'] = $max;
return $this->addTest('max', function ($value) use ($max) {
return $value <= $max;
});
}
|
php
|
{
"resource": ""
}
|
q240110
|
Plugin.generateInfoMetadata
|
train
|
public function generateInfoMetadata(PackageEvent $event)
{
$op = $event->getOperation();
$package = $op->getJobType() == 'update'
? $op->getTargetPackage()
: $op->getPackage();
$installPath = $this->installationManager->getInstallPath($package);
if (preg_match('/^drupal-/', $package->getType())) {
if (preg_match('/^dev-/', $package->getPrettyVersion())) {
$name = $package->getName();
$project = preg_replace('/^.*\//', '', $name);
$version = preg_replace('/^dev-(.*)/', $this->core.'.x-$1-dev', $package->getPrettyVersion());
$branch = preg_replace('/^([0-9]*\.x-[0-9]*).*$/', '$1', $version);
$datestamp = time();
$this->io->write(' - Generating metadata for <info>'.$name.'</info>');
// Compute the rebuild version string for a project.
$version = $this->computeRebuildVersion($installPath, $branch) ?: $version;
if ($this->core == '7') {
// Generate version information for `.info` files in ini format.
$finder = new Finder();
$finder
->files()
->in($installPath)
->name('*.info')
->notContains('datestamp =');
foreach ($finder as $file) {
file_put_contents(
$file->getRealpath(),
$this->generateInfoIniMetadata($version, $project, $datestamp),
FILE_APPEND
);
}
} else {
// Generate version information for `.info.yml` files in YAML format.
$finder = new Finder();
$finder
->files()
->in($installPath)
->name('*.info.yml')
->notContains('datestamp:');
foreach ($finder as $file) {
file_put_contents(
$file->getRealpath(),
$this->generateInfoYamlMetadata($version, $project, $datestamp),
FILE_APPEND
);
}
}
}
}
}
|
php
|
{
"resource": ""
}
|
q240111
|
Plugin.computeRebuildVersion
|
train
|
protected function computeRebuildVersion($installPath, $branch)
{
$version = '';
$branchPreg = preg_quote($branch);
$process = new Process("cd $installPath; git describe --tags");
$process->run();
if ($process->isSuccessful()) {
$lastTag = strtok($process->getOutput(), "\n");
// Make sure the tag starts as Drupal formatted (for eg.
// 7.x-1.0-alpha1) and if we are on a proper branch (ie. not master)
// then it's on that branch.
if (preg_match('/^(?<drupalversion>'.$branchPreg.'\.\d+(?:-[^-]+)?)(?<gitextra>-(?<numberofcommits>\d+-)g[0-9a-f]{7})?$/', $lastTag, $matches)) {
if (isset($matches['gitextra'])) {
// If we found additional git metadata (in particular, number of commits)
// then use that info to build the version string.
$version = $matches['drupalversion'].'+'.$matches['numberofcommits'].'dev';
} else {
// Otherwise, the branch tip is pointing to the same commit as the
// last tag on the branch, in which case we use the prior tag and
// add '+0-dev' to indicate we're still on a -dev branch.
$version = $lastTag.'+0-dev';
}
}
}
return $version;
}
|
php
|
{
"resource": ""
}
|
q240112
|
Plugin.generateInfoIniMetadata
|
train
|
protected function generateInfoIniMetadata($version, $project, $datestamp)
{
$core = preg_replace('/^([0-9]).*$/', '$1.x', $version);
$date = date('Y-m-d', $datestamp);
$info = <<<METADATA
; Information add by drustack/composer-generate-metadata on {$date}
core = "{$core}"
project = "{$project}"
version = "{$version}"
datestamp = "{$datestamp}"
METADATA;
return $info;
}
|
php
|
{
"resource": ""
}
|
q240113
|
Plugin.generateInfoYamlMetadata
|
train
|
protected function generateInfoYamlMetadata($version, $project, $datestamp)
{
$core = preg_replace('/^([0-9]).*$/', '$1.x', $version);
$date = date('Y-m-d', $datestamp);
$info = <<<METADATA
# Information add by drustack/composer-generate-metadata on {$date}
core: "{$core}"
project: "{$project}"
version: "{$version}"
datestamp: "{$datestamp}"
METADATA;
return $info;
}
|
php
|
{
"resource": ""
}
|
q240114
|
FilePath.equals
|
train
|
public function equals(FilePathInterface $filePath): bool
{
return $this->getDrive() === $filePath->getDrive() && $this->isAbsolute() === $filePath->isAbsolute() && $this->getDirectoryParts() === $filePath->getDirectoryParts() && $this->getFilename() === $filePath->getFilename();
}
|
php
|
{
"resource": ""
}
|
q240115
|
FilePath.getDirectory
|
train
|
public function getDirectory(): FilePathInterface
{
return new self($this->myIsAbsolute, $this->myAboveBaseLevel, $this->myDrive, $this->myDirectoryParts, null);
}
|
php
|
{
"resource": ""
}
|
q240116
|
FilePath.getParentDirectory
|
train
|
public function getParentDirectory(): ?FilePathInterface
{
if ($this->myParentDirectory($aboveBaseLevel, $directoryParts)) {
return new self($this->myIsAbsolute, $aboveBaseLevel, $this->myDrive, $directoryParts, null);
}
return null;
}
|
php
|
{
"resource": ""
}
|
q240117
|
FilePath.toAbsolute
|
train
|
public function toAbsolute(): FilePathInterface
{
if ($this->myAboveBaseLevel > 0) {
throw new FilePathLogicException('File path "' . $this->__toString() . '" can not be made absolute: Relative path is above base level.');
}
return new self(true, $this->myAboveBaseLevel, $this->myDrive, $this->myDirectoryParts, $this->myFilename);
}
|
php
|
{
"resource": ""
}
|
q240118
|
FilePath.toRelative
|
train
|
public function toRelative(): FilePathInterface
{
return new self(false, $this->myAboveBaseLevel, null, $this->myDirectoryParts, $this->myFilename);
}
|
php
|
{
"resource": ""
}
|
q240119
|
FilePath.withFilePath
|
train
|
public function withFilePath(FilePathInterface $filePath): FilePathInterface
{
if (!$this->myCombine($filePath, $isAbsolute, $aboveBaseLevel, $directoryParts, $filename, $error)) {
throw new FilePathLogicException('File path "' . $this->__toString() . '" can not be combined with file path "' . $filePath->__toString() . '": ' . $error);
}
return new self($isAbsolute, $aboveBaseLevel, $filePath->getDrive() ?: $this->getDrive(), $directoryParts, $filename);
}
|
php
|
{
"resource": ""
}
|
q240120
|
FilePath.isValid
|
train
|
public static function isValid(string $filePath): bool
{
return self::myFilePathParse(
DIRECTORY_SEPARATOR,
$filePath,
function ($p, $d, &$e) {
return self::myPartValidator($p, $d, $e);
});
}
|
php
|
{
"resource": ""
}
|
q240121
|
FilePath.parse
|
train
|
public static function parse(string $filePath): FilePathInterface
{
if (!self::myFilePathParse(
DIRECTORY_SEPARATOR,
$filePath,
function ($p, $d, &$e) {
return self::myPartValidator($p, $d, $e);
},
null,
$isAbsolute,
$aboveBaseLevel,
$drive,
$directoryParts,
$filename,
$error)
) {
throw new FilePathInvalidArgumentException('File path "' . $filePath . '" is invalid: ' . $error);
}
return new self($isAbsolute, $aboveBaseLevel, $drive, $directoryParts, $filename);
}
|
php
|
{
"resource": ""
}
|
q240122
|
FilePath.myFilePathParse
|
train
|
private static function myFilePathParse(string $directorySeparator, string $path, callable $partValidator, callable $stringDecoder = null, ?bool &$isAbsolute = null, ?int &$aboveBaseLevel = null, ?string &$drive = null, ?array &$directoryParts = null, ?string &$filename = null, ?string &$error = null): bool
{
$drive = null;
// If on Window, try to parse drive.
if (self::myIsWindows()) {
$driveAndPath = explode(':', $path, 2);
if (count($driveAndPath) === 2) {
$drive = $driveAndPath[0];
if (!self::myDriveValidator($drive, $error)) {
return false;
}
$drive = strtoupper($drive);
$path = $driveAndPath[1];
}
}
$result = self::myParse(
$directorySeparator,
DIRECTORY_SEPARATOR !== '\'' ? str_replace('/', DIRECTORY_SEPARATOR, $path) : $path,
$partValidator,
$stringDecoder,
$isAbsolute,
$aboveBaseLevel,
$directoryParts,
$filename,
$error
);
// File path containing a drive and relative path is invalid.
if ($drive !== null && !$isAbsolute) {
$error = 'Path can not contain drive "' . $drive . '" and non-absolute path "' . $path . '".';
return false;
}
return $result;
}
|
php
|
{
"resource": ""
}
|
q240123
|
FilePath.myPartValidator
|
train
|
private static function myPartValidator(string $part, bool $isDirectory, ?string &$error): bool
{
if (preg_match(self::myIsWindows() ? '/[\0<>:*?"|]+/' : '/[\0]+/', $part, $matches)) {
$error = ($isDirectory ? 'Part of directory' : 'Filename') . ' "' . $part . '" contains invalid character "' . $matches[0] . '".';
return false;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240124
|
FilePath.myDriveValidator
|
train
|
private static function myDriveValidator(string $drive, ?string &$error): bool
{
if (!preg_match('/^[a-zA-Z]$/', $drive)) {
$error = 'Drive "' . $drive . '" is invalid.';
return false;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240125
|
AutoLoader.load
|
train
|
public function load($className)
{
$this->_classFilename = $className . '.php';
$this->_includePaths = explode(PATH_SEPARATOR, get_include_path());
$classFound = null;
if(strpos($this->_classFilename, '\\') !== false)
{
$classFound = $this->searchForBackslashNamespacedClass();
}
elseif(strpos($this->_classFilename, '_') !== false)
{
$classFound = $this->searchForUnderscoreNamespacedClass();
}
else
{
$classFound = $this->searchForNonNamespacedClass();
}
return $classFound;
}
|
php
|
{
"resource": ""
}
|
q240126
|
AutoLoader.searchForBackslashNamespacedClass
|
train
|
protected function searchForBackslashNamespacedClass()
{
$filename = $this->_classFilename;
foreach($this->_includePaths as $includePath)
{
$className = str_replace('\\', '/', $filename);
$filePath = $includePath . DIRECTORY_SEPARATOR . $className;
if(file_exists($filePath) == true)
{
require($filePath);
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240127
|
AutoLoader.searchForNonNamespacedClass
|
train
|
protected function searchForNonNamespacedClass()
{
$filename = $this->_classFilename;
foreach($this->_includePaths as $includePath)
{
$filePath = $includePath . DIRECTORY_SEPARATOR . $filename;
if(file_exists($filePath) == true)
{
require($filename);
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240128
|
CrudCommonMethods.getEntityNamePlural
|
train
|
protected function getEntityNamePlural()
{
$name = $this->getEntityNameSingular();
$nameParts = Text::camelCaseToSeparator($name, '#');
$nameParts = explode('#', $nameParts);
$lastPart = array_pop($nameParts);
$lastPart = ucfirst(Text::plural(strtolower($lastPart)));
array_push($nameParts, $lastPart);
return lcfirst(implode('', $nameParts));
}
|
php
|
{
"resource": ""
}
|
q240129
|
CrudCommonMethods.getEntityNameSingular
|
train
|
protected function getEntityNameSingular()
{
$names = explode('\\', $this->getEntityClassName());
$name = end($names);
return lcfirst($name);
}
|
php
|
{
"resource": ""
}
|
q240130
|
Thumb.generateBasename
|
train
|
protected function generateBasename()
{
$filename = md5($this->image . $this->height . $this->width);
if (isset(static::$config['default_extension'])) {
$extension = static::$config['default_extension'];
} else {
$extension = pathinfo($this->image, PATHINFO_EXTENSION);
}
return $filename . '.' . $extension;
}
|
php
|
{
"resource": ""
}
|
q240131
|
Thumb.isCacheExpired
|
train
|
protected function isCacheExpired($destiny)
{
$cacheModified = filemtime($destiny);
if ($this->expiration !== null) {
return $this->expiration > $cacheModified;
}
return filemtime($this->image) > $cacheModified;
}
|
php
|
{
"resource": ""
}
|
q240132
|
Thumb.fromFile
|
train
|
public static function fromFile($filename, $width, $height = 0)
{
$urlizer = new Urlizer($filename);
static::configureUrlizer($urlizer);
// If the filename is not initialized by '/', this is a fullpath
if (strpos($filename, '/') !== 0) {
$filename = $urlizer->getPublicFilename();
}
try {
$thumb = new static($filename, $width, $height);
} catch (\InvalidArgumentException $e) {
if (static::$config['fallback'] === null) {
throw $e;
}
return static::$config['fallback'];
}
$basename = $thumb->generateBasename();
$filename = $urlizer->buildThumbFilename($basename);
$thumb->getCache($filename);
return $urlizer->buildThumbUrl($basename);
}
|
php
|
{
"resource": ""
}
|
q240133
|
Thumb.fromUrl
|
train
|
public static function fromUrl($url, $width, $height = 0)
{
$extension = pathinfo(strtok($url, '?'), PATHINFO_EXTENSION);
$filename = sprintf('%s/thumb_%s.%s', sys_get_temp_dir(), md5($url), $extension);
if (! file_exists($filename) && ! @copy($url, $filename, static::getStreamContextOptions())) {
return static::$config['fallback'];
}
$urlizer = new Urlizer();
static::configureUrlizer($urlizer);
$thumb = new static($filename, $width, $height);
$basename = $thumb->generateBasename();
$filename = $urlizer->buildThumbFilename($basename);
$thumb->getCache($filename);
return $urlizer->buildThumbUrl($basename);
}
|
php
|
{
"resource": ""
}
|
q240134
|
Thumb.image
|
train
|
public static function image($relative, array $attributes = [])
{
$attributes += ['alt' => null];
$height = isset($attributes['height']) ? $attributes['height'] : 0;
$width = isset($attributes['width']) ? $attributes['width'] : 0;
$url = static::url($relative, $width, $height);
$attributes['src'] = $url;
$attrs = [];
foreach ($attributes as $name => $attr) {
$attrs[] = "$name=\"{$attr}\"";
}
$attrs = implode(' ', $attrs);
return "<img {$attrs} />";
}
|
php
|
{
"resource": ""
}
|
q240135
|
Thumb.configureUrlizer
|
train
|
protected static function configureUrlizer(Urlizer $urlizer)
{
$path = isset(static::$config['public_path']) ? static::$config['public_path'] : $_SERVER['DOCUMENT_ROOT'];
$urlizer->setPublicPath($path);
if (isset(static::$config['base_uri'])) {
$urlizer->setBaseUrl(static::$config['base_uri']);
}
$urlizer->setThumbFolder(static::$config['thumb_folder']);
}
|
php
|
{
"resource": ""
}
|
q240136
|
ACacheManager._createData
|
train
|
protected function _createData(callable $func): array
{
$data = \call_user_func($func);
if(!\is_array($data) && !$data instanceof \Traversable) {
return []; //ignore invalid results
}
$return = [];
foreach($data as $key => $value) {
$return[$key] = [
'value' => $value,
'expires' => null
];
}
return $return;
}
|
php
|
{
"resource": ""
}
|
q240137
|
UserController.index
|
train
|
public function index(UrlParamsProcessor $processor)
{
$this->authorize('readList', User::class);
$processor
->addFilter(new ArrayParser('id'))
->addFilter(new StringParser('email'), 'email')
->addFilter(new StringParser('name'))
->addFilter(new StringParser('first_name'))
->addFilter(new StringParser('last_name'))
->addFilter(new DateRangeParser('created_at'))
->addFilter(new DateParser('updated_at'))
->process($this->request);
$results = $this->repository->getMany($processor->buildQueryBuilder());
$results->setPath(apiUrl('users'));
return new UserCollection($results);
}
|
php
|
{
"resource": ""
}
|
q240138
|
UserController.update
|
train
|
public function update($id)
{
$user = $this->repository->getById($id);
if (!$user) {
return $this->errorNotFound();
}
$this->authorize('update', $user);
$input = $this->validator
->bind('name', ['user_id' => $user->id])
->bind('email', ['user_id' => $user->id])
->validate('update');
$user = dispatch_now(new UpdateUser($user, $input));
return new UserResource($user);
}
|
php
|
{
"resource": ""
}
|
q240139
|
Reflections.get
|
train
|
public function get($class=null)
{
$class = $this->get_class($class);
if (isset($this->reflections[$class]))
return $this->reflections[$class];
throw new ActiveRecordException("Class not found: $class");
}
|
php
|
{
"resource": ""
}
|
q240140
|
Preferences.setWebHook
|
train
|
public function setWebHook($url)
{
$this->data->notification = new stdClass;
$this->data->notification->webhook = new stdClass;
$this->data->notification->webhook->url = $url;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240141
|
Preferences.enableMerchantEmail
|
train
|
public function enableMerchantEmail()
{
$this->data->email = new stdClass;
$this->data->email->merchant = new stdClass;
$this->data->email->merchant->enabled = true;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240142
|
Preferences.disableMerchantEmail
|
train
|
public function disableMerchantEmail()
{
$this->data->email = new stdClass;
$this->data->email->merchant = new stdClass;
$this->data->email->merchant->enabled = false;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240143
|
Preferences.enableCustomerEmail
|
train
|
public function enableCustomerEmail()
{
$this->data->email = new stdClass;
$this->data->email->customer = new stdClass;
$this->data->email->customer->enabled = true;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240144
|
Preferences.disableCustomerEmail
|
train
|
public function disableCustomerEmail()
{
$this->data->email = new stdClass;
$this->data->email->customer = new stdClass;
$this->data->email->customer->enabled = false;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240145
|
ContentPackage.boot
|
train
|
public static function boot(ICms $cms)
{
$iocContainer = $cms->getIocContainer();
$iocContainer->bind(IIocContainer::SCOPE_SINGLETON, IContentGroupRepository::class, DbContentGroupRepository::class);
$iocContainer->bind(IIocContainer::SCOPE_SINGLETON, ContentLoaderService::class, ContentLoaderService::class);
$iocContainer->bindCallback(
IIocContainer::SCOPE_SINGLETON,
ContentConfig::class,
function () use ($cms) : ContentConfig {
$definition = new ContentConfigDefinition();
static::defineConfig($definition);
return $definition->finalize();
}
);
}
|
php
|
{
"resource": ""
}
|
q240146
|
Defaults.flattenValues
|
train
|
protected function flattenValues(&$values)
{
array_walk($values, function (&$value) {
if ($this->isOrnamentModel($value)) {
$value = $value->getPrimaryKey();
if (is_array($value)) {
$value = '('.implode(', ', $value).')';
}
}
});
}
|
php
|
{
"resource": ""
}
|
q240147
|
DBug.DBug
|
train
|
function DBug($var='',$die=false,$forceType='',$bCollapsed=false) {
if ($var === '') {
return;
}
//include js and css scripts
if(!defined('BDBUGINIT')) {
define("BDBUGINIT", TRUE);
$this->initJSandCSS();
}
$arrAccept=array("array","object","xml"); //array of variable types that can be "forced"
$this->bCollapsed = $bCollapsed;
if(in_array($forceType,$arrAccept))
$this->{"varIs".ucfirst($forceType)}($var);
else
$this->checkType($var);
if ($die) {
die();
}
}
|
php
|
{
"resource": ""
}
|
q240148
|
DBug.varIsXmlResource
|
train
|
private function varIsXmlResource($var) {
$xml_parser=xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
xml_set_element_handler($xml_parser,array(&$this,"xmlStartElement"),array(&$this,"xmlEndElement"));
xml_set_character_data_handler($xml_parser,array(&$this,"xmlCharacterData"));
xml_set_default_handler($xml_parser,array(&$this,"xmlDefaultHandler"));
$this->makeTableHeader("xml","xml document",2);
$this->makeTDHeader("xml","xmlRoot");
//attempt to open xml file
$bFile=(!($fp=@fopen($var,"r"))) ? false : true;
//read xml file
if($bFile) {
while($data=str_replace("\n","",fread($fp,4096)))
$this->xmlParse($xml_parser,$data,feof($fp));
}
//if xml is not a file, attempt to read it as a string
else {
if(!is_string($var)) {
echo $this->error("xml").$this->closeTDRow()."</table>\n";
return;
}
$data=$var;
$this->xmlParse($xml_parser,$data,1);
}
echo $this->closeTDRow()."</table>\n";
}
|
php
|
{
"resource": ""
}
|
q240149
|
Vector3D.scalarTripleProduct
|
train
|
public function scalarTripleProduct(Vector3D $second, Vector3D $third) : float
{
return $this->dotProduct($second->crossProduct($third));
}
|
php
|
{
"resource": ""
}
|
q240150
|
Vector3D.vectorTripleProduct
|
train
|
public function vectorTripleProduct(Vector3D $second, Vector3D $third) : Vector3D
{
return $this->crossProduct($second->crossProduct($third));
}
|
php
|
{
"resource": ""
}
|
q240151
|
FileModel.readData
|
train
|
private function readData()
{
switch ($this->fileType) {
case self::TYPE_JSON :
$data = json_decode(file_get_contents($this->readPath), true);
break;
default : $data = require $this->readPath;
}
return $data;
}
|
php
|
{
"resource": ""
}
|
q240152
|
FileModel.get
|
train
|
public function get($key)
{
$key = is_array($key) ? $key : [$key];
$config = $this->data;
while ($key) {
$k = array_shift($key);
$config = isset($config[$k]) ? $config[$k] : [];
}
return $config;
}
|
php
|
{
"resource": ""
}
|
q240153
|
FileModel.remove
|
train
|
public function remove($key)
{
$key = is_array($key) ? $key : [$key];
$config = $this->data;
$data = &$config;
while ($key) {
$k = array_shift($key);
if (!$key) {
unset($config[$k]);
break;
}
$config[$k] = isset($config[$k]) ? $config[$k] : [];
$config = &$config[$k];
}
$this->data = $data;
return $this->save();
}
|
php
|
{
"resource": ""
}
|
q240154
|
FileModel.put
|
train
|
public function put($data)
{
$this->data = array_merge($this->data, $data);
return $this->save();
}
|
php
|
{
"resource": ""
}
|
q240155
|
ProxyRequest.ResponseClass
|
train
|
public function ResponseClass($Class) {
$Code = (string)$this->ResponseStatus;
if (is_null($Code)) return FALSE;
if (strlen($Code) != strlen($Class)) return FALSE;
for ($i = 0; $i < strlen($Class); $i++)
if ($Class{$i} != 'x' && $Class{$i} != $Code{$i}) return FALSE;
return TRUE;
}
|
php
|
{
"resource": ""
}
|
q240156
|
ModerationController.CheckedComments
|
train
|
public function CheckedComments() {
$this->DeliveryType(DELIVERY_TYPE_BOOL);
$this->DeliveryMethod(DELIVERY_METHOD_JSON);
ModerationController::InformCheckedComments($this);
$this->Render();
}
|
php
|
{
"resource": ""
}
|
q240157
|
ModerationController.CheckedDiscussions
|
train
|
public function CheckedDiscussions() {
$this->DeliveryType(DELIVERY_TYPE_BOOL);
$this->DeliveryMethod(DELIVERY_METHOD_JSON);
ModerationController::InformCheckedDiscussions($this);
$this->Render();
}
|
php
|
{
"resource": ""
}
|
q240158
|
ModerationController.ClearCommentSelections
|
train
|
public function ClearCommentSelections($DiscussionID = '', $TransientKey = '') {
$Session = Gdn::Session();
if ($Session->ValidateTransientKey($TransientKey)) {
$CheckedComments = Gdn::UserModel()->GetAttribute($Session->User->UserID, 'CheckedComments', array());
unset($CheckedComments[$DiscussionID]);
Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedComments', $CheckedComments);
}
Redirect(GetIncomingValue('Target', '/discussions'));
}
|
php
|
{
"resource": ""
}
|
q240159
|
ModerationController.ClearDiscussionSelections
|
train
|
public function ClearDiscussionSelections($TransientKey = '') {
$Session = Gdn::Session();
if ($Session->ValidateTransientKey($TransientKey))
Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedDiscussions', FALSE);
Redirect(GetIncomingValue('Target', '/discussions'));
}
|
php
|
{
"resource": ""
}
|
q240160
|
Route.getCompiled
|
train
|
public function getCompiled()
{
if ($this->compiled === null) {
$regexp = "/^";
// Method(s)
$methodIdx = 0;
foreach($this->methods as $method) {
$regexp .= "(?:" . strtoupper($method) . ")";
if (($methodIdx + 1) < count($this->methods)) {
$regexp .= "|";
}
$methodIdx++;
}
// Separator
$regexp .= "~";
// Url
$regexp .= str_replace('/', '\/', $this->match);
$regexp .= "$/";
$this->compiled = $regexp;
}
return $this->compiled;
}
|
php
|
{
"resource": ""
}
|
q240161
|
Route.getValue
|
train
|
public function getValue($key, $default = null)
{
if (is_array($this->kwargs) && isset($this->kwargs[$key])) {
return $this->kwargs[$key];
}
return $default; // @codeCoverageIgnore
}
|
php
|
{
"resource": ""
}
|
q240162
|
Tooltips.addItem
|
train
|
public function addItem($id, $content, $title = false)
{
$this->tooltips[$id] = $this->newItem($id, $content, $title);
}
|
php
|
{
"resource": ""
}
|
q240163
|
JsonApiClient.call
|
train
|
protected function call(\LibX\Net\Rest\Request $request, \LibX\Net\Rest\Response $response)
{
// Make the call!
$this->client->execute($request, $response);
//print_r($request);
//print_r($response);
// Get info
$info = $response->getInfo();
// Get JSON response
$json = $response->getData();
// Decode JSON
$data = json_decode($json);
return $data;
}
|
php
|
{
"resource": ""
}
|
q240164
|
CommentsController.getDelete
|
train
|
public function getDelete($id = null)
{
// Get comment information
$comment = Comments::getCommentsRepository()->find($id);
if ($comment == null)
{
// Prepare the error message
$error = Lang::get('comments.comment.not_found');
// Redirect to the post management page
return Redirect::route('posts')->with('error', $error);
}
Base::Log('Comment (' . $comment->id . ') was deleted.');
// Delete the post
$comment->delete();
// Prepare the success message
$success = Lang::get('comments.comment.deleted');
// Redirect to the post management page
return Redirect::back()->with('success', $success);
}
|
php
|
{
"resource": ""
}
|
q240165
|
Model_Temporal.temporal_property
|
train
|
public static function temporal_property($key, $default = null)
{
$class = get_called_class();
// If already determined
if (!array_key_exists($class, static::$_temporal_cached))
{
static::temporal_properties();
}
return \Arr::get(static::$_temporal_cached[$class], $key, $default);
}
|
php
|
{
"resource": ""
}
|
q240166
|
Model_Temporal.find_revision
|
train
|
public static function find_revision($id, $timestamp = null, $relations = array())
{
if ($timestamp == null)
{
return parent::find($id);
}
$timestamp_start_name = static::temporal_property('start_column');
$timestamp_end_name = static::temporal_property('end_column');
// Select the next latest revision after the requested one then use that
// to get the revision before.
self::disable_primary_key_check();
$query = static::query()
->where('id', $id)
->where($timestamp_start_name, '<=', $timestamp)
->where($timestamp_end_name, '>', $timestamp);
self::enable_primary_key_check();
//Make sure the temporal stuff is activated
$query->set_temporal_properties($timestamp, $timestamp_end_name, $timestamp_start_name);
foreach ($relations as $relation)
{
$query->related($relation);
}
$query_result = $query->get_one();
// If the query did not return a result but null, then we cannot call
// set_lazy_timestamp on it without throwing errors
if ( $query_result !== null )
{
$query_result->set_lazy_timestamp($timestamp);
}
return $query_result;
}
|
php
|
{
"resource": ""
}
|
q240167
|
Model_Temporal.find_revisions_between
|
train
|
public static function find_revisions_between($id, $earliestTime = null, $latestTime = null)
{
$timestamp_start_name = static::temporal_property('start_column');
$max_timestamp = static::temporal_property('max_timestamp');
if ($earliestTime == null)
{
$earliestTime = 0;
}
if($latestTime == null)
{
$latestTime = $max_timestamp;
}
static::disable_primary_key_check();
//Select all revisions within the given range.
$query = static::query()
->where('id', $id)
->where($timestamp_start_name, '>=', $earliestTime)
->where($timestamp_start_name, '<=', $latestTime);
static::enable_primary_key_check();
$revisions = $query->get();
return $revisions;
}
|
php
|
{
"resource": ""
}
|
q240168
|
Model_Temporal.find
|
train
|
public static function find($id = null, array $options = array())
{
$timestamp_end_name = static::temporal_property('end_column');
$max_timestamp = static::temporal_property('max_timestamp');
switch ($id)
{
case 'all':
case 'first':
case 'last':
break;
default:
$id = (array) $id;
$count = 0;
foreach(static::getNonTimestampPks() as $key)
{
$options['where'][] = array($key, $id[$count]);
$count++;
}
break;
}
$options['where'][] = array($timestamp_end_name, $max_timestamp);
static::enable_id_only_primary_key();
$result = parent::find($id, $options);
static::disable_id_only_primary_key();
return $result;
}
|
php
|
{
"resource": ""
}
|
q240169
|
Model_Temporal.getNonTimestampPks
|
train
|
public static function getNonTimestampPks()
{
$timestamp_start_name = static::temporal_property('start_column');
$timestamp_end_name = static::temporal_property('end_column');
$pks = array();
foreach(parent::primary_key() as $key)
{
if ($key != $timestamp_start_name && $key != $timestamp_end_name)
{
$pks[] = $key;
}
}
return $pks;
}
|
php
|
{
"resource": ""
}
|
q240170
|
Model_Temporal.save
|
train
|
public function save($cascade = null, $use_transaction = false)
{
// Load temporal properties.
$timestamp_start_name = static::temporal_property('start_column');
$timestamp_end_name = static::temporal_property('end_column');
$mysql_timestamp = static::temporal_property('mysql_timestamp');
$max_timestamp = static::temporal_property('max_timestamp');
$current_timestamp = $mysql_timestamp ?
\Date::forge()->format('mysql') :
\Date::forge()->get_timestamp();
// If this is new then just call the parent and let everything happen as normal
if ($this->is_new())
{
static::disable_primary_key_check();
$this->{$timestamp_start_name} = $current_timestamp;
$this->{$timestamp_end_name} = $max_timestamp;
static::enable_primary_key_check();
// Make sure save will populate the PK
static::enable_id_only_primary_key();
$result = parent::save($cascade, $use_transaction);
static::disable_id_only_primary_key();
return $result;
}
// If this is an update then set a new PK, save and then insert a new row
else
{
// run the before save observers before checking the diff
$this->observe('before_save');
// then disable it so it doesn't get executed by parent::save()
$this->disable_event('before_save');
$diff = $this->get_diff();
if (count($diff[0]) > 0)
{
// Take a copy of this model
$revision = clone $this;
// Give that new model an end time of the current time after resetting back to the old data
$revision->set($this->_original);
self::disable_primary_key_check();
$revision->{$timestamp_end_name} = $current_timestamp;
self::enable_primary_key_check();
// Make sure relations stay the same
$revision->_original_relations = $this->_data_relations;
// save that, now we have our archive
self::enable_id_only_primary_key();
$revision_result = $revision->overwrite(false, $use_transaction);
self::disable_id_only_primary_key();
if ( ! $revision_result)
{
// If the revision did not save then stop the process so the user can do something.
return false;
}
// Now that the old data is saved update the current object so its end timestamp is now
self::disable_primary_key_check();
$this->{$timestamp_start_name} = $current_timestamp;
self::enable_primary_key_check();
$result = parent::save($cascade, $use_transaction);
}
else
{
// If nothing has changed call parent::save() to insure relations are saved too
$result = parent::save($cascade, $use_transaction);
}
// make sure the before save event is enabled again
$this->enable_event('before_save');
return $result;
}
}
|
php
|
{
"resource": ""
}
|
q240171
|
Model_Temporal.restore
|
train
|
public function restore()
{
$timestamp_end_name = static::temporal_property('end_column');
$max_timestamp = static::temporal_property('max_timestamp');
// check to see if there is a currently active row, if so then don't
// restore anything.
$activeRow = static::find('first', array(
'where' => array(
array('id', $this->id),
array($timestamp_end_name, $max_timestamp),
),
));
if(is_null($activeRow))
{
// No active row was found so we are ok to go and restore the this
// revision
$timestamp_start_name = static::temporal_property('start_column');
$mysql_timestamp = static::temporal_property('mysql_timestamp');
$max_timestamp = static::temporal_property('max_timestamp');
$current_timestamp = $mysql_timestamp ?
\Date::forge()->format('mysql') :
\Date::forge()->get_timestamp();
// Make sure this is saved as a new entry
$this->_is_new = true;
// Update timestamps
static::disable_primary_key_check();
$this->{$timestamp_start_name} = $current_timestamp;
$this->{$timestamp_end_name} = $max_timestamp;
// Save
$result = parent::save();
static::enable_primary_key_check();
return $result;
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240172
|
Model_Temporal.add_primary_keys_to_where
|
train
|
protected function add_primary_keys_to_where($query)
{
$timestamp_start_name = static::temporal_property('start_column');
$timestamp_end_name = static::temporal_property('end_column');
$primary_key = array(
'id',
$timestamp_start_name,
$timestamp_end_name,
);
foreach ($primary_key as $pk)
{
$query->where($pk, '=', $this->_original[$pk]);
}
}
|
php
|
{
"resource": ""
}
|
q240173
|
Model_Temporal.primary_key
|
train
|
public static function primary_key()
{
$id_only = static::get_primary_key_id_only_status();
$pk_status = static::get_primary_key_status();
if ($id_only)
{
return static::getNonTimestampPks();
}
if ($pk_status && ! $id_only)
{
return static::$_primary_key;
}
return array();
}
|
php
|
{
"resource": ""
}
|
q240174
|
Option.create
|
train
|
public static function create($value, $empty = null)
{
// Option is a callable class!
$value = ( ! $value instanceof self) && is_callable($value) ? $value() : $value;
if (is_callable($empty)) {
$option = $empty($value) ? self::$none : new Some($value);
} else if ($value === $empty) {
$option = self::$none;
} else if ($value instanceof self) {
$option = $value;
} else {
$option = new Some($value);
}
return $option;
}
|
php
|
{
"resource": ""
}
|
q240175
|
PrimaryRelation.getSiblings
|
train
|
public function getSiblings($role, $primaryOnly = false)
{
$primaryField = $this->getPrimaryField($role);
$parentObject = $this->owner->parentObject;
$childObject = $this->owner->childObject;
if (empty($childObject)) {
return [];
}
$relationFields = [];
if ($primaryOnly) {
$relationFields['{{%alias%}}.[[' . $primaryField . ']]'] = 1;
}
return $childObject->siblingRelationQuery($parentObject, ['where' => $relationFields], ['disableAccess' => true])->all();
}
|
php
|
{
"resource": ""
}
|
q240176
|
PrimaryRelation.setPrimary
|
train
|
public function setPrimary($role)
{
if (!$this->handlePrimary($role)) {
return false;
}
$primaryField = $this->getPrimaryField($role);
$primarySiblings = $this->getSiblings($role, true);
foreach ($primarySiblings as $sibling) {
$sibling->{$primaryField} = 0;
if (!$sibling->save()) {
return false;
}
}
$this->owner->{$primaryField} = 1;
return $this->owner->save();
}
|
php
|
{
"resource": ""
}
|
q240177
|
PrimaryRelation.isPrimary
|
train
|
public function isPrimary($role)
{
if (!$this->handlePrimary($role)) {
return false;
}
$primaryField = $this->getPrimaryField($role);
return !empty($this->owner->{$primaryField});
}
|
php
|
{
"resource": ""
}
|
q240178
|
ServiceProvider.register
|
train
|
public function register()
{
$container = $this->container;
$console = new Console('EncorePHP', $container::VERSION);
$this->container->bind('console', $console);
if ($this->container->bound('error')) {
$this->container['error']->setDisplayer(new ConsoleDisplayer($console));
}
}
|
php
|
{
"resource": ""
}
|
q240179
|
ServiceProvider.boot
|
train
|
public function boot()
{
// Loop the providers and register commands
$providers = $this->container->providers(false);
foreach ($providers as $provider) {
if (method_exists($provider, 'commands')) {
$this->registerCommands($provider->commands());
}
}
}
|
php
|
{
"resource": ""
}
|
q240180
|
ServiceProvider.registerCommands
|
train
|
protected function registerCommands(array $commands)
{
foreach ($commands as $command) {
if ( ! $command instanceof SymfonyCommand) {
$command = $this->container[$command];
}
$this->container['console']->add($command);
}
}
|
php
|
{
"resource": ""
}
|
q240181
|
Mutable.add
|
train
|
public function add(array $params) {
foreach ($params as $key => $value) {
$this->set($key, $value);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240182
|
Mutable.get
|
train
|
public function get($key, $default = null) {
if (strpos($key, '.') === false) {
$value = isset($this->_data[$key]) ? $this->_data[$key] : null;
} else {
$value = Hash::get($this->_data, $key);
}
if ($value === null) {
return $default;
}
return $value;
}
|
php
|
{
"resource": ""
}
|
q240183
|
Mutable.remove
|
train
|
public function remove($key) {
$this->_data = Hash::remove($this->_data, $key);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240184
|
Mutable.set
|
train
|
public function set($key, $value = null) {
if (strpos($key, '.') === false) {
$this->_data[$key] = $value;
} else {
$this->_data = Hash::set($this->_data, $key, $value);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240185
|
Kernel.boot
|
train
|
public function boot(Application $application, InputInterface $input, $output)
{
if (true === $this->booted) {
return;
}
$this->application = $application;
$this->input = $input;
$this->output = $output;
$this->initializeContainer();
$this->booted = true;
}
|
php
|
{
"resource": ""
}
|
q240186
|
Kernel.initializeContainer
|
train
|
protected function initializeContainer()
{
$this->container = $this->buildContainer();
// Load all the default services
$this->getContainerLoader($this->container)->load('services.xml');
$this->container->compile();
}
|
php
|
{
"resource": ""
}
|
q240187
|
Kernel.buildContainer
|
train
|
protected function buildContainer()
{
$container = new ContainerBuilder(new ParameterBag($this->getContainerParameters()));
$container->setResourceTracking(true);
$container->set('kernel', $this);
$container->set('application', $this->application);
// Load the build file
$this->getContainerLoader($container)->load($this->getBuildFile(), self::TYPE_BUILD_FILE);
// Load the properties file
$file = $this->getPropertiesFile();
if ($file) {
$this->getContainerLoader($container)->load($file, self::TYPE_PROPERTIES_FILE);
}
return $container;
}
|
php
|
{
"resource": ""
}
|
q240188
|
Kernel.getEnvironmentVariables
|
train
|
protected function getEnvironmentVariables()
{
$env = array();
foreach ($_SERVER as $name => $val) {
if (is_array($val) || !in_array(strtolower($name), $this->getEnvironmentVariablesThatICareAbout())) {
// In the future, this could be supported
continue;
}
$env['env.'.$name] = $val;
}
return $env;
}
|
php
|
{
"resource": ""
}
|
q240189
|
Kernel.getBuildFile
|
train
|
protected function getBuildFile()
{
$buildfile = getcwd().'/build.yml';
if (true === $this->input->hasParameterOption('--buildfile')) {
$buildfile = realpath($this->input->getParameterOption('--buildfile'));
}
if (is_file($buildfile) && is_readable($buildfile)) {
return $buildfile;
}
throw new \Exception(
sprintf('Could not find build file "%s"', $buildfile)
);
}
|
php
|
{
"resource": ""
}
|
q240190
|
Kernel.getPropertiesFile
|
train
|
protected function getPropertiesFile()
{
$propertyfile = getcwd().'/build.properties';
if (true === $this->input->hasParameterOption('--propertyfile')) {
$propertyfile = realpath($this->input->getParameterOption('--propertyfile'));
}
if (is_file($propertyfile) && is_readable($propertyfile)) {
return $propertyfile;
}
if (true === $this->input->hasParameterOption('--propertyfile')) {
throw new \Exception(
sprintf(
'Could not find properties file "%s"',
$this->input->getParameterOption('--propertyfile')
)
);
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240191
|
Stream.getMetaDataValue
|
train
|
public function getMetaDataValue($key) {
return (isset($this->meta[$key]) ? $this->meta[$key] : null);
}
|
php
|
{
"resource": ""
}
|
q240192
|
Stream.getContent
|
train
|
public function getContent() {
if($this->isSeekable())
$this->rewind();
if (!$this->isReadable() || ($contents = stream_get_contents($this->stream)) === false) {
throw new \RuntimeException('Could not get contents of not readable stream');
}
return $contents;
}
|
php
|
{
"resource": ""
}
|
q240193
|
Stream.read
|
train
|
public function read($length = null) {
if(is_null($length))
$length = $this->getSize(0);
if (!$this->isReadable() || ($data = fread($this->stream, $length)) === false) {
throw new \RuntimeException('Could not read from not readable stream');
}
return $data;
}
|
php
|
{
"resource": ""
}
|
q240194
|
Stream.write
|
train
|
public function write($string) {
if (!$this->isWritable() || ($written = fwrite($this->stream, $string)) === false) {
throw new \RuntimeException('Could not write in a not writable stream');
}
return $written;
}
|
php
|
{
"resource": ""
}
|
q240195
|
Registry.getByClassname
|
train
|
public function getByClassname(string $classname)
{
foreach ($this->container as $value) {
if (is_object($value) && $value instanceof $classname) {
return $value;
}
}
return null;
}
|
php
|
{
"resource": ""
}
|
q240196
|
Connection.connect
|
train
|
public function connect() {
$count = 0;
do {
$count += 1;
$this->Resource = pg_connect($this->getConnectionString());
if ($this->Resource !== false) {
return true;
}
} while ($count < $this->getConnectTries());
throw new TriesOverConnectException();
}
|
php
|
{
"resource": ""
}
|
q240197
|
Connection.getConnectionString
|
train
|
private function getConnectionString() {
$parameters = array(
'host=' . $this->getHost(),
'connect_timeout=' . $this->getConnectTimeout(),
'user=' . $this->getUserName(),
);
$this->hasPort() && $parameters[] = 'port=' . $this->getPort();
$this->hasPassword() && $parameters[] = 'password=' . $this->getPassword();
$this->hasDatabase() && $parameters[] = 'dbname=' . $this->getDatabase();
return implode(' ', $parameters);
}
|
php
|
{
"resource": ""
}
|
q240198
|
Preg.replace_callback
|
train
|
public static function replace_callback ($subject, $pattern, $callback, $limit = -1) {
return preg_replace_callback(self::set_u_modifier($pattern, TRUE), $callback, $subject, $limit);
}
|
php
|
{
"resource": ""
}
|
q240199
|
SkillPartQuery.filterByPartId
|
train
|
public function filterByPartId($partId = null, $comparison = null)
{
if (is_array($partId)) {
$useMinMax = false;
if (isset($partId['min'])) {
$this->addUsingAlias(SkillPartTableMap::COL_PART_ID, $partId['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($partId['max'])) {
$this->addUsingAlias(SkillPartTableMap::COL_PART_ID, $partId['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(SkillPartTableMap::COL_PART_ID, $partId, $comparison);
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.