repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
GrupaZero/cms | src/Gzero/Cms/BlockFinder.php | BlockFinder.handleStaticPageCase | protected function handleStaticPageCase($path, $filter)
{
if (isset($filter['paths'][$path])) {
return array_keys($filter['paths'][$path] + $filter['excluded'], true, true);
}
return array_keys($filter['excluded'], true, true);
} | php | protected function handleStaticPageCase($path, $filter)
{
if (isset($filter['paths'][$path])) {
return array_keys($filter['paths'][$path] + $filter['excluded'], true, true);
}
return array_keys($filter['excluded'], true, true);
} | [
"protected",
"function",
"handleStaticPageCase",
"(",
"$",
"path",
",",
"$",
"filter",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"filter",
"[",
"'paths'",
"]",
"[",
"$",
"path",
"]",
")",
")",
"{",
"return",
"array_keys",
"(",
"$",
"filter",
"[",
"'pat... | It checks which blocks should be displayed for specific static page
@param string $path Static page named route
@param array $filter Array with all filters
@return array | [
"It",
"checks",
"which",
"blocks",
"should",
"be",
"displayed",
"for",
"specific",
"static",
"page"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/BlockFinder.php#L144-L150 | train |
GrupaZero/cms | src/Gzero/Cms/BlockFinder.php | BlockFinder.extractFilter | protected function extractFilter(Block $block, array &$filter, array &$excluded)
{
if (isset($block->filter['+'])) {
foreach ($block->filter['+'] as $filterValue) {
if (isset($filter[$filterValue])) {
$filter[$filterValue][$block->id] = true;
} else {
$filter[$filterValue] = [$block->id => true];
}
}
}
if (isset($block->filter['-'])) {
foreach ($block->filter['-'] as $filterValue) {
if (isset($filter[$filterValue])) {
$filter[$filterValue][$block->id] = false;
} else {
$filter[$filterValue] = [$block->id => false];
}
// By default block with - should display on all sited except those from filter
$excluded[$block->id] = true;
}
}
} | php | protected function extractFilter(Block $block, array &$filter, array &$excluded)
{
if (isset($block->filter['+'])) {
foreach ($block->filter['+'] as $filterValue) {
if (isset($filter[$filterValue])) {
$filter[$filterValue][$block->id] = true;
} else {
$filter[$filterValue] = [$block->id => true];
}
}
}
if (isset($block->filter['-'])) {
foreach ($block->filter['-'] as $filterValue) {
if (isset($filter[$filterValue])) {
$filter[$filterValue][$block->id] = false;
} else {
$filter[$filterValue] = [$block->id => false];
}
// By default block with - should display on all sited except those from filter
$excluded[$block->id] = true;
}
}
} | [
"protected",
"function",
"extractFilter",
"(",
"Block",
"$",
"block",
",",
"array",
"&",
"$",
"filter",
",",
"array",
"&",
"$",
"excluded",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"block",
"->",
"filter",
"[",
"'+'",
"]",
")",
")",
"{",
"foreach",
... | It extracts filter property from single block
@param Block $block Block instance
@param array $filter Filter array
@param array $excluded Excluded array
@return void | [
"It",
"extracts",
"filter",
"property",
"from",
"single",
"block"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/BlockFinder.php#L161-L183 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.getResizedImageSize | static public function getResizedImageSize($file, $target=25){
list($width, $height, , ) = getimagesize($file);
$max = max($width, $height);
$rapp = $target / $max;
$width = intval($rapp * $width);
$height = intval($rapp * $height);
return array($width, $height);
} | php | static public function getResizedImageSize($file, $target=25){
list($width, $height, , ) = getimagesize($file);
$max = max($width, $height);
$rapp = $target / $max;
$width = intval($rapp * $width);
$height = intval($rapp * $height);
return array($width, $height);
} | [
"static",
"public",
"function",
"getResizedImageSize",
"(",
"$",
"file",
",",
"$",
"target",
"=",
"25",
")",
"{",
"list",
"(",
"$",
"width",
",",
"$",
"height",
",",
",",
")",
"=",
"getimagesize",
"(",
"$",
"file",
")",
";",
"$",
"max",
"=",
"max",... | Get width and heigth of an image resized in order fit a target size.
@param string $file The image to resize
@param int $target The final max width/height
@return array array of ($width, $height). One of them must be $target | [
"Get",
"width",
"and",
"heigth",
"of",
"an",
"image",
"resized",
"in",
"order",
"fit",
"a",
"target",
"size",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L75-L82 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.doesTableExist | public static function doesTableExist($table) {
try {
fw\Database::prepare("SELECT 1 FROM {$table}")->fetchOne();
return true;
} catch (\PDOException $ex) {
return false;
}
} | php | public static function doesTableExist($table) {
try {
fw\Database::prepare("SELECT 1 FROM {$table}")->fetchOne();
return true;
} catch (\PDOException $ex) {
return false;
}
} | [
"public",
"static",
"function",
"doesTableExist",
"(",
"$",
"table",
")",
"{",
"try",
"{",
"fw",
"\\",
"Database",
"::",
"prepare",
"(",
"\"SELECT 1 FROM {$table}\"",
")",
"->",
"fetchOne",
"(",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"\\",
"... | Checks if a table exist in the DB schema
@param string $table Name of the table to look for
@return boolean Does the table exist | [
"Checks",
"if",
"a",
"table",
"exist",
"in",
"the",
"DB",
"schema"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L91-L98 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.generateRandomToken | public static function generateRandomToken($length=32) {
$chars = str_split('abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
$len_chars = count($chars);
$token = '';
for ($i = 0; $i < $length; $i++)
$token .= $chars[ mt_rand(0, $len_chars - 1) ];
# Number of 32 char chunks
$chunks = ceil( strlen($token) / 32 );
$md5token = '';
# Run each chunk through md5
for ( $i=1; $i<=$chunks; $i++ )
$md5token .= md5( substr($token, $i * 32 - 32, 32) );
# Trim the token
return substr($md5token, 0, $length);
} | php | public static function generateRandomToken($length=32) {
$chars = str_split('abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
$len_chars = count($chars);
$token = '';
for ($i = 0; $i < $length; $i++)
$token .= $chars[ mt_rand(0, $len_chars - 1) ];
# Number of 32 char chunks
$chunks = ceil( strlen($token) / 32 );
$md5token = '';
# Run each chunk through md5
for ( $i=1; $i<=$chunks; $i++ )
$md5token .= md5( substr($token, $i * 32 - 32, 32) );
# Trim the token
return substr($md5token, 0, $length);
} | [
"public",
"static",
"function",
"generateRandomToken",
"(",
"$",
"length",
"=",
"32",
")",
"{",
"$",
"chars",
"=",
"str_split",
"(",
"'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'",
")",
";",
"$",
"len_chars",
"=",
"count",
"(",
"$",
"chars",
")"... | Returns a randomy generated token of a given size
@param int $length Length of the token, default to 32
@return string Random token | [
"Returns",
"a",
"randomy",
"generated",
"token",
"of",
"a",
"given",
"size"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L106-L124 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.getBase64EncryptionKey | protected static function getBase64EncryptionKey() {
$key = 'STANDARDKEYIFNOSERVER';
if(!empty(Filter::server('SERVER_NAME')) && !empty(Filter::server('SERVER_SOFTWARE')))
$key = md5(Filter::server('SERVER_NAME').Filter::server('SERVER_SOFTWARE'));
return $key;
} | php | protected static function getBase64EncryptionKey() {
$key = 'STANDARDKEYIFNOSERVER';
if(!empty(Filter::server('SERVER_NAME')) && !empty(Filter::server('SERVER_SOFTWARE')))
$key = md5(Filter::server('SERVER_NAME').Filter::server('SERVER_SOFTWARE'));
return $key;
} | [
"protected",
"static",
"function",
"getBase64EncryptionKey",
"(",
")",
"{",
"$",
"key",
"=",
"'STANDARDKEYIFNOSERVER'",
";",
"if",
"(",
"!",
"empty",
"(",
"Filter",
"::",
"server",
"(",
"'SERVER_NAME'",
")",
")",
"&&",
"!",
"empty",
"(",
"Filter",
"::",
"s... | Generate the key used by the encryption to safe base64 functions.
@return string Encryption key | [
"Generate",
"the",
"key",
"used",
"by",
"the",
"encryption",
"to",
"safe",
"base64",
"functions",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L131-L137 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.decryptFromSafeBase64 | public static function decryptFromSafeBase64($encrypted){
$encrypted = str_replace('-', '+', $encrypted);
$encrypted = str_replace('_', '/', $encrypted);
$encrypted = str_replace('*', '=', $encrypted);
$encrypted = base64_decode($encrypted);
if($encrypted === false)
throw new \InvalidArgumentException('The encrypted value is not in correct base64 format.');
if (mb_strlen($encrypted, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES))
throw new \InvalidArgumentException('The encrypted value does not contain enough characters for the key.');
$nonce = mb_substr($encrypted, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($encrypted, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, self::getBase64EncryptionKey());
if($decrypted === false) {
throw new \InvalidArgumentException('The message has been tampered with in transit.');
}
//sodium_memzero($encrypted); // Requires PHP 7.2
return $decrypted;
} | php | public static function decryptFromSafeBase64($encrypted){
$encrypted = str_replace('-', '+', $encrypted);
$encrypted = str_replace('_', '/', $encrypted);
$encrypted = str_replace('*', '=', $encrypted);
$encrypted = base64_decode($encrypted);
if($encrypted === false)
throw new \InvalidArgumentException('The encrypted value is not in correct base64 format.');
if (mb_strlen($encrypted, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES))
throw new \InvalidArgumentException('The encrypted value does not contain enough characters for the key.');
$nonce = mb_substr($encrypted, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($encrypted, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, self::getBase64EncryptionKey());
if($decrypted === false) {
throw new \InvalidArgumentException('The message has been tampered with in transit.');
}
//sodium_memzero($encrypted); // Requires PHP 7.2
return $decrypted;
} | [
"public",
"static",
"function",
"decryptFromSafeBase64",
"(",
"$",
"encrypted",
")",
"{",
"$",
"encrypted",
"=",
"str_replace",
"(",
"'-'",
",",
"'+'",
",",
"$",
"encrypted",
")",
";",
"$",
"encrypted",
"=",
"str_replace",
"(",
"'_'",
",",
"'/'",
",",
"$... | Decode and encrypt a text from base64 compatible with URL use
@param string $encrypted Text to decrypt
@return string Decrypted text | [
"Decode",
"and",
"encrypt",
"a",
"text",
"from",
"base64",
"compatible",
"with",
"URL",
"use"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L166-L189 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.isValidPath | public static function isValidPath($filename, $acceptfolder = FALSE) {
if(strpbrk($filename, $acceptfolder ? '?%*:|"<>' : '\\/?%*:|"<>') === FALSE) return true;
return false;
} | php | public static function isValidPath($filename, $acceptfolder = FALSE) {
if(strpbrk($filename, $acceptfolder ? '?%*:|"<>' : '\\/?%*:|"<>') === FALSE) return true;
return false;
} | [
"public",
"static",
"function",
"isValidPath",
"(",
"$",
"filename",
",",
"$",
"acceptfolder",
"=",
"FALSE",
")",
"{",
"if",
"(",
"strpbrk",
"(",
"$",
"filename",
",",
"$",
"acceptfolder",
"?",
"'?%*:|\"<>'",
":",
"'\\\\/?%*:|\"<>'",
")",
"===",
"FALSE",
"... | Check whether a path is under a valid form.
@param string $filename Filename path to check
@param boolean $acceptfolder Should folders be accepted?
@return boolean True if path valid | [
"Check",
"whether",
"a",
"path",
"is",
"under",
"a",
"valid",
"form",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L224-L227 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.getCalendarShortMonths | public static function getCalendarShortMonths($calendarId = 0) {
if(!isset(self::$calendarShortMonths[$calendarId])) {
$calendar_info = cal_info($calendarId);
self::$calendarShortMonths[$calendarId] = $calendar_info['abbrevmonths'];
}
return self::$calendarShortMonths[$calendarId];
} | php | public static function getCalendarShortMonths($calendarId = 0) {
if(!isset(self::$calendarShortMonths[$calendarId])) {
$calendar_info = cal_info($calendarId);
self::$calendarShortMonths[$calendarId] = $calendar_info['abbrevmonths'];
}
return self::$calendarShortMonths[$calendarId];
} | [
"public",
"static",
"function",
"getCalendarShortMonths",
"(",
"$",
"calendarId",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"calendarShortMonths",
"[",
"$",
"calendarId",
"]",
")",
")",
"{",
"$",
"calendar_info",
"=",
"cal_info",... | Return short names for the months of the specific calendar.
@see \cal_info()
@param integer $calendarId Calendar ID (according to PHP cal_info)
@return array Array of month short names | [
"Return",
"short",
"names",
"for",
"the",
"months",
"of",
"the",
"specific",
"calendar",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L236-L242 | train |
jon48/webtrees-lib | src/Webtrees/Functions/Functions.php | Functions.isImageTypeSupported | public static function isImageTypeSupported($reqtype) {
$supportByGD = array('jpg'=>'jpeg', 'jpeg'=>'jpeg', 'gif'=>'gif', 'png'=>'png');
$reqtype = strtolower($reqtype);
if (empty($supportByGD[$reqtype])) {
return false;
}
$type = $supportByGD[$reqtype];
if (function_exists('imagecreatefrom'.$type) && function_exists('image'.$type)) {
return $type;
}
return false;
} | php | public static function isImageTypeSupported($reqtype) {
$supportByGD = array('jpg'=>'jpeg', 'jpeg'=>'jpeg', 'gif'=>'gif', 'png'=>'png');
$reqtype = strtolower($reqtype);
if (empty($supportByGD[$reqtype])) {
return false;
}
$type = $supportByGD[$reqtype];
if (function_exists('imagecreatefrom'.$type) && function_exists('image'.$type)) {
return $type;
}
return false;
} | [
"public",
"static",
"function",
"isImageTypeSupported",
"(",
"$",
"reqtype",
")",
"{",
"$",
"supportByGD",
"=",
"array",
"(",
"'jpg'",
"=>",
"'jpeg'",
",",
"'jpeg'",
"=>",
"'jpeg'",
",",
"'gif'",
"=>",
"'gif'",
",",
"'png'",
"=>",
"'png'",
")",
";",
"$",... | Returns whether the image type is supported by the system, and if so, return the standardised type
@param string $reqtype Extension to test
@return boolean|string Is supported? | [
"Returns",
"whether",
"the",
"image",
"type",
"is",
"supported",
"by",
"the",
"system",
"and",
"if",
"so",
"return",
"the",
"standardised",
"type"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/Functions.php#L263-L278 | train |
GrupaZero/cms | src/Gzero/Cms/Http/Resources/Content.php | Content.buildPath | private function buildPath($path)
{
$result = [];
foreach (explode('/', $path) as $value) {
if (!empty($value)) {
$result[] = (int) $value;
}
}
return $result;
} | php | private function buildPath($path)
{
$result = [];
foreach (explode('/', $path) as $value) {
if (!empty($value)) {
$result[] = (int) $value;
}
}
return $result;
} | [
"private",
"function",
"buildPath",
"(",
"$",
"path",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",... | Returns array of path ids as integers
@param Content $path path to explode
@return array extracted path | [
"Returns",
"array",
"of",
"path",
"ids",
"as",
"integers"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Http/Resources/Content.php#L151-L160 | train |
jon48/webtrees-lib | src/Webtrees/Module/AdminTasks/Model/AbstractTask.php | AbstractTask.setParameters | public function setParameters($is_enabled, \DateTime $last_updated, $last_result, $frequency, $nb_occur, $is_running){
$this->is_enabled = $is_enabled;
$this->last_updated = $last_updated;
$this->last_result = $last_result;
$this->frequency = $frequency;
$this->nb_occurrences = $nb_occur;
$this->is_running = $is_running;
} | php | public function setParameters($is_enabled, \DateTime $last_updated, $last_result, $frequency, $nb_occur, $is_running){
$this->is_enabled = $is_enabled;
$this->last_updated = $last_updated;
$this->last_result = $last_result;
$this->frequency = $frequency;
$this->nb_occurrences = $nb_occur;
$this->is_running = $is_running;
} | [
"public",
"function",
"setParameters",
"(",
"$",
"is_enabled",
",",
"\\",
"DateTime",
"$",
"last_updated",
",",
"$",
"last_result",
",",
"$",
"frequency",
",",
"$",
"nb_occur",
",",
"$",
"is_running",
")",
"{",
"$",
"this",
"->",
"is_enabled",
"=",
"$",
... | Set parameters of the Task
@param bool $is_enabled Status of the task
@param \DateTime $lastupdated Time of the last task run
@param bool $last_result Result of the last run, true for success, false for failure
@param int $frequency Frequency of execution in minutes
@param int $nb_occur Number of remaining occurrences, 0 for tasks not limited
@param bool $is_running Indicates if the task is currently running | [
"Set",
"parameters",
"of",
"the",
"Task"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/AdminTasks/Model/AbstractTask.php#L118-L125 | train |
jon48/webtrees-lib | src/Webtrees/Module/AdminTasks/Model/AbstractTask.php | AbstractTask.execute | public function execute(){
if($this->last_updated->add(new \DateInterval('PT'.self::TASK_TIME_OUT.'S')) < new \DateTime())
$this->is_running = false;
if(!$this->is_running){
$this->last_result = false;
$this->is_running = true;
$this->save();
Log::addDebugLog('Start execution of Admin task: '.$this->getTitle());
$this->last_result = $this->executeSteps();
if($this->last_result){
$this->last_updated = new \DateTime();
if($this->nb_occurrences > 0){
$this->nb_occurrences--;
if($this->nb_occurrences == 0) $this->is_enabled = false;
}
}
$this->is_running = false;
$this->save();
Log::addDebugLog('Execution completed for Admin task: '.$this->getTitle().' - '.($this->last_result ? 'Success' : 'Failure'));
}
} | php | public function execute(){
if($this->last_updated->add(new \DateInterval('PT'.self::TASK_TIME_OUT.'S')) < new \DateTime())
$this->is_running = false;
if(!$this->is_running){
$this->last_result = false;
$this->is_running = true;
$this->save();
Log::addDebugLog('Start execution of Admin task: '.$this->getTitle());
$this->last_result = $this->executeSteps();
if($this->last_result){
$this->last_updated = new \DateTime();
if($this->nb_occurrences > 0){
$this->nb_occurrences--;
if($this->nb_occurrences == 0) $this->is_enabled = false;
}
}
$this->is_running = false;
$this->save();
Log::addDebugLog('Execution completed for Admin task: '.$this->getTitle().' - '.($this->last_result ? 'Success' : 'Failure'));
}
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"last_updated",
"->",
"add",
"(",
"new",
"\\",
"DateInterval",
"(",
"'PT'",
".",
"self",
"::",
"TASK_TIME_OUT",
".",
"'S'",
")",
")",
"<",
"new",
"\\",
"DateTime",
"(",
")"... | Execute the task, default skeleton | [
"Execute",
"the",
"task",
"default",
"skeleton"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/AdminTasks/Model/AbstractTask.php#L246-L269 | train |
Rareloop/primer-core | src/Primer/Primer.php | Primer.start | public static function start($options)
{
ErrorHandler::register();
ExceptionHandler::register();
// Default params
$defaultTemplateClass = 'Rareloop\Primer\TemplateEngine\Handlebars\Template';
// Work out what we were passed as an argument
if (is_string($options)) {
// Backwards compatibility
Primer::$BASE_PATH = realpath($options);
Primer::$PATTERN_PATH = Primer::$BASE_PATH . '/patterns';
Primer::$PATTERN_PATH = Primer::$BASE_PATH . '/views';
Primer::$CACHE_PATH = Primer::$BASE_PATH . '/cache';
Primer::$TEMPLATE_CLASS = $defaultTemplateClass;
Primer::$WRAP_TEMPLATES = true;
} else {
// New more expressive function params
if (!isset($options['basePath'])) {
throw new Exception('No `basePath` param passed to Primer::start()');
}
Primer::$BASE_PATH = realpath($options['basePath']);
Primer::$PATTERN_PATH = isset($options['patternPath']) ? realpath($options['patternPath']) : Primer::$BASE_PATH . '/patterns';
Primer::$VIEW_PATH = isset($options['viewPath']) ? realpath($options['viewPath']) : Primer::$BASE_PATH . '/views';
Primer::$CACHE_PATH = isset($options['cachePath']) ? realpath($options['cachePath']) : Primer::$BASE_PATH . '/cache';
Primer::$TEMPLATE_CLASS = isset($options['templateClass']) ? $options['templateClass'] : $defaultTemplateClass;
Primer::$WRAP_TEMPLATES = isset($options['wrapTemplate']) ? $options['wrapTemplate'] : true;
}
// Attempt to load all `init.php` files. We shouldn't really have to do this here but currently
// include functions don't actually load patterns so its hard to track when things are loaded
// TODO: Move everything through Pattern constructors
$finder = new Finder();
$initFiles = $finder->in(Primer::$PATTERN_PATH)->files()->name('init.php');
foreach ($initFiles as $file) {
include_once($file);
}
return Primer::instance();
} | php | public static function start($options)
{
ErrorHandler::register();
ExceptionHandler::register();
// Default params
$defaultTemplateClass = 'Rareloop\Primer\TemplateEngine\Handlebars\Template';
// Work out what we were passed as an argument
if (is_string($options)) {
// Backwards compatibility
Primer::$BASE_PATH = realpath($options);
Primer::$PATTERN_PATH = Primer::$BASE_PATH . '/patterns';
Primer::$PATTERN_PATH = Primer::$BASE_PATH . '/views';
Primer::$CACHE_PATH = Primer::$BASE_PATH . '/cache';
Primer::$TEMPLATE_CLASS = $defaultTemplateClass;
Primer::$WRAP_TEMPLATES = true;
} else {
// New more expressive function params
if (!isset($options['basePath'])) {
throw new Exception('No `basePath` param passed to Primer::start()');
}
Primer::$BASE_PATH = realpath($options['basePath']);
Primer::$PATTERN_PATH = isset($options['patternPath']) ? realpath($options['patternPath']) : Primer::$BASE_PATH . '/patterns';
Primer::$VIEW_PATH = isset($options['viewPath']) ? realpath($options['viewPath']) : Primer::$BASE_PATH . '/views';
Primer::$CACHE_PATH = isset($options['cachePath']) ? realpath($options['cachePath']) : Primer::$BASE_PATH . '/cache';
Primer::$TEMPLATE_CLASS = isset($options['templateClass']) ? $options['templateClass'] : $defaultTemplateClass;
Primer::$WRAP_TEMPLATES = isset($options['wrapTemplate']) ? $options['wrapTemplate'] : true;
}
// Attempt to load all `init.php` files. We shouldn't really have to do this here but currently
// include functions don't actually load patterns so its hard to track when things are loaded
// TODO: Move everything through Pattern constructors
$finder = new Finder();
$initFiles = $finder->in(Primer::$PATTERN_PATH)->files()->name('init.php');
foreach ($initFiles as $file) {
include_once($file);
}
return Primer::instance();
} | [
"public",
"static",
"function",
"start",
"(",
"$",
"options",
")",
"{",
"ErrorHandler",
"::",
"register",
"(",
")",
";",
"ExceptionHandler",
"::",
"register",
"(",
")",
";",
"// Default params",
"$",
"defaultTemplateClass",
"=",
"'Rareloop\\Primer\\TemplateEngine\\H... | Bootstrap the Primer singleton
For backwards compatibility the first param is either a string to the BASE_PATH
or it can be an assoc array
array(
'basePath' => '',
'patternPath' => '', // Defaults to PRIMER::$BASE_PATH . '/pattern'
'cachePath' => '', // Defaults to PRIMER::$BASE_PATH . '/cache'
'templateEngine' => '' // Defaults to 'Rareloop\Primer\TemplateEngine\Handlebars\Template'
)
@param String|Array $options
@return Rareloop\Primer\Primer | [
"Bootstrap",
"the",
"Primer",
"singleton"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Primer.php#L100-L144 | train |
Rareloop/primer-core | src/Primer/Primer.php | Primer.getTemplate | public function getTemplate($id)
{
// Default system wide template wrapping config
$wrapTemplate = Primer::$WRAP_TEMPLATES;
$id = Primer::cleanId($id);
// Create the template
$template = new Pattern('templates/' . $id);
$templateData = new ViewData([
"primer" => [
'bodyClass' => 'is-template',
'template' => $id,
],
]);
$data = $template->getData();
// Template level wrapping config
if (isset($data->primer->wrapTemplate)) {
$wrapTemplate = $data->primer->wrapTemplate;
}
if ($wrapTemplate) {
$view = 'template';
// Check the data to see if there is a custom view
if (isset($data->primer) && isset($data->primer->view)) {
$view = $data->primer->view;
}
$templateData->primer->items = $template->render(false);
Event::fire('render', $templateData);
return View::render($view, $templateData);
} else {
// Merge the data we would have passed into the view into the template
$template->setData($templateData);
// Get a reference to the template data so that we can pass it to anyone who's listening
$viewData = $template->getData();
Event::fire('render', $viewData);
return $template->render(false);
}
} | php | public function getTemplate($id)
{
// Default system wide template wrapping config
$wrapTemplate = Primer::$WRAP_TEMPLATES;
$id = Primer::cleanId($id);
// Create the template
$template = new Pattern('templates/' . $id);
$templateData = new ViewData([
"primer" => [
'bodyClass' => 'is-template',
'template' => $id,
],
]);
$data = $template->getData();
// Template level wrapping config
if (isset($data->primer->wrapTemplate)) {
$wrapTemplate = $data->primer->wrapTemplate;
}
if ($wrapTemplate) {
$view = 'template';
// Check the data to see if there is a custom view
if (isset($data->primer) && isset($data->primer->view)) {
$view = $data->primer->view;
}
$templateData->primer->items = $template->render(false);
Event::fire('render', $templateData);
return View::render($view, $templateData);
} else {
// Merge the data we would have passed into the view into the template
$template->setData($templateData);
// Get a reference to the template data so that we can pass it to anyone who's listening
$viewData = $template->getData();
Event::fire('render', $viewData);
return $template->render(false);
}
} | [
"public",
"function",
"getTemplate",
"(",
"$",
"id",
")",
"{",
"// Default system wide template wrapping config",
"$",
"wrapTemplate",
"=",
"Primer",
"::",
"$",
"WRAP_TEMPLATES",
";",
"$",
"id",
"=",
"Primer",
"::",
"cleanId",
"(",
"$",
"id",
")",
";",
"// Cre... | Get a specific page template
@param String $id The template id
@return String | [
"Get",
"a",
"specific",
"page",
"template"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Primer.php#L169-L216 | train |
Rareloop/primer-core | src/Primer/Primer.php | Primer.getPatterns | public function getPatterns($ids, $showChrome = true)
{
$renderList = new RenderList();
foreach ($ids as $id) {
$id = Primer::cleanId($id);
// Check if the Id is for a pattern or a group
$parts = explode('/', $id);
if (count($parts) > 2) {
// It's a pattern
$renderList->add(new Pattern($id));
} elseif (count($parts) > 1) {
// It's a group
$renderList->add(new Group($id));
} else {
// It's a section (e.g. all elements or all components)
$renderList->add(new Section($id));
}
}
return $this->prepareViewForPatterns($renderList, $showChrome);
} | php | public function getPatterns($ids, $showChrome = true)
{
$renderList = new RenderList();
foreach ($ids as $id) {
$id = Primer::cleanId($id);
// Check if the Id is for a pattern or a group
$parts = explode('/', $id);
if (count($parts) > 2) {
// It's a pattern
$renderList->add(new Pattern($id));
} elseif (count($parts) > 1) {
// It's a group
$renderList->add(new Group($id));
} else {
// It's a section (e.g. all elements or all components)
$renderList->add(new Section($id));
}
}
return $this->prepareViewForPatterns($renderList, $showChrome);
} | [
"public",
"function",
"getPatterns",
"(",
"$",
"ids",
",",
"$",
"showChrome",
"=",
"true",
")",
"{",
"$",
"renderList",
"=",
"new",
"RenderList",
"(",
")",
";",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"id",
")",
"{",
"$",
"id",
"=",
"Primer",
"::",
... | Get a selection of patterns
@param Array $ids An array of pattern/group/section ids
@param boolean $showChrome Should we show the chrome
@return String | [
"Get",
"a",
"selection",
"of",
"patterns"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Primer.php#L256-L278 | train |
Rareloop/primer-core | src/Primer/Primer.php | Primer.getTemplates | public function getTemplates()
{
$templates = array();
if ($handle = opendir(Primer::$PATTERN_PATH . '/templates')) {
while (false !== ($entry = readdir($handle))) {
if (substr($entry, 0, 1) !== '.') {
$templates[] = array(
'id' => $entry,
'title' => preg_replace('/[^A-Za-z0-9]/', ' ', $entry),
);
}
}
closedir($handle);
}
return $templates;
} | php | public function getTemplates()
{
$templates = array();
if ($handle = opendir(Primer::$PATTERN_PATH . '/templates')) {
while (false !== ($entry = readdir($handle))) {
if (substr($entry, 0, 1) !== '.') {
$templates[] = array(
'id' => $entry,
'title' => preg_replace('/[^A-Za-z0-9]/', ' ', $entry),
);
}
}
closedir($handle);
}
return $templates;
} | [
"public",
"function",
"getTemplates",
"(",
")",
"{",
"$",
"templates",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"handle",
"=",
"opendir",
"(",
"Primer",
"::",
"$",
"PATTERN_PATH",
".",
"'/templates'",
")",
")",
"{",
"while",
"(",
"false",
"!==",
... | Get the list of templates available. Returns an array of associative arrays
e.g.
array(
array(
'id' => 'home',
'title' => 'Home',
),
array(
'id' => 'about-us',
'title' => 'About Us'
)
);
@return array | [
"Get",
"the",
"list",
"of",
"templates",
"available",
".",
"Returns",
"an",
"array",
"of",
"associative",
"arrays"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Primer.php#L336-L354 | train |
jon48/webtrees-lib | src/Webtrees/Mvc/View/ViewFactory.php | ViewFactory.makeView | public function makeView($view_name, MvcController $mvc_ctrl, BaseController $ctrl, ViewBag $data)
{
if(!$mvc_ctrl) throw new \Exception('Mvc Controller not defined');
if(!$ctrl) throw new \Exception('Base Controller not defined');
if(!$view_name) throw new \Exception('View not defined');
$mvc_ctrl_refl = new \ReflectionObject($mvc_ctrl);
$view_class = $mvc_ctrl_refl->getNamespaceName() . '\\Views\\' . $view_name . 'View';
if(!class_exists($view_class)) throw new \Exception('View does not exist');
return new $view_class($ctrl, $data);
} | php | public function makeView($view_name, MvcController $mvc_ctrl, BaseController $ctrl, ViewBag $data)
{
if(!$mvc_ctrl) throw new \Exception('Mvc Controller not defined');
if(!$ctrl) throw new \Exception('Base Controller not defined');
if(!$view_name) throw new \Exception('View not defined');
$mvc_ctrl_refl = new \ReflectionObject($mvc_ctrl);
$view_class = $mvc_ctrl_refl->getNamespaceName() . '\\Views\\' . $view_name . 'View';
if(!class_exists($view_class)) throw new \Exception('View does not exist');
return new $view_class($ctrl, $data);
} | [
"public",
"function",
"makeView",
"(",
"$",
"view_name",
",",
"MvcController",
"$",
"mvc_ctrl",
",",
"BaseController",
"$",
"ctrl",
",",
"ViewBag",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"mvc_ctrl",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"'Mvc... | Return the view specified by the controller and view name, using data from the ViewBag
@param string $view_name
@param \MyArtJaub\Webtrees\Mvc\Controller\MvcControllerInterface $mvc_ctrl
@param \Fisharebest\Webtrees\Controller\BaseController $ctrl
@param \MyArtJaub\Webtrees\Mvc\View\ViewBag $data
@return \MyArtJaub\Webtrees\Mvc\View\AbstractView View
@throws \Exception | [
"Return",
"the",
"view",
"specified",
"by",
"the",
"controller",
"and",
"view",
"name",
"using",
"data",
"from",
"the",
"ViewBag"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Mvc/View/ViewFactory.php#L54-L65 | train |
jon48/webtrees-lib | src/Webtrees/Mvc/View/ViewFactory.php | ViewFactory.make | public static function make($view_name, MvcController $mvc_ctrl, BaseController $ctrl, ViewBag $data)
{
return self::getInstance()->makeView($view_name, $mvc_ctrl, $ctrl, $data);
} | php | public static function make($view_name, MvcController $mvc_ctrl, BaseController $ctrl, ViewBag $data)
{
return self::getInstance()->makeView($view_name, $mvc_ctrl, $ctrl, $data);
} | [
"public",
"static",
"function",
"make",
"(",
"$",
"view_name",
",",
"MvcController",
"$",
"mvc_ctrl",
",",
"BaseController",
"$",
"ctrl",
",",
"ViewBag",
"$",
"data",
")",
"{",
"return",
"self",
"::",
"getInstance",
"(",
")",
"->",
"makeView",
"(",
"$",
... | Static invocation of the makeView method
@param string $view_name
@param \MyArtJaub\Webtrees\Mvc\Controller\MvcControllerInterface $mvc_ctrl
@param \Fisharebest\Webtrees\Controller\BaseController $ctrl
@param \MyArtJaub\Webtrees\Mvc\View\ViewBag $data
@return \MyArtJaub\Webtrees\Mvc\View\AbstractView View
@see \MyArtJaub\Webtrees\Mvc\View\ViewFactory::handle() | [
"Static",
"invocation",
"of",
"the",
"makeView",
"method"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Mvc/View/ViewFactory.php#L77-L80 | train |
alexislefebvre/AsyncTweetsBundle | src/Entity/Tweet.php | Tweet.addMedia | public function addMedia(Media $media)
{
$this->medias->add($media);
$media->addTweet($this);
return $this;
} | php | public function addMedia(Media $media)
{
$this->medias->add($media);
$media->addTweet($this);
return $this;
} | [
"public",
"function",
"addMedia",
"(",
"Media",
"$",
"media",
")",
"{",
"$",
"this",
"->",
"medias",
"->",
"add",
"(",
"$",
"media",
")",
";",
"$",
"media",
"->",
"addTweet",
"(",
"$",
"this",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Add a media.
@param Media $media
@return Tweet | [
"Add",
"a",
"media",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Entity/Tweet.php#L288-L294 | train |
alexislefebvre/AsyncTweetsBundle | src/Entity/Tweet.php | Tweet.removeMedia | public function removeMedia(Media $media)
{
$this->medias->removeElement($media);
$media->removeTweet($this);
return $this;
} | php | public function removeMedia(Media $media)
{
$this->medias->removeElement($media);
$media->removeTweet($this);
return $this;
} | [
"public",
"function",
"removeMedia",
"(",
"Media",
"$",
"media",
")",
"{",
"$",
"this",
"->",
"medias",
"->",
"removeElement",
"(",
"$",
"media",
")",
";",
"$",
"media",
"->",
"removeTweet",
"(",
"$",
"this",
")",
";",
"return",
"$",
"this",
";",
"}"... | Remove a media.
@param Media $media
@return Tweet | [
"Remove",
"a",
"media",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Entity/Tweet.php#L303-L309 | train |
alexislefebvre/AsyncTweetsBundle | src/Entity/Tweet.php | Tweet.mustBeKept | public function mustBeKept($tweetId)
{
if (count($this->getRetweetingStatuses()) == 0) {
// This tweet has not been retweeted
return false;
}
// Check that this tweet has not been retweeted after $tweetId
foreach ($this->getRetweetingStatuses() as $retweeting_status) {
// This tweet is retweeted in the timeline, keep it
if ($retweeting_status->getId() >= $tweetId) {
return true;
}
}
return false;
} | php | public function mustBeKept($tweetId)
{
if (count($this->getRetweetingStatuses()) == 0) {
// This tweet has not been retweeted
return false;
}
// Check that this tweet has not been retweeted after $tweetId
foreach ($this->getRetweetingStatuses() as $retweeting_status) {
// This tweet is retweeted in the timeline, keep it
if ($retweeting_status->getId() >= $tweetId) {
return true;
}
}
return false;
} | [
"public",
"function",
"mustBeKept",
"(",
"$",
"tweetId",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"getRetweetingStatuses",
"(",
")",
")",
"==",
"0",
")",
"{",
"// This tweet has not been retweeted",
"return",
"false",
";",
"}",
"// Check that this... | Check that tweet can be deleted.
@param int $tweetId
@return bool | [
"Check",
"that",
"tweet",
"can",
"be",
"deleted",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Entity/Tweet.php#L346-L362 | train |
GrupaZero/cms | src/Gzero/Cms/CMSSeeder.php | CMSSeeder.run | public function run()
{
config()->set('gzero-core.db_transactions', false);
$languages = Language::all()->keyBy('code');
$users = $this->seedUsers();
$contents = $this->seedContent($languages, $users);
$this->seedBlock(BlockType::all(), $languages, $users, $contents);
//$fileTypes = $this->seedFileTypes();
//$files = $this->seedFiles($fileTypes, $languages, $users, $contents, $blocks);
//$this->seedOptions($languages);
} | php | public function run()
{
config()->set('gzero-core.db_transactions', false);
$languages = Language::all()->keyBy('code');
$users = $this->seedUsers();
$contents = $this->seedContent($languages, $users);
$this->seedBlock(BlockType::all(), $languages, $users, $contents);
//$fileTypes = $this->seedFileTypes();
//$files = $this->seedFiles($fileTypes, $languages, $users, $contents, $blocks);
//$this->seedOptions($languages);
} | [
"public",
"function",
"run",
"(",
")",
"{",
"config",
"(",
")",
"->",
"set",
"(",
"'gzero-core.db_transactions'",
",",
"false",
")",
";",
"$",
"languages",
"=",
"Language",
"::",
"all",
"(",
")",
"->",
"keyBy",
"(",
"'code'",
")",
";",
"$",
"users",
... | This function run all seeds
@return void | [
"This",
"function",
"run",
"all",
"seeds"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/CMSSeeder.php#L47-L57 | train |
GrupaZero/cms | src/Gzero/Cms/CMSSeeder.php | CMSSeeder.seedRandomContent | private function seedRandomContent(string $type, $parent, $languages, $users)
{
$user = $users->random();
$en = $languages['en'];
$pl = $languages['pl'];
$faker = Factory::create($en->i18n);
$title = $faker->realText(38, 1);
$content = dispatch_now(CreateContent::make($title, $en, $user, array_merge(
[
'type' => $type,
'parent_id' => array_get($parent, 'id', null),
'weight' => rand(0, 10),
'rating' => rand(0, 5),
'is_on_home' => (bool) rand(0, 1),
'is_comment_allowed' => (bool) rand(0, 1),
'is_promoted' => (bool) rand(0, 1),
'is_sticky' => (bool) rand(0, 1),
'is_active' => (bool) rand(0, 1),
'published_at' => Carbon::now()
],
$this->generateContentTranslation($en)
)));
$faker = Factory::create($pl->i18n);
$title = $faker->realText(38, 1);
dispatch_now(new AddContentTranslation($content, $title, $pl, $user, $this->generateContentTranslation($pl)));
return $content;
} | php | private function seedRandomContent(string $type, $parent, $languages, $users)
{
$user = $users->random();
$en = $languages['en'];
$pl = $languages['pl'];
$faker = Factory::create($en->i18n);
$title = $faker->realText(38, 1);
$content = dispatch_now(CreateContent::make($title, $en, $user, array_merge(
[
'type' => $type,
'parent_id' => array_get($parent, 'id', null),
'weight' => rand(0, 10),
'rating' => rand(0, 5),
'is_on_home' => (bool) rand(0, 1),
'is_comment_allowed' => (bool) rand(0, 1),
'is_promoted' => (bool) rand(0, 1),
'is_sticky' => (bool) rand(0, 1),
'is_active' => (bool) rand(0, 1),
'published_at' => Carbon::now()
],
$this->generateContentTranslation($en)
)));
$faker = Factory::create($pl->i18n);
$title = $faker->realText(38, 1);
dispatch_now(new AddContentTranslation($content, $title, $pl, $user, $this->generateContentTranslation($pl)));
return $content;
} | [
"private",
"function",
"seedRandomContent",
"(",
"string",
"$",
"type",
",",
"$",
"parent",
",",
"$",
"languages",
",",
"$",
"users",
")",
"{",
"$",
"user",
"=",
"$",
"users",
"->",
"random",
"(",
")",
";",
"$",
"en",
"=",
"$",
"languages",
"[",
"'... | Seed single content
@param string $type Content type
@param Content|Null $parent Parent element
@param array $languages Array with languages
@param array $users Array with users
@return bool | [
"Seed",
"single",
"content"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/CMSSeeder.php#L118-L147 | train |
GrupaZero/cms | src/Gzero/Cms/CMSSeeder.php | CMSSeeder.seedRandomBlock | private function seedRandomBlock(BlockType $type, $languages, $users, $contents)
{
$language = $languages->random();
$faker = Factory::create($language->i18n);
$isActive = (bool) rand(0, 1);
$isCacheable = (bool) rand(0, 1);
$filter = (rand(0, 1)) ? [
'+' => [$this->getRandomBlockFilter($contents)],
'-' => [$this->getRandomBlockFilter($contents)]
] : null;
$input = [
'type' => $type->name,
'region' => $this->getRandomBlockRegion(),
'weight' => rand(0, 12),
'filter' => $filter,
'options' => array_combine($this->faker->words(), $this->faker->words()),
'is_active' => $isActive,
'is_cacheable' => $isCacheable,
'translations' => $this->prepareBlockTranslation($languages['en']),
'body' => $faker->realText(300),
'custom_fields' => array_combine($this->faker->words(), $this->faker->words()),
];
$block = dispatch_now(CreateBlock::make($faker->realText(38, 1), $language, $users->random(), $input));
return $block;
} | php | private function seedRandomBlock(BlockType $type, $languages, $users, $contents)
{
$language = $languages->random();
$faker = Factory::create($language->i18n);
$isActive = (bool) rand(0, 1);
$isCacheable = (bool) rand(0, 1);
$filter = (rand(0, 1)) ? [
'+' => [$this->getRandomBlockFilter($contents)],
'-' => [$this->getRandomBlockFilter($contents)]
] : null;
$input = [
'type' => $type->name,
'region' => $this->getRandomBlockRegion(),
'weight' => rand(0, 12),
'filter' => $filter,
'options' => array_combine($this->faker->words(), $this->faker->words()),
'is_active' => $isActive,
'is_cacheable' => $isCacheable,
'translations' => $this->prepareBlockTranslation($languages['en']),
'body' => $faker->realText(300),
'custom_fields' => array_combine($this->faker->words(), $this->faker->words()),
];
$block = dispatch_now(CreateBlock::make($faker->realText(38, 1), $language, $users->random(), $input));
return $block;
} | [
"private",
"function",
"seedRandomBlock",
"(",
"BlockType",
"$",
"type",
",",
"$",
"languages",
",",
"$",
"users",
",",
"$",
"contents",
")",
"{",
"$",
"language",
"=",
"$",
"languages",
"->",
"random",
"(",
")",
";",
"$",
"faker",
"=",
"Factory",
"::"... | Seed single block
@param BlockType $type Block type
@param array $languages Array with languages
@param array $users Array with users
@param array $contents Array with contents
@return Block | [
"Seed",
"single",
"block"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/CMSSeeder.php#L246-L272 | train |
GrupaZero/cms | src/Gzero/Cms/CMSSeeder.php | CMSSeeder.generateBodyHTML | private function generateBodyHTML(Generator $faker)
{
$html = [];
$imageCategories = [
'abstract',
'animals',
'business',
'cats',
'city',
'food',
'nightlife',
'fashion',
'people',
'nature',
'sports',
'technics',
'transport'
];
$paragraphImageNumber = rand(0, 5);
$headingNumber = rand(0, 5);
$imageUrl = $faker->imageUrl(1140, 480, $imageCategories[array_rand($imageCategories)]);
// random dumber of paragraphs
for ($i = 0; $i < rand(5, 10); $i++) {
$html[] = '<p>' . $faker->realText(rand(300, 1500)) . '</p>';
// insert heading
if ($i == $headingNumber) {
$html[] = '<h3>' . $faker->realText(100) . '</h3>';
}
// insert image
if ($i == $paragraphImageNumber) {
$html[] = '<p><img src="' . $imageUrl . '" class="img-fluid"/></p>';
}
}
return implode('', $html);
} | php | private function generateBodyHTML(Generator $faker)
{
$html = [];
$imageCategories = [
'abstract',
'animals',
'business',
'cats',
'city',
'food',
'nightlife',
'fashion',
'people',
'nature',
'sports',
'technics',
'transport'
];
$paragraphImageNumber = rand(0, 5);
$headingNumber = rand(0, 5);
$imageUrl = $faker->imageUrl(1140, 480, $imageCategories[array_rand($imageCategories)]);
// random dumber of paragraphs
for ($i = 0; $i < rand(5, 10); $i++) {
$html[] = '<p>' . $faker->realText(rand(300, 1500)) . '</p>';
// insert heading
if ($i == $headingNumber) {
$html[] = '<h3>' . $faker->realText(100) . '</h3>';
}
// insert image
if ($i == $paragraphImageNumber) {
$html[] = '<p><img src="' . $imageUrl . '" class="img-fluid"/></p>';
}
}
return implode('', $html);
} | [
"private",
"function",
"generateBodyHTML",
"(",
"Generator",
"$",
"faker",
")",
"{",
"$",
"html",
"=",
"[",
"]",
";",
"$",
"imageCategories",
"=",
"[",
"'abstract'",
",",
"'animals'",
",",
"'business'",
",",
"'cats'",
",",
"'city'",
",",
"'food'",
",",
"... | Function generates translation body HTML
@param Generator $faker Faker factory
@return string generated HTML | [
"Function",
"generates",
"translation",
"body",
"HTML"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/CMSSeeder.php#L417-L452 | train |
GrupaZero/cms | src/Gzero/Cms/CMSSeeder.php | CMSSeeder.getRandomBlockFilter | private function getRandomBlockFilter($contents)
{
return rand(0, 1) ? $contents[array_rand($contents)]->path . '*' : $contents[array_rand($contents)]->path;
} | php | private function getRandomBlockFilter($contents)
{
return rand(0, 1) ? $contents[array_rand($contents)]->path . '*' : $contents[array_rand($contents)]->path;
} | [
"private",
"function",
"getRandomBlockFilter",
"(",
"$",
"contents",
")",
"{",
"return",
"rand",
"(",
"0",
",",
"1",
")",
"?",
"$",
"contents",
"[",
"array_rand",
"(",
"$",
"contents",
")",
"]",
"->",
"path",
".",
"'*'",
":",
"$",
"contents",
"[",
"a... | Function generates block filter path
@param array $contents Array with contents
@return string | [
"Function",
"generates",
"block",
"filter",
"path"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/CMSSeeder.php#L461-L464 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/ContentReadRepository.php | ContentReadRepository.getByPath | public function getByPath(string $path, string $languageCode, bool $onlyActive = false)
{
return Content::query()
->with(self::$loadRelations)
->join('routes', function ($join) use ($languageCode, $path, $onlyActive) {
$join->on('contents.id', '=', 'routes.routable_id')
->where('routes.routable_type', '=', Content::class)
->where('routes.language_code', $languageCode)
->where('routes.path', $path)
->when($onlyActive, function ($query) {
$query->where('routes.is_active', true);
});
})
->first(['contents.*']);
} | php | public function getByPath(string $path, string $languageCode, bool $onlyActive = false)
{
return Content::query()
->with(self::$loadRelations)
->join('routes', function ($join) use ($languageCode, $path, $onlyActive) {
$join->on('contents.id', '=', 'routes.routable_id')
->where('routes.routable_type', '=', Content::class)
->where('routes.language_code', $languageCode)
->where('routes.path', $path)
->when($onlyActive, function ($query) {
$query->where('routes.is_active', true);
});
})
->first(['contents.*']);
} | [
"public",
"function",
"getByPath",
"(",
"string",
"$",
"path",
",",
"string",
"$",
"languageCode",
",",
"bool",
"$",
"onlyActive",
"=",
"false",
")",
"{",
"return",
"Content",
"::",
"query",
"(",
")",
"->",
"with",
"(",
"self",
"::",
"$",
"loadRelations"... | Retrieve a content by given path
@param string $path URI path
@param string $languageCode Language code
@param bool $onlyActive Trigger
@return Content|mixed | [
"Retrieve",
"a",
"content",
"by",
"given",
"path"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/ContentReadRepository.php#L103-L117 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/ContentReadRepository.php | ContentReadRepository.getAncestorsTitlesAndPaths | public function getAncestorsTitlesAndPaths(Content $content, Language $language, $onlyActive = true)
{
$ancestorIds = array_filter(explode('/', $content->path));
return \DB::table('contents as c')
->join('routes as r', function ($join) use ($language, $onlyActive) {
$join->on('c.id', '=', 'r.routable_id')
->where('r.routable_type', '=', Content::class)
->where('r.language_code', $language->code)
->when($onlyActive, function ($query) {
$query->where('r.is_active', true);
});
})
->join('content_translations as ct', function ($join) use ($language, $onlyActive) {
$join->on('c.id', '=', 'ct.content_id')->where('ct.language_code', $language->code)
->when($onlyActive, function ($query) {
$query->where('ct.is_active', true);
});
})
->whereIn('c.id', $ancestorIds)
->orderBy('level', 'ASC')
->select(['ct.title', 'r.path'])
->get();
} | php | public function getAncestorsTitlesAndPaths(Content $content, Language $language, $onlyActive = true)
{
$ancestorIds = array_filter(explode('/', $content->path));
return \DB::table('contents as c')
->join('routes as r', function ($join) use ($language, $onlyActive) {
$join->on('c.id', '=', 'r.routable_id')
->where('r.routable_type', '=', Content::class)
->where('r.language_code', $language->code)
->when($onlyActive, function ($query) {
$query->where('r.is_active', true);
});
})
->join('content_translations as ct', function ($join) use ($language, $onlyActive) {
$join->on('c.id', '=', 'ct.content_id')->where('ct.language_code', $language->code)
->when($onlyActive, function ($query) {
$query->where('ct.is_active', true);
});
})
->whereIn('c.id', $ancestorIds)
->orderBy('level', 'ASC')
->select(['ct.title', 'r.path'])
->get();
} | [
"public",
"function",
"getAncestorsTitlesAndPaths",
"(",
"Content",
"$",
"content",
",",
"Language",
"$",
"language",
",",
"$",
"onlyActive",
"=",
"true",
")",
"{",
"$",
"ancestorIds",
"=",
"array_filter",
"(",
"explode",
"(",
"'/'",
",",
"$",
"content",
"->... | Returns titles & url paths from ancestors
@param Content $content Content
@param Language $language Language
@param bool $onlyActive isActive trigger
@return \Illuminate\Support\Collection | [
"Returns",
"titles",
"&",
"url",
"paths",
"from",
"ancestors"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/ContentReadRepository.php#L128-L150 | train |
GrupaZero/cms | src/Gzero/Cms/Repositories/ContentReadRepository.php | ContentReadRepository.getChildren | public function getChildren(Content $content, Language $language)
{
return $content->children()
->with(self::$loadRelations)
->where('published_at', '<=', Carbon::now())
->whereHas('routes', function ($query) use ($language) {
$query->where('routes.is_active', true)
->where('language_code', $language->code);
})
->orderBy('is_promoted', 'DESC')
->orderBy('is_sticky', 'DESC')
->orderBy('weight', 'ASC')
->orderBy('published_at', 'DESC')
->paginate(option('general', 'default_page_size', 20));
} | php | public function getChildren(Content $content, Language $language)
{
return $content->children()
->with(self::$loadRelations)
->where('published_at', '<=', Carbon::now())
->whereHas('routes', function ($query) use ($language) {
$query->where('routes.is_active', true)
->where('language_code', $language->code);
})
->orderBy('is_promoted', 'DESC')
->orderBy('is_sticky', 'DESC')
->orderBy('weight', 'ASC')
->orderBy('published_at', 'DESC')
->paginate(option('general', 'default_page_size', 20));
} | [
"public",
"function",
"getChildren",
"(",
"Content",
"$",
"content",
",",
"Language",
"$",
"language",
")",
"{",
"return",
"$",
"content",
"->",
"children",
"(",
")",
"->",
"with",
"(",
"self",
"::",
"$",
"loadRelations",
")",
"->",
"where",
"(",
"'publi... | Get all children specific content
@param Content $content parent
@param Language $language Current language
@return mixed | [
"Get",
"all",
"children",
"specific",
"content"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Repositories/ContentReadRepository.php#L237-L251 | train |
jon48/webtrees-lib | src/Webtrees/Mvc/View/AbstractView.php | AbstractView.render | public function render() {
global $controller;
if(!$this->ctrl) throw new \Exception('Controller not initialised');
$controller = $this->ctrl;
$this->ctrl->pageHeader();
echo $this->renderContent();
} | php | public function render() {
global $controller;
if(!$this->ctrl) throw new \Exception('Controller not initialised');
$controller = $this->ctrl;
$this->ctrl->pageHeader();
echo $this->renderContent();
} | [
"public",
"function",
"render",
"(",
")",
"{",
"global",
"$",
"controller",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"ctrl",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"'Controller not initialised'",
")",
";",
"$",
"controller",
"=",
"$",
"this",
"->",
... | Render the view to the page, including header.
@throws \Exception | [
"Render",
"the",
"view",
"to",
"the",
"page",
"including",
"header",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Mvc/View/AbstractView.php#L45-L54 | train |
jon48/webtrees-lib | src/Webtrees/Mvc/View/AbstractView.php | AbstractView.getHtmlPartial | public function getHtmlPartial() {
ob_start();
$html_render = $this->renderContent();
$html_buffer = ob_get_clean();
return empty($html_render) ? $html_buffer : $html_render;
} | php | public function getHtmlPartial() {
ob_start();
$html_render = $this->renderContent();
$html_buffer = ob_get_clean();
return empty($html_render) ? $html_buffer : $html_render;
} | [
"public",
"function",
"getHtmlPartial",
"(",
")",
"{",
"ob_start",
"(",
")",
";",
"$",
"html_render",
"=",
"$",
"this",
"->",
"renderContent",
"(",
")",
";",
"$",
"html_buffer",
"=",
"ob_get_clean",
"(",
")",
";",
"return",
"empty",
"(",
"$",
"html_rende... | Return the HTML code generated by the view, without any header | [
"Return",
"the",
"HTML",
"code",
"generated",
"by",
"the",
"view",
"without",
"any",
"header"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Mvc/View/AbstractView.php#L66-L72 | train |
pckg/database | src/Pckg/Database/Repository/RepositoryFactory.php | RepositoryFactory.getRepositoryByConfig | protected static function getRepositoryByConfig($config, $name)
{
if (!is_array($config)) {
if (class_exists($config)) {
return new $config;
}
throw new Exception('Cannot create repository from string');
} elseif ($config['driver'] == 'faker') {
return new Faker(Factory::create());
} elseif ($config['driver'] == 'middleware') {
return resolve($config['middleware'])->execute(function() {
}
);
}
return static::initPdoDatabase($config, $name);
} | php | protected static function getRepositoryByConfig($config, $name)
{
if (!is_array($config)) {
if (class_exists($config)) {
return new $config;
}
throw new Exception('Cannot create repository from string');
} elseif ($config['driver'] == 'faker') {
return new Faker(Factory::create());
} elseif ($config['driver'] == 'middleware') {
return resolve($config['middleware'])->execute(function() {
}
);
}
return static::initPdoDatabase($config, $name);
} | [
"protected",
"static",
"function",
"getRepositoryByConfig",
"(",
"$",
"config",
",",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"if",
"(",
"class_exists",
"(",
"$",
"config",
")",
")",
"{",
"return",
"new",
... | Instantiate connection for defined driver.
@param $config
@param $name
@return Faker|RepositoryPDO
@throws Exception | [
"Instantiate",
"connection",
"for",
"defined",
"driver",
"."
] | 99b26b4cb2bacc2bbbb83b7341a209c1cf0100d3 | https://github.com/pckg/database/blob/99b26b4cb2bacc2bbbb83b7341a209c1cf0100d3/src/Pckg/Database/Repository/RepositoryFactory.php#L212-L229 | train |
voslartomas/WebCMS2 | install/Form.php | Form.signalReceived | public function signalReceived($signal)
{
if ($signal === 'submit') {
if (!$this->getPresenter()->getRequest()->hasFlag(Nette\Application\Request::RESTORED)) {
$this->fireEvents();
}
} else {
$class = get_class($this);
throw new BadSignalException("Missing handler for signal '$signal' in $class.");
}
} | php | public function signalReceived($signal)
{
if ($signal === 'submit') {
if (!$this->getPresenter()->getRequest()->hasFlag(Nette\Application\Request::RESTORED)) {
$this->fireEvents();
}
} else {
$class = get_class($this);
throw new BadSignalException("Missing handler for signal '$signal' in $class.");
}
} | [
"public",
"function",
"signalReceived",
"(",
"$",
"signal",
")",
"{",
"if",
"(",
"$",
"signal",
"===",
"'submit'",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getPresenter",
"(",
")",
"->",
"getRequest",
"(",
")",
"->",
"hasFlag",
"(",
"Nette",
"\\... | This method is called by presenter.
@param string
@return void | [
"This",
"method",
"is",
"called",
"by",
"presenter",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/install/Form.php#L121-L131 | train |
c4studio/chronos | src/Chronos/Scaffolding/database/migrations/2016_10_17_300000_alter_users_table.php | AlterUsersTable.up | public function up()
{
Schema::table('users', function (Blueprint $table) {
if (Schema::hasColumn('users', 'name'))
$table->dropColumn('name');
$table->integer('role_id')->unsigned()->nullable();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->string('firstname')->default('');
$table->string('lastname')->default('');
$table->string('picture')->nullable();
});
} | php | public function up()
{
Schema::table('users', function (Blueprint $table) {
if (Schema::hasColumn('users', 'name'))
$table->dropColumn('name');
$table->integer('role_id')->unsigned()->nullable();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->string('firstname')->default('');
$table->string('lastname')->default('');
$table->string('picture')->nullable();
});
} | [
"public",
"function",
"up",
"(",
")",
"{",
"Schema",
"::",
"table",
"(",
"'users'",
",",
"function",
"(",
"Blueprint",
"$",
"table",
")",
"{",
"if",
"(",
"Schema",
"::",
"hasColumn",
"(",
"'users'",
",",
"'name'",
")",
")",
"$",
"table",
"->",
"dropC... | Run the database.
@return void | [
"Run",
"the",
"database",
"."
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Scaffolding/database/migrations/2016_10_17_300000_alter_users_table.php#L14-L25 | train |
c4studio/chronos | src/Chronos/Scaffolding/database/migrations/2016_10_17_300000_alter_users_table.php | AlterUsersTable.down | public function down()
{
Schema::table('users', function ($table) {
$table->string('name')->after('id');
$table->dropColumn('picture');
$table->dropColumn('lastname');
$table->dropColumn('firstname');
$table->dropForeign('users_role_id_foreign');
$table->dropColumn('role_id');
});
} | php | public function down()
{
Schema::table('users', function ($table) {
$table->string('name')->after('id');
$table->dropColumn('picture');
$table->dropColumn('lastname');
$table->dropColumn('firstname');
$table->dropForeign('users_role_id_foreign');
$table->dropColumn('role_id');
});
} | [
"public",
"function",
"down",
"(",
")",
"{",
"Schema",
"::",
"table",
"(",
"'users'",
",",
"function",
"(",
"$",
"table",
")",
"{",
"$",
"table",
"->",
"string",
"(",
"'name'",
")",
"->",
"after",
"(",
"'id'",
")",
";",
"$",
"table",
"->",
"dropCol... | Reverse the database.
@return void | [
"Reverse",
"the",
"database",
"."
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Scaffolding/database/migrations/2016_10_17_300000_alter_users_table.php#L32-L42 | train |
GrupaZero/cms | src/Gzero/Cms/Listeners/BlockLoad.php | BlockLoad.handle | public function handle($event)
{
if ($event instanceof RouteMatched) {
$this->handleLaravelRoute($event);
}
if ($event instanceof GzeroRouteMatched) {
$this->handleRoute($event);
}
} | php | public function handle($event)
{
if ($event instanceof RouteMatched) {
$this->handleLaravelRoute($event);
}
if ($event instanceof GzeroRouteMatched) {
$this->handleRoute($event);
}
} | [
"public",
"function",
"handle",
"(",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"event",
"instanceof",
"RouteMatched",
")",
"{",
"$",
"this",
"->",
"handleLaravelRoute",
"(",
"$",
"event",
")",
";",
"}",
"if",
"(",
"$",
"event",
"instanceof",
"GzeroRouteMat... | Handle the event. It loads block for matched routes.
@param mixed $event Matched route or content
@return void | [
"Handle",
"the",
"event",
".",
"It",
"loads",
"block",
"for",
"matched",
"routes",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Listeners/BlockLoad.php#L49-L58 | train |
GrupaZero/cms | src/Gzero/Cms/Listeners/BlockLoad.php | BlockLoad.handleLaravelRoute | public function handleLaravelRoute(RouteMatched $event)
{
if ($this->isValidFrontendRoute($event)) {
ViewComposer::addCallback(function () use ($event) {
$blockIds = $this->blockFinder->getBlocksIds($event->route->getName(), true);
$blocks = $this->blockRepository->getVisibleBlocks($blockIds, $this->languageService->getCurrent(), true);
$this->handleBlockRendering($blocks);
$blocks = $blocks->groupBy('region');
view()->share('blocks', $blocks);
});
}
} | php | public function handleLaravelRoute(RouteMatched $event)
{
if ($this->isValidFrontendRoute($event)) {
ViewComposer::addCallback(function () use ($event) {
$blockIds = $this->blockFinder->getBlocksIds($event->route->getName(), true);
$blocks = $this->blockRepository->getVisibleBlocks($blockIds, $this->languageService->getCurrent(), true);
$this->handleBlockRendering($blocks);
$blocks = $blocks->groupBy('region');
view()->share('blocks', $blocks);
});
}
} | [
"public",
"function",
"handleLaravelRoute",
"(",
"RouteMatched",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isValidFrontendRoute",
"(",
"$",
"event",
")",
")",
"{",
"ViewComposer",
"::",
"addCallback",
"(",
"function",
"(",
")",
"use",
"(",
"$"... | Handle the event. It loads block for static named routes.
@param RouteMatched $event dispatched event
@return void | [
"Handle",
"the",
"event",
".",
"It",
"loads",
"block",
"for",
"static",
"named",
"routes",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Listeners/BlockLoad.php#L67-L78 | train |
GrupaZero/cms | src/Gzero/Cms/Listeners/BlockLoad.php | BlockLoad.handleRoute | public function handleRoute(GzeroRouteMatched $event)
{
$blockIds = $this->blockFinder->getBlocksIds($event->route->getRoutable(), true);
$blocks = $this->blockRepository->getVisibleBlocks($blockIds, $this->languageService->getCurrent(), true);
$this->handleBlockRendering($blocks);
$blocks = $blocks->groupBy('region');
view()->share('blocks', $blocks);
} | php | public function handleRoute(GzeroRouteMatched $event)
{
$blockIds = $this->blockFinder->getBlocksIds($event->route->getRoutable(), true);
$blocks = $this->blockRepository->getVisibleBlocks($blockIds, $this->languageService->getCurrent(), true);
$this->handleBlockRendering($blocks);
$blocks = $blocks->groupBy('region');
view()->share('blocks', $blocks);
} | [
"public",
"function",
"handleRoute",
"(",
"GzeroRouteMatched",
"$",
"event",
")",
"{",
"$",
"blockIds",
"=",
"$",
"this",
"->",
"blockFinder",
"->",
"getBlocksIds",
"(",
"$",
"event",
"->",
"route",
"->",
"getRoutable",
"(",
")",
",",
"true",
")",
";",
"... | Handle the event. It loads block for dynamic router.
@param GzeroRouteMatched $event dispatched event
@return void | [
"Handle",
"the",
"event",
".",
"It",
"loads",
"block",
"for",
"dynamic",
"router",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Listeners/BlockLoad.php#L87-L94 | train |
GrupaZero/cms | src/Gzero/Cms/Listeners/BlockLoad.php | BlockLoad.handleBlockRendering | protected function handleBlockRendering($blocks)
{
foreach ($blocks as &$block) {
$type = resolve($block->type->handler);
$block->view = $type->handle($block, $this->languageService->getCurrent());
}
} | php | protected function handleBlockRendering($blocks)
{
foreach ($blocks as &$block) {
$type = resolve($block->type->handler);
$block->view = $type->handle($block, $this->languageService->getCurrent());
}
} | [
"protected",
"function",
"handleBlockRendering",
"(",
"$",
"blocks",
")",
"{",
"foreach",
"(",
"$",
"blocks",
"as",
"&",
"$",
"block",
")",
"{",
"$",
"type",
"=",
"resolve",
"(",
"$",
"block",
"->",
"type",
"->",
"handler",
")",
";",
"$",
"block",
"-... | It renders blocks
@param Collection $blocks List of blocks to render
@return void | [
"It",
"renders",
"blocks"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Listeners/BlockLoad.php#L103-L109 | train |
pckg/database | src/Pckg/Database/Query/Helper/With.php | With.fillRecordWithRelations | public function fillRecordWithRelations(Record $record)
{
foreach ($this->getWith() as $relation) {
$relation->fillRecord($record);
}
return $record;
} | php | public function fillRecordWithRelations(Record $record)
{
foreach ($this->getWith() as $relation) {
$relation->fillRecord($record);
}
return $record;
} | [
"public",
"function",
"fillRecordWithRelations",
"(",
"Record",
"$",
"record",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getWith",
"(",
")",
"as",
"$",
"relation",
")",
"{",
"$",
"relation",
"->",
"fillRecord",
"(",
"$",
"record",
")",
";",
"}",
"r... | Fill record with all it's relations.
@param Record $record
@return Record | [
"Fill",
"record",
"with",
"all",
"it",
"s",
"relations",
"."
] | 99b26b4cb2bacc2bbbb83b7341a209c1cf0100d3 | https://github.com/pckg/database/blob/99b26b4cb2bacc2bbbb83b7341a209c1cf0100d3/src/Pckg/Database/Query/Helper/With.php#L155-L162 | train |
pckg/database | src/Pckg/Database/Query/Helper/With.php | With.fillCollectionWithRelations | public function fillCollectionWithRelations(CollectionInterface $collection)
{
if (!$collection->count()) {
return $collection;
}
foreach ($this->getWith() as $relation) {
$relation->fillCollection($collection);
}
return $collection;
} | php | public function fillCollectionWithRelations(CollectionInterface $collection)
{
if (!$collection->count()) {
return $collection;
}
foreach ($this->getWith() as $relation) {
$relation->fillCollection($collection);
}
return $collection;
} | [
"public",
"function",
"fillCollectionWithRelations",
"(",
"CollectionInterface",
"$",
"collection",
")",
"{",
"if",
"(",
"!",
"$",
"collection",
"->",
"count",
"(",
")",
")",
"{",
"return",
"$",
"collection",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"g... | Fill collection of records with all of their relations.
@param CollectionInterface $collection
@return CollectionInterface | [
"Fill",
"collection",
"of",
"records",
"with",
"all",
"of",
"their",
"relations",
"."
] | 99b26b4cb2bacc2bbbb83b7341a209c1cf0100d3 | https://github.com/pckg/database/blob/99b26b4cb2bacc2bbbb83b7341a209c1cf0100d3/src/Pckg/Database/Query/Helper/With.php#L179-L190 | train |
jon48/webtrees-lib | src/Webtrees/Module/GeoDispersion/AdminConfigController.php | AdminConfigController.renderEdit | protected function renderEdit(GeoAnalysis $ga = null) {
$wt_tree = Globals::getTree();
Theme::theme(new AdministrationTheme)->init($wt_tree);
$controller = new PageController();
$controller
->restrictAccess(Auth::isManager($wt_tree))
->addInlineJavascript('
function toggleMapOptions() {
if($("input:radio[name=\'use_map\']:checked").val() == 1) {
$("#map_options").show();
}
else {
$("#map_options").hide();
}
}
$("[name=\'use_map\']").on("change", toggleMapOptions);
toggleMapOptions();
');
$data = new ViewBag();
if($ga) {
$controller->setPageTitle(I18N::translate('Edit the geographical dispersion analysis'));
$data->set('geo_analysis', $ga);
} else {
$controller->setPageTitle(I18N::translate('Add a geographical dispersion analysis'));
}
$data->set('title', $controller->getPageTitle());
$data->set('admin_config_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl());
$data->set('module_title', $this->module->getTitle());
$data->set('save_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@save&ged=' . $wt_tree->getNameUrl());
$data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
$map_list = array_map(
function(OutlineMap $map) {
return $map->getDescription();
},
$this->provider->getOutlineMapsList()
);
asort($map_list);
$data->set('map_list', $map_list);
$gen_details = array(0 => I18N::translate('All'));
for($i = 1; $i <= 10 ; $i++) $gen_details[$i] = $i;
$data->set('generation_details', $gen_details);
ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
} | php | protected function renderEdit(GeoAnalysis $ga = null) {
$wt_tree = Globals::getTree();
Theme::theme(new AdministrationTheme)->init($wt_tree);
$controller = new PageController();
$controller
->restrictAccess(Auth::isManager($wt_tree))
->addInlineJavascript('
function toggleMapOptions() {
if($("input:radio[name=\'use_map\']:checked").val() == 1) {
$("#map_options").show();
}
else {
$("#map_options").hide();
}
}
$("[name=\'use_map\']").on("change", toggleMapOptions);
toggleMapOptions();
');
$data = new ViewBag();
if($ga) {
$controller->setPageTitle(I18N::translate('Edit the geographical dispersion analysis'));
$data->set('geo_analysis', $ga);
} else {
$controller->setPageTitle(I18N::translate('Add a geographical dispersion analysis'));
}
$data->set('title', $controller->getPageTitle());
$data->set('admin_config_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl());
$data->set('module_title', $this->module->getTitle());
$data->set('save_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@save&ged=' . $wt_tree->getNameUrl());
$data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
$map_list = array_map(
function(OutlineMap $map) {
return $map->getDescription();
},
$this->provider->getOutlineMapsList()
);
asort($map_list);
$data->set('map_list', $map_list);
$gen_details = array(0 => I18N::translate('All'));
for($i = 1; $i <= 10 ; $i++) $gen_details[$i] = $i;
$data->set('generation_details', $gen_details);
ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
} | [
"protected",
"function",
"renderEdit",
"(",
"GeoAnalysis",
"$",
"ga",
"=",
"null",
")",
"{",
"$",
"wt_tree",
"=",
"Globals",
"::",
"getTree",
"(",
")",
";",
"Theme",
"::",
"theme",
"(",
"new",
"AdministrationTheme",
")",
"->",
"init",
"(",
"$",
"wt_tree"... | Renders the edit form, whether it is an edition of an existing GeoAnalysis, or the addition of a new one.
@param (GeoAnalysis!null) $ga GeoAnalysis to edit | [
"Renders",
"the",
"edit",
"form",
"whether",
"it",
"is",
"an",
"edition",
"of",
"an",
"existing",
"GeoAnalysis",
"or",
"the",
"addition",
"of",
"a",
"new",
"one",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/GeoDispersion/AdminConfigController.php#L394-L442 | train |
GrupaZero/cms | src/Gzero/Cms/Jobs/CreateBlock.php | CreateBlock.slider | public static function slider(string $title, Language $language, User $author, array $attributes = [])
{
return new self($title, $language, $author, array_merge($attributes, ['type' => 'slider']));
} | php | public static function slider(string $title, Language $language, User $author, array $attributes = [])
{
return new self($title, $language, $author, array_merge($attributes, ['type' => 'slider']));
} | [
"public",
"static",
"function",
"slider",
"(",
"string",
"$",
"title",
",",
"Language",
"$",
"language",
",",
"User",
"$",
"author",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"title",
",",
"$",
"lang... | It creates job to create block
@param string $title Translation title
@param Language $language Language
@param User $author User model
@param array $attributes Array of optional attributes
@return CreateBlock | [
"It",
"creates",
"job",
"to",
"create",
"block"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Jobs/CreateBlock.php#L113-L116 | train |
jon48/webtrees-lib | src/Webtrees/Hook/Hook.php | Hook.subscribe | public function subscribe($hsubscriber){
if(HookProvider::getInstance()->isModuleOperational()){
Database::prepare(
"INSERT IGNORE INTO `##maj_hooks` (majh_hook_function, majh_hook_context, majh_module_name)".
" VALUES (?, ?, ?)"
)->execute(array($this->hook_function, $this->hook_context, $hsubscriber));
}
} | php | public function subscribe($hsubscriber){
if(HookProvider::getInstance()->isModuleOperational()){
Database::prepare(
"INSERT IGNORE INTO `##maj_hooks` (majh_hook_function, majh_hook_context, majh_module_name)".
" VALUES (?, ?, ?)"
)->execute(array($this->hook_function, $this->hook_context, $hsubscriber));
}
} | [
"public",
"function",
"subscribe",
"(",
"$",
"hsubscriber",
")",
"{",
"if",
"(",
"HookProvider",
"::",
"getInstance",
"(",
")",
"->",
"isModuleOperational",
"(",
")",
")",
"{",
"Database",
"::",
"prepare",
"(",
"\"INSERT IGNORE INTO `##maj_hooks` (majh_hook_function... | Subscribe a class implementing HookSubscriberInterface to the Hook
The Hook is by default enabled.
@param string $hsubscriber Name of the subscriber module | [
"Subscribe",
"a",
"class",
"implementing",
"HookSubscriberInterface",
"to",
"the",
"Hook",
"The",
"Hook",
"is",
"by",
"default",
"enabled",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Hook/Hook.php#L50-L57 | train |
jon48/webtrees-lib | src/Webtrees/Hook/Hook.php | Hook.setPriority | public function setPriority($hsubscriber, $priority){
if(HookProvider::getInstance()->isModuleOperational()){
Database::prepare(
"UPDATE `##maj_hooks`".
" SET majh_module_priority=?".
" WHERE majh_hook_function=?".
" AND majh_hook_context=?".
" AND majh_module_name=?"
)->execute(array($priority, $this->hook_function, $this->hook_context, $hsubscriber));
}
} | php | public function setPriority($hsubscriber, $priority){
if(HookProvider::getInstance()->isModuleOperational()){
Database::prepare(
"UPDATE `##maj_hooks`".
" SET majh_module_priority=?".
" WHERE majh_hook_function=?".
" AND majh_hook_context=?".
" AND majh_module_name=?"
)->execute(array($priority, $this->hook_function, $this->hook_context, $hsubscriber));
}
} | [
"public",
"function",
"setPriority",
"(",
"$",
"hsubscriber",
",",
"$",
"priority",
")",
"{",
"if",
"(",
"HookProvider",
"::",
"getInstance",
"(",
")",
"->",
"isModuleOperational",
"(",
")",
")",
"{",
"Database",
"::",
"prepare",
"(",
"\"UPDATE `##maj_hooks`\"... | Define the priority for execution of the Hook for the specific HookSubscriberInterface
@param string $hsubscriber Name of the subscriber module
@param int $priority Priority of execution | [
"Define",
"the",
"priority",
"for",
"execution",
"of",
"the",
"Hook",
"for",
"the",
"specific",
"HookSubscriberInterface"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Hook/Hook.php#L65-L75 | train |
jon48/webtrees-lib | src/Webtrees/Hook/Hook.php | Hook.executeOnlyFor | public function executeOnlyFor(array $module_names) {
$result = array();
if(HookProvider::getInstance()->isModuleOperational()){
$params = func_get_args();
array_shift($params);
foreach ($module_names as $module_name) {
if($module = Module::getModuleByName($module_name)) {
$result[] = call_user_func_array(array($module, $this->hook_function), $params);
}
}
}
return $result;
} | php | public function executeOnlyFor(array $module_names) {
$result = array();
if(HookProvider::getInstance()->isModuleOperational()){
$params = func_get_args();
array_shift($params);
foreach ($module_names as $module_name) {
if($module = Module::getModuleByName($module_name)) {
$result[] = call_user_func_array(array($module, $this->hook_function), $params);
}
}
}
return $result;
} | [
"public",
"function",
"executeOnlyFor",
"(",
"array",
"$",
"module_names",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"if",
"(",
"HookProvider",
"::",
"getInstance",
"(",
")",
"->",
"isModuleOperational",
"(",
")",
")",
"{",
"$",
"params",
"="... | Return the resuls of the execution of the hook function for a defined list of modules, only for those enabled.
@param string[] $module_names List of Modules to execute
@return array Results of the hook executions | [
"Return",
"the",
"resuls",
"of",
"the",
"execution",
"of",
"the",
"hook",
"function",
"for",
"a",
"defined",
"list",
"of",
"modules",
"only",
"for",
"those",
"enabled",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Hook/Hook.php#L139-L151 | train |
jon48/webtrees-lib | src/Webtrees/Hook/Hook.php | Hook.execute | public function execute(){
$result = array();
if(HookProvider::getInstance()->isModuleOperational()){
$params = func_get_args();
$sqlquery = '';
$sqlparams = array($this->hook_function);
if($this->hook_context != 'all') {
$sqlparams = array($this->hook_function, $this->hook_context);
$sqlquery = " OR majh_hook_context=?";
}
$module_names=Database::prepare(
"SELECT majh_module_name AS module, majh_module_priority AS priority FROM `##maj_hooks`".
" WHERE majh_hook_function = ? AND (majh_hook_context='all'".$sqlquery.") AND majh_status='enabled'".
" ORDER BY majh_module_priority ASC, module ASC"
)->execute($sqlparams)->fetchAssoc();
asort($module_names);
array_unshift($params, array_keys($module_names));
$result = call_user_func_array(array(&$this, 'executeOnlyFor'), $params);
}
return $result;
} | php | public function execute(){
$result = array();
if(HookProvider::getInstance()->isModuleOperational()){
$params = func_get_args();
$sqlquery = '';
$sqlparams = array($this->hook_function);
if($this->hook_context != 'all') {
$sqlparams = array($this->hook_function, $this->hook_context);
$sqlquery = " OR majh_hook_context=?";
}
$module_names=Database::prepare(
"SELECT majh_module_name AS module, majh_module_priority AS priority FROM `##maj_hooks`".
" WHERE majh_hook_function = ? AND (majh_hook_context='all'".$sqlquery.") AND majh_status='enabled'".
" ORDER BY majh_module_priority ASC, module ASC"
)->execute($sqlparams)->fetchAssoc();
asort($module_names);
array_unshift($params, array_keys($module_names));
$result = call_user_func_array(array(&$this, 'executeOnlyFor'), $params);
}
return $result;
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"if",
"(",
"HookProvider",
"::",
"getInstance",
"(",
")",
"->",
"isModuleOperational",
"(",
")",
")",
"{",
"$",
"params",
"=",
"func_get_args",
"(",
")",
";",
... | Return the results of the execution of the hook function for all subscribed and enabled modules, in the order defined by their priority.
Parameters can be passed if the hook requires them.
@return array Results of the hook executions | [
"Return",
"the",
"results",
"of",
"the",
"execution",
"of",
"the",
"hook",
"function",
"for",
"all",
"subscribed",
"and",
"enabled",
"modules",
"in",
"the",
"order",
"defined",
"by",
"their",
"priority",
".",
"Parameters",
"can",
"be",
"passed",
"if",
"the",... | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Hook/Hook.php#L159-L179 | train |
jon48/webtrees-lib | src/Webtrees/Hook/Hook.php | Hook.getNumberActiveModules | public function getNumberActiveModules(){
if(HookProvider::getInstance()->isModuleOperational()){
$sqlquery = '';
$sqlparams = array($this->hook_function);
if($this->hook_context != 'all') {
$sqlparams = array($this->hook_function, $this->hook_context);
$sqlquery = " OR majh_hook_context=?";
}
$module_names=Database::prepare(
"SELECT majh_module_name AS modules FROM `##maj_hooks`".
" WHERE majh_hook_function = ? AND (majh_hook_context='all'".$sqlquery.") AND majh_status='enabled'"
)->execute($sqlparams)->fetchOneColumn();
return count($module_names);
}
return 0;
} | php | public function getNumberActiveModules(){
if(HookProvider::getInstance()->isModuleOperational()){
$sqlquery = '';
$sqlparams = array($this->hook_function);
if($this->hook_context != 'all') {
$sqlparams = array($this->hook_function, $this->hook_context);
$sqlquery = " OR majh_hook_context=?";
}
$module_names=Database::prepare(
"SELECT majh_module_name AS modules FROM `##maj_hooks`".
" WHERE majh_hook_function = ? AND (majh_hook_context='all'".$sqlquery.") AND majh_status='enabled'"
)->execute($sqlparams)->fetchOneColumn();
return count($module_names);
}
return 0;
} | [
"public",
"function",
"getNumberActiveModules",
"(",
")",
"{",
"if",
"(",
"HookProvider",
"::",
"getInstance",
"(",
")",
"->",
"isModuleOperational",
"(",
")",
")",
"{",
"$",
"sqlquery",
"=",
"''",
";",
"$",
"sqlparams",
"=",
"array",
"(",
"$",
"this",
"... | Returns the number of active modules linked to a hook
@return int Number of active modules | [
"Returns",
"the",
"number",
"of",
"active",
"modules",
"linked",
"to",
"a",
"hook"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Hook/Hook.php#L186-L201 | train |
jon48/webtrees-lib | src/Webtrees/Module/CertificatesModule.php | CertificatesModule.getProvider | public function getProvider() {
if(!$this->provider) {
$root_path = $this->getSetting('MAJ_CERT_ROOTDIR', 'certificates/');
$this->provider = new CertificateFileProvider($root_path, Globals::getTree());
}
return $this->provider;
} | php | public function getProvider() {
if(!$this->provider) {
$root_path = $this->getSetting('MAJ_CERT_ROOTDIR', 'certificates/');
$this->provider = new CertificateFileProvider($root_path, Globals::getTree());
}
return $this->provider;
} | [
"public",
"function",
"getProvider",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"provider",
")",
"{",
"$",
"root_path",
"=",
"$",
"this",
"->",
"getSetting",
"(",
"'MAJ_CERT_ROOTDIR'",
",",
"'certificates/'",
")",
";",
"$",
"this",
"->",
"provider... | Returns the default Certificate File Provider, as configured in the module
@return \MyArtJaub\Webtrees\Module\Certificates\Model\CertificateProviderInterface | [
"Returns",
"the",
"default",
"Certificate",
"File",
"Provider",
"as",
"configured",
"in",
"the",
"module"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/CertificatesModule.php#L241-L247 | train |
jon48/webtrees-lib | src/Webtrees/Module/CertificatesModule.php | CertificatesModule.getDisplay_ACT | protected function getDisplay_ACT(Certificate $certificate, $sid = null){
$html = '';
if($certificate){
$certificate->setSource($sid);
$html = $certificate->displayImage('icon');
}
return $html;
} | php | protected function getDisplay_ACT(Certificate $certificate, $sid = null){
$html = '';
if($certificate){
$certificate->setSource($sid);
$html = $certificate->displayImage('icon');
}
return $html;
} | [
"protected",
"function",
"getDisplay_ACT",
"(",
"Certificate",
"$",
"certificate",
",",
"$",
"sid",
"=",
"null",
")",
"{",
"$",
"html",
"=",
"''",
";",
"if",
"(",
"$",
"certificate",
")",
"{",
"$",
"certificate",
"->",
"setSource",
"(",
"$",
"sid",
")"... | Return the HTML code for custom simple tag _ACT
@param Certificate $certificatePath Certificate (as per the GEDCOM)
@param string|null $sid Linked Source ID, if it exists | [
"Return",
"the",
"HTML",
"code",
"for",
"custom",
"simple",
"tag",
"_ACT"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/CertificatesModule.php#L256-L263 | train |
g4code/log | src/Debug.php | Debug.handlerShutdown | public static function handlerShutdown()
{
$error = error_get_last();
if($error !== NULL) {
self::handlerError($error['type'], '[SHUTDOWN] ' . $error['message'], $error['file'], $error['line']);
}
} | php | public static function handlerShutdown()
{
$error = error_get_last();
if($error !== NULL) {
self::handlerError($error['type'], '[SHUTDOWN] ' . $error['message'], $error['file'], $error['line']);
}
} | [
"public",
"static",
"function",
"handlerShutdown",
"(",
")",
"{",
"$",
"error",
"=",
"error_get_last",
"(",
")",
";",
"if",
"(",
"$",
"error",
"!==",
"NULL",
")",
"{",
"self",
"::",
"handlerError",
"(",
"$",
"error",
"[",
"'type'",
"]",
",",
"'[SHUTDOW... | Error handler for fatal errors
@return void | [
"Error",
"handler",
"for",
"fatal",
"errors"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Debug.php#L171-L177 | train |
g4code/log | src/Debug.php | Debug._writeLog | private static function _writeLog($filename, $msg, $addTime = true)
{
// preppend details
if($addTime) {
$msg = self::formatHeaderWithTime() . $msg;
}
if(DI::has('BufferOptions')) {
$options = DI::get('BufferConnectionOptions');
$callback = function($data) use ($filename) {
Writer::writeLogVerbose($filename, implode("\n\n", $data) . "\n\n");
};
// just to be on safe side, set max size to 500, that is reasonable number
$maxSize = 500;
$size = isset($options['size']) && is_int($options['size']) && $options['size'] > 0 && $options['size'] < $maxSize
? $options['size']
: $maxSize;
$buffer = new Buffer($filename, Buffer::ADAPTER_REDIS, $size, $callback, $options);
$buffer->add($msg);
} else {
Writer::writeLogVerbose($filename, $msg);
}
} | php | private static function _writeLog($filename, $msg, $addTime = true)
{
// preppend details
if($addTime) {
$msg = self::formatHeaderWithTime() . $msg;
}
if(DI::has('BufferOptions')) {
$options = DI::get('BufferConnectionOptions');
$callback = function($data) use ($filename) {
Writer::writeLogVerbose($filename, implode("\n\n", $data) . "\n\n");
};
// just to be on safe side, set max size to 500, that is reasonable number
$maxSize = 500;
$size = isset($options['size']) && is_int($options['size']) && $options['size'] > 0 && $options['size'] < $maxSize
? $options['size']
: $maxSize;
$buffer = new Buffer($filename, Buffer::ADAPTER_REDIS, $size, $callback, $options);
$buffer->add($msg);
} else {
Writer::writeLogVerbose($filename, $msg);
}
} | [
"private",
"static",
"function",
"_writeLog",
"(",
"$",
"filename",
",",
"$",
"msg",
",",
"$",
"addTime",
"=",
"true",
")",
"{",
"// preppend details",
"if",
"(",
"$",
"addTime",
")",
"{",
"$",
"msg",
"=",
"self",
"::",
"formatHeaderWithTime",
"(",
")",
... | Write log with buffer support
@param string $filename
@param string $msg
@return void | [
"Write",
"log",
"with",
"buffer",
"support"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Debug.php#L185-L213 | train |
g4code/log | src/Debug.php | Debug._parseException | private static function _parseException(\Exception $e, $plain_text = false)
{
$exMsg = $e->getMessage();
$exCode = $e->getCode();
$exLine = $e->getLine();
$exFile = basename($e->getFile());
$exTrace = $e->getTrace();
$trace = '';
foreach ($exTrace as $key => $row) {
$trace .= '<span class="traceLine">#' . ($key++) . ' ';
if (!empty($row['function'])) {
$trace .= "<b>";
if (!empty($row['class'])) {
$trace .= $row['class'] . $row['type'];
}
$trace .= "{$row['function']}</b>()";
}
if (!empty($row['file'])) {
$trace .= " | LINE: <b>{$row['line']}</b> | FILE: <u>" . basename($row['file']) . '</u>';
}
$trace .= "</span>\n";
}
$msg = "<em style='font-size:larger;'>{$exMsg}</em> (code: {$exCode})<br />\nLINE: <b>{$exLine}</b>\nFILE: <u>{$exFile}</u>";
$parsed = sprintf("<pre>\n<p style='%s'>\n<strong>EXCEPTION:</strong><br />%s\n%s\n</p>\n</pre>\n\n", self::getFormattedCss(), $msg, $trace);
return $plain_text ? str_replace(array("\t"), '', strip_tags($parsed)) : $parsed;
} | php | private static function _parseException(\Exception $e, $plain_text = false)
{
$exMsg = $e->getMessage();
$exCode = $e->getCode();
$exLine = $e->getLine();
$exFile = basename($e->getFile());
$exTrace = $e->getTrace();
$trace = '';
foreach ($exTrace as $key => $row) {
$trace .= '<span class="traceLine">#' . ($key++) . ' ';
if (!empty($row['function'])) {
$trace .= "<b>";
if (!empty($row['class'])) {
$trace .= $row['class'] . $row['type'];
}
$trace .= "{$row['function']}</b>()";
}
if (!empty($row['file'])) {
$trace .= " | LINE: <b>{$row['line']}</b> | FILE: <u>" . basename($row['file']) . '</u>';
}
$trace .= "</span>\n";
}
$msg = "<em style='font-size:larger;'>{$exMsg}</em> (code: {$exCode})<br />\nLINE: <b>{$exLine}</b>\nFILE: <u>{$exFile}</u>";
$parsed = sprintf("<pre>\n<p style='%s'>\n<strong>EXCEPTION:</strong><br />%s\n%s\n</p>\n</pre>\n\n", self::getFormattedCss(), $msg, $trace);
return $plain_text ? str_replace(array("\t"), '', strip_tags($parsed)) : $parsed;
} | [
"private",
"static",
"function",
"_parseException",
"(",
"\\",
"Exception",
"$",
"e",
",",
"$",
"plain_text",
"=",
"false",
")",
"{",
"$",
"exMsg",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"$",
"exCode",
"=",
"$",
"e",
"->",
"getCode",
"(",
... | Parses exceptions into human readable format + html styling
@param Exception $e Exception object that's being parsed
@param bool $plain_text flag to return formated exception, or plain text
@todo: finish plain text implemntation
@return string | [
"Parses",
"exceptions",
"into",
"human",
"readable",
"format",
"+",
"html",
"styling"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Debug.php#L225-L258 | train |
g4code/log | src/Debug.php | Debug.formatRequestData | public static function formatRequestData($asString = true)
{
$fromServer = array(
'REQUEST_URI',
'REQUEST_METHOD',
'HTTP_REFERER',
'QUERY_STRING',
'HTTP_USER_AGENT',
'REMOTE_ADDR',
);
if($asString) {
$s = "\n\n";
$s .= isset($_REQUEST)? "REQUEST: " . print_r($_REQUEST, true) . PHP_EOL : '';
foreach ($fromServer as $item) {
$s .= isset($_SERVER[$item]) ? "{$item}: {$_SERVER[$item]}\n" : '';
}
} else {
$s = array(
'REQUEST' => $_REQUEST,
'SERVER' => $_SERVER,
);
}
return $s;
} | php | public static function formatRequestData($asString = true)
{
$fromServer = array(
'REQUEST_URI',
'REQUEST_METHOD',
'HTTP_REFERER',
'QUERY_STRING',
'HTTP_USER_AGENT',
'REMOTE_ADDR',
);
if($asString) {
$s = "\n\n";
$s .= isset($_REQUEST)? "REQUEST: " . print_r($_REQUEST, true) . PHP_EOL : '';
foreach ($fromServer as $item) {
$s .= isset($_SERVER[$item]) ? "{$item}: {$_SERVER[$item]}\n" : '';
}
} else {
$s = array(
'REQUEST' => $_REQUEST,
'SERVER' => $_SERVER,
);
}
return $s;
} | [
"public",
"static",
"function",
"formatRequestData",
"(",
"$",
"asString",
"=",
"true",
")",
"{",
"$",
"fromServer",
"=",
"array",
"(",
"'REQUEST_URI'",
",",
"'REQUEST_METHOD'",
",",
"'HTTP_REFERER'",
",",
"'QUERY_STRING'",
",",
"'HTTP_USER_AGENT'",
",",
"'REMOTE_... | Returns all request data formated into string
@return string | [
"Returns",
"all",
"request",
"data",
"formated",
"into",
"string"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Debug.php#L264-L289 | train |
g4code/log | src/Debug.php | Debug._skipFormating | private static function _skipFormating()
{
return false;
if(null !== self::$_isAjaxOrCli) {
return self::$_isAjaxOrCli;
}
self::$_isAjaxOrCli =
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
|| (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']));
return self::$_isAjaxOrCli;
} | php | private static function _skipFormating()
{
return false;
if(null !== self::$_isAjaxOrCli) {
return self::$_isAjaxOrCli;
}
self::$_isAjaxOrCli =
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
|| (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']));
return self::$_isAjaxOrCli;
} | [
"private",
"static",
"function",
"_skipFormating",
"(",
")",
"{",
"return",
"false",
";",
"if",
"(",
"null",
"!==",
"self",
"::",
"$",
"_isAjaxOrCli",
")",
"{",
"return",
"self",
"::",
"$",
"_isAjaxOrCli",
";",
"}",
"self",
"::",
"$",
"_isAjaxOrCli",
"="... | Check if request is ajax or cli and skip formating
@return bool | [
"Check",
"if",
"request",
"is",
"ajax",
"or",
"cli",
"and",
"skip",
"formating"
] | 909d06503abbb21ac6c79a61d1b2b1bd89eb26d7 | https://github.com/g4code/log/blob/909d06503abbb21ac6c79a61d1b2b1bd89eb26d7/src/Debug.php#L306-L319 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getRootIndi | public function getRootIndi() {
$root_indi_id = $this->getRootIndiId();
if(!empty($root_indi_id)) {
return Individual::getInstance($root_indi_id, $this->tree);
}
return null;
} | php | public function getRootIndi() {
$root_indi_id = $this->getRootIndiId();
if(!empty($root_indi_id)) {
return Individual::getInstance($root_indi_id, $this->tree);
}
return null;
} | [
"public",
"function",
"getRootIndi",
"(",
")",
"{",
"$",
"root_indi_id",
"=",
"$",
"this",
"->",
"getRootIndiId",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"root_indi_id",
")",
")",
"{",
"return",
"Individual",
"::",
"getInstance",
"(",
"$",
"r... | Return the root individual for the reference tree and user.
@return Individual Individual | [
"Return",
"the",
"root",
"individual",
"for",
"the",
"reference",
"tree",
"and",
"user",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L128-L134 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.deleteAll | public function deleteAll() {
if(!$this->is_setup) return;
Database::prepare(
'DELETE FROM `##maj_sosa`'.
' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id ')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId()
));
} | php | public function deleteAll() {
if(!$this->is_setup) return;
Database::prepare(
'DELETE FROM `##maj_sosa`'.
' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id ')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId()
));
} | [
"public",
"function",
"deleteAll",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
";",
"Database",
"::",
"prepare",
"(",
"'DELETE FROM `##maj_sosa`'",
".",
"' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id '",
")",
"->",
"ex... | Remove all Sosa entries related to the gedcom file and user | [
"Remove",
"all",
"Sosa",
"entries",
"related",
"to",
"the",
"gedcom",
"file",
"and",
"user"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L143-L152 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.deleteAncestors | public function deleteAncestors($sosa) {
if(!$this->is_setup) return;
$gen = Functions::getGeneration($sosa);
Database::prepare(
'DELETE FROM `##maj_sosa`'.
' WHERE majs_gedcom_id=:tree_id and majs_user_id = :user_id' .
' AND majs_gen >= :gen' .
' AND FLOOR(majs_sosa / (POW(2, (majs_gen - :gen)))) = :sosa'
)->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen,
'sosa' => $sosa
));
} | php | public function deleteAncestors($sosa) {
if(!$this->is_setup) return;
$gen = Functions::getGeneration($sosa);
Database::prepare(
'DELETE FROM `##maj_sosa`'.
' WHERE majs_gedcom_id=:tree_id and majs_user_id = :user_id' .
' AND majs_gen >= :gen' .
' AND FLOOR(majs_sosa / (POW(2, (majs_gen - :gen)))) = :sosa'
)->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen,
'sosa' => $sosa
));
} | [
"public",
"function",
"deleteAncestors",
"(",
"$",
"sosa",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
";",
"$",
"gen",
"=",
"Functions",
"::",
"getGeneration",
"(",
"$",
"sosa",
")",
";",
"Database",
"::",
"prepare",
"(",
... | Remove all ancestors of a sosa number
@param int $sosa | [
"Remove",
"all",
"ancestors",
"of",
"a",
"sosa",
"number"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L159-L173 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getAllSosaWithGenerations | public function getAllSosaWithGenerations(){
if(!$this->is_setup) return array();
return Database::prepare(
'SELECT majs_i_id AS indi,' .
' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations' .
' FROM `##maj_sosa`' .
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id' .
' GROUP BY majs_i_id'
)->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId()
))->fetchAssoc();
} | php | public function getAllSosaWithGenerations(){
if(!$this->is_setup) return array();
return Database::prepare(
'SELECT majs_i_id AS indi,' .
' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations' .
' FROM `##maj_sosa`' .
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id' .
' GROUP BY majs_i_id'
)->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId()
))->fetchAssoc();
} | [
"public",
"function",
"getAllSosaWithGenerations",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"array",
"(",
")",
";",
"return",
"Database",
"::",
"prepare",
"(",
"'SELECT majs_i_id AS indi,'",
".",
"' GROUP_CONCAT(DISTINCT majs_ge... | Return the list of all sosas, with the generations it belongs to
@return array Associative array of Sosa ancestors, with their generation, comma separated | [
"Return",
"the",
"list",
"of",
"all",
"sosas",
"with",
"the",
"generations",
"it",
"belongs",
"to"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L263-L275 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getSosaListAtGeneration | public function getSosaListAtGeneration($gen){
if(!$this->is_setup) return array();
if(!$this->sosa_list_by_gen)
$this->sosa_list_by_gen = array();
if($gen){
if(!isset($this->sosa_list_by_gen[$gen])){
$this->sosa_list_by_gen[$gen] = Database::prepare(
'SELECT majs_sosa AS sosa, majs_i_id AS indi'.
' FROM `##maj_sosa`'.
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
' AND majs_gen = :gen'.
' ORDER BY majs_sosa ASC')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))
->fetchAssoc();
}
return $this->sosa_list_by_gen[$gen];
}
return array();
} | php | public function getSosaListAtGeneration($gen){
if(!$this->is_setup) return array();
if(!$this->sosa_list_by_gen)
$this->sosa_list_by_gen = array();
if($gen){
if(!isset($this->sosa_list_by_gen[$gen])){
$this->sosa_list_by_gen[$gen] = Database::prepare(
'SELECT majs_sosa AS sosa, majs_i_id AS indi'.
' FROM `##maj_sosa`'.
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
' AND majs_gen = :gen'.
' ORDER BY majs_sosa ASC')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))
->fetchAssoc();
}
return $this->sosa_list_by_gen[$gen];
}
return array();
} | [
"public",
"function",
"getSosaListAtGeneration",
"(",
"$",
"gen",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"array",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"sosa_list_by_gen",
")",
"$",
"this",
"->",
"sosa_list_... | Get an associative array of Sosa individuals in generation G. Keys are Sosa numbers, values individuals.
@param number $gen Generation
@return array Array of Sosa individuals | [
"Get",
"an",
"associative",
"array",
"of",
"Sosa",
"individuals",
"in",
"generation",
"G",
".",
"Keys",
"are",
"Sosa",
"numbers",
"values",
"individuals",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L283-L306 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getFamilySosaListAtGeneration | public function getFamilySosaListAtGeneration($gen){
if(!$this->is_setup) return array();
if(!$this->sosa_fam_list_by_gen)
$this->sosa_fam_list_by_gen = array();
if($gen){
if(!isset($this->sosa_fam_list_by_gen[$gen])){
$this->sosa_fam_list_by_gen[$gen] = Database::prepare(
'SELECT s1.majs_sosa AS sosa, f_id AS fam'.
' FROM `##families`'.
' INNER JOIN `##maj_sosa` AS s1 ON (`##families`.f_husb = s1.majs_i_id AND `##families`.f_file = s1.majs_gedcom_id)'.
' INNER JOIN `##maj_sosa` AS s2 ON (`##families`.f_wife = s2.majs_i_id AND `##families`.f_file = s2.majs_gedcom_id)'.
' WHERE s1.majs_sosa + 1 = s2.majs_sosa'.
' AND s1.majs_gedcom_id= :tree_id AND s1.majs_user_id=:user_id'.
' AND s2.majs_gedcom_id= :tree_id AND s2.majs_user_id=:user_id'.
' AND s1.majs_gen = :gen'.
' ORDER BY s1.majs_sosa ASC'
)
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))
->fetchAssoc();
}
return $this->sosa_fam_list_by_gen[$gen];
}
return array();
} | php | public function getFamilySosaListAtGeneration($gen){
if(!$this->is_setup) return array();
if(!$this->sosa_fam_list_by_gen)
$this->sosa_fam_list_by_gen = array();
if($gen){
if(!isset($this->sosa_fam_list_by_gen[$gen])){
$this->sosa_fam_list_by_gen[$gen] = Database::prepare(
'SELECT s1.majs_sosa AS sosa, f_id AS fam'.
' FROM `##families`'.
' INNER JOIN `##maj_sosa` AS s1 ON (`##families`.f_husb = s1.majs_i_id AND `##families`.f_file = s1.majs_gedcom_id)'.
' INNER JOIN `##maj_sosa` AS s2 ON (`##families`.f_wife = s2.majs_i_id AND `##families`.f_file = s2.majs_gedcom_id)'.
' WHERE s1.majs_sosa + 1 = s2.majs_sosa'.
' AND s1.majs_gedcom_id= :tree_id AND s1.majs_user_id=:user_id'.
' AND s2.majs_gedcom_id= :tree_id AND s2.majs_user_id=:user_id'.
' AND s1.majs_gen = :gen'.
' ORDER BY s1.majs_sosa ASC'
)
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))
->fetchAssoc();
}
return $this->sosa_fam_list_by_gen[$gen];
}
return array();
} | [
"public",
"function",
"getFamilySosaListAtGeneration",
"(",
"$",
"gen",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"array",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"sosa_fam_list_by_gen",
")",
"$",
"this",
"->",
"... | Get an associative array of Sosa families in generation G. Keys are Sosa numbers for the husband, values families.
@param number $gen Generation
@return array Array of Sosa families | [
"Get",
"an",
"associative",
"array",
"of",
"Sosa",
"families",
"in",
"generation",
"G",
".",
"Keys",
"are",
"Sosa",
"numbers",
"for",
"the",
"husband",
"values",
"families",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L314-L342 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getMissingSosaListAtGeneration | public function getMissingSosaListAtGeneration($gen){
if(!$this->is_setup) return array();
if($gen){
return $this->sosa_list_by_gen[$gen] = Database::prepare(
'SELECT schild.majs_sosa sosa, schild.majs_i_id indi, sfat.majs_sosa IS NOT NULL has_father, smot.majs_sosa IS NOT NULL has_mother'.
' FROM `##maj_sosa` schild'.
' LEFT JOIN `##maj_sosa` sfat ON ((schild.majs_sosa * 2) = sfat.majs_sosa AND schild.majs_gedcom_id = sfat.majs_gedcom_id AND schild.majs_user_id = sfat.majs_user_id)'.
' LEFT JOIN `##maj_sosa` smot ON ((schild.majs_sosa * 2 + 1) = smot.majs_sosa AND schild.majs_gedcom_id = smot.majs_gedcom_id AND schild.majs_user_id = smot.majs_user_id)'.
' WHERE schild.majs_gedcom_id = :tree_id AND schild.majs_user_id = :user_id'.
' AND schild.majs_gen = :gen'.
' AND (sfat.majs_sosa IS NULL OR smot.majs_sosa IS NULL)'.
' ORDER BY schild.majs_sosa ASC')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen - 1
))->fetchAll(\PDO::FETCH_ASSOC);
}
return array();
} | php | public function getMissingSosaListAtGeneration($gen){
if(!$this->is_setup) return array();
if($gen){
return $this->sosa_list_by_gen[$gen] = Database::prepare(
'SELECT schild.majs_sosa sosa, schild.majs_i_id indi, sfat.majs_sosa IS NOT NULL has_father, smot.majs_sosa IS NOT NULL has_mother'.
' FROM `##maj_sosa` schild'.
' LEFT JOIN `##maj_sosa` sfat ON ((schild.majs_sosa * 2) = sfat.majs_sosa AND schild.majs_gedcom_id = sfat.majs_gedcom_id AND schild.majs_user_id = sfat.majs_user_id)'.
' LEFT JOIN `##maj_sosa` smot ON ((schild.majs_sosa * 2 + 1) = smot.majs_sosa AND schild.majs_gedcom_id = smot.majs_gedcom_id AND schild.majs_user_id = smot.majs_user_id)'.
' WHERE schild.majs_gedcom_id = :tree_id AND schild.majs_user_id = :user_id'.
' AND schild.majs_gen = :gen'.
' AND (sfat.majs_sosa IS NULL OR smot.majs_sosa IS NULL)'.
' ORDER BY schild.majs_sosa ASC')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen - 1
))->fetchAll(\PDO::FETCH_ASSOC);
}
return array();
} | [
"public",
"function",
"getMissingSosaListAtGeneration",
"(",
"$",
"gen",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"array",
"(",
")",
";",
"if",
"(",
"$",
"gen",
")",
"{",
"return",
"$",
"this",
"->",
"sosa_list_by_gen",
"... | Get an associative array of Sosa individuals in generation G who are missing parents. Keys are Sosa numbers, values individuals.
@param number $gen Generation
@return array Array of Sosa individuals | [
"Get",
"an",
"associative",
"array",
"of",
"Sosa",
"individuals",
"in",
"generation",
"G",
"who",
"are",
"missing",
"parents",
".",
"Keys",
"are",
"Sosa",
"numbers",
"values",
"individuals",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L350-L369 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getTotalIndividuals | public function getTotalIndividuals() {
if(!$this->is_setup) return 0;
return Database::prepare(
'SELECT COUNT(*) FROM `##individuals`' .
' WHERE i_file = :tree_id')
->execute(array('tree_id' => $this->tree->getTreeId()))
->fetchOne() ?: 0;
} | php | public function getTotalIndividuals() {
if(!$this->is_setup) return 0;
return Database::prepare(
'SELECT COUNT(*) FROM `##individuals`' .
' WHERE i_file = :tree_id')
->execute(array('tree_id' => $this->tree->getTreeId()))
->fetchOne() ?: 0;
} | [
"public",
"function",
"getTotalIndividuals",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"0",
";",
"return",
"Database",
"::",
"prepare",
"(",
"'SELECT COUNT(*) FROM `##individuals`'",
".",
"' WHERE i_file = :tree_id'",
")",
"->",
... | How many individuals exist in the tree.
@return int | [
"How",
"many",
"individuals",
"exist",
"in",
"the",
"tree",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L414-L421 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getSosaCount | public function getSosaCount(){
if(!$this->is_setup) return 0;
return Database::prepare(
'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId()
))->fetchOne() ?: 0;
} | php | public function getSosaCount(){
if(!$this->is_setup) return 0;
return Database::prepare(
'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId()
))->fetchOne() ?: 0;
} | [
"public",
"function",
"getSosaCount",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"0",
";",
"return",
"Database",
"::",
"prepare",
"(",
"'SELECT COUNT(majs_sosa) FROM `##maj_sosa`'",
".",
"' WHERE majs_gedcom_id=:tree_id AND majs_user_... | Get the total Sosa count for all generations
@return number Number of Sosas | [
"Get",
"the",
"total",
"Sosa",
"count",
"for",
"all",
"generations"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L428-L437 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getDifferentSosaCountUpToGeneration | public function getDifferentSosaCountUpToGeneration($gen){
if(!$this->is_setup) return 0;
return Database::prepare(
'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
' AND majs_gen <= :gen')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))->fetchOne() ?: 0;
} | php | public function getDifferentSosaCountUpToGeneration($gen){
if(!$this->is_setup) return 0;
return Database::prepare(
'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
' AND majs_gen <= :gen')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))->fetchOne() ?: 0;
} | [
"public",
"function",
"getDifferentSosaCountUpToGeneration",
"(",
"$",
"gen",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
"0",
";",
"return",
"Database",
"::",
"prepare",
"(",
"'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`'",
".",
... | Get the number of distinct Sosa individual up to a specific generation.
@param number $gen Generation
@return number Number of distinct Sosa individuals up to generation | [
"Get",
"the",
"number",
"of",
"distinct",
"Sosa",
"individual",
"up",
"to",
"a",
"specific",
"generation",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L499-L510 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getMeanGenerationTime | public function getMeanGenerationTime(){
if(!$this->is_setup) return;
if(!$this->statistics_tab){
$this->getStatisticsByGeneration();
}
//Linear regression on x=generation and y=birthdate
$sum_xy = 0;
$sum_x=0;
$sum_y=0;
$sum_x2=0;
$n=count($this->statistics_tab);
foreach($this->statistics_tab as $gen=>$stats){
$sum_xy+=$gen*$stats['avgBirth'];
$sum_x+=$gen;
$sum_y+=$stats['avgBirth'];
$sum_x2+=$gen*$gen;
}
$denom=($n*$sum_x2)-($sum_x*$sum_x);
if($denom!=0){
return -(($n*$sum_xy)-($sum_x*$sum_y))/($denom);
}
return null;
} | php | public function getMeanGenerationTime(){
if(!$this->is_setup) return;
if(!$this->statistics_tab){
$this->getStatisticsByGeneration();
}
//Linear regression on x=generation and y=birthdate
$sum_xy = 0;
$sum_x=0;
$sum_y=0;
$sum_x2=0;
$n=count($this->statistics_tab);
foreach($this->statistics_tab as $gen=>$stats){
$sum_xy+=$gen*$stats['avgBirth'];
$sum_x+=$gen;
$sum_y+=$stats['avgBirth'];
$sum_x2+=$gen*$gen;
}
$denom=($n*$sum_x2)-($sum_x*$sum_x);
if($denom!=0){
return -(($n*$sum_xy)-($sum_x*$sum_y))/($denom);
}
return null;
} | [
"public",
"function",
"getMeanGenerationTime",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
")",
"return",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"statistics_tab",
")",
"{",
"$",
"this",
"->",
"getStatisticsByGeneration",
"(",
")",
";",... | Get the mean generation time, based on a linear regression of birth years and generations
@return number|NULL Mean generation time | [
"Get",
"the",
"mean",
"generation",
"time",
"based",
"on",
"a",
"linear",
"regression",
"of",
"birth",
"years",
"and",
"generations"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L542-L564 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaProvider.php | SosaProvider.getAncestorDispersionForGen | public function getAncestorDispersionForGen($gen) {
if(!$this->is_setup || $gen > 11) return array(); // Going further than 11 gen will be out of range in the query
return Database::prepare(
'SELECT branches, count(i_id)'.
' FROM ('.
' SELECT i_id,'.
' CASE'.
' WHEN CEIL(LOG2(SUM(branch))) = LOG2(SUM(branch)) THEN SUM(branch)'.
' ELSE -1'. // We put all ancestors shared between some branches in the same bucket
' END branches'.
' FROM ('.
' SELECT DISTINCT majs_i_id i_id,'.
' POW(2, FLOOR(majs_sosa / POW(2, (majs_gen - :gen))) - POW(2, :gen -1)) branch'.
' FROM `##maj_sosa`'.
' WHERE majs_gedcom_id = :tree_id AND majs_user_id = :user_id'.
' AND majs_gen >= :gen'.
' ) indistat'.
' GROUP BY i_id'.
') grouped'.
' GROUP BY branches')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))->fetchAssoc() ?: array();
} | php | public function getAncestorDispersionForGen($gen) {
if(!$this->is_setup || $gen > 11) return array(); // Going further than 11 gen will be out of range in the query
return Database::prepare(
'SELECT branches, count(i_id)'.
' FROM ('.
' SELECT i_id,'.
' CASE'.
' WHEN CEIL(LOG2(SUM(branch))) = LOG2(SUM(branch)) THEN SUM(branch)'.
' ELSE -1'. // We put all ancestors shared between some branches in the same bucket
' END branches'.
' FROM ('.
' SELECT DISTINCT majs_i_id i_id,'.
' POW(2, FLOOR(majs_sosa / POW(2, (majs_gen - :gen))) - POW(2, :gen -1)) branch'.
' FROM `##maj_sosa`'.
' WHERE majs_gedcom_id = :tree_id AND majs_user_id = :user_id'.
' AND majs_gen >= :gen'.
' ) indistat'.
' GROUP BY i_id'.
') grouped'.
' GROUP BY branches')
->execute(array(
'tree_id' => $this->tree->getTreeId(),
'user_id' => $this->user->getUserId(),
'gen' => $gen
))->fetchAssoc() ?: array();
} | [
"public",
"function",
"getAncestorDispersionForGen",
"(",
"$",
"gen",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"is_setup",
"||",
"$",
"gen",
">",
"11",
")",
"return",
"array",
"(",
")",
";",
"// Going further than 11 gen will be out of range in the query",
"... | Return a computed array of statistics about the dispersion of ancestors across the ancestors
at a specified generation.
This statistics cannot be used for generations above 11, as it would cause a out of range in MySQL
Format:
- key : a base-2 representation of the ancestor at generation G for which exclusive ancestors have been found,
-1 is used for shared ancestors
For instance base2(0100) = base10(4) represent the maternal grand father
- values: number of ancestors exclusively in the ancestors of the ancestor in key
For instance a result at generation 3 could be :
array ( -1 => 12 -> 12 ancestors are shared by the grand-parents
base10(1) => 32 -> 32 ancestors are exclusive to the paternal grand-father
base10(2) => 25 -> 25 ancestors are exclusive to the paternal grand-mother
base10(4) => 12 -> 12 ancestors are exclusive to the maternal grand-father
base10(8) => 30 -> 30 ancestors are exclusive to the maternal grand-mother
)
@param int $gen Reference generation
@return array | [
"Return",
"a",
"computed",
"array",
"of",
"statistics",
"about",
"the",
"dispersion",
"of",
"ancestors",
"across",
"the",
"ancestors",
"at",
"a",
"specified",
"generation",
".",
"This",
"statistics",
"cannot",
"be",
"used",
"for",
"generations",
"above",
"11",
... | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaProvider.php#L588-L613 | train |
voslartomas/WebCMS2 | Entity/Entity.php | Entity.toArray | public function toArray($notEmptyValues = false)
{
$props = $this->getReflection()->getProperties();
if ($this->getReflection()->getParentClass()) {
$temp = $this->getReflection()->getParentClass()->getProperties();
$props = array_merge($props, $temp);
}
if (strpos($this->getReflection()->getName(), '__CG__') !== FALSE) {
$props = $this->getReflection()->getParentClass()->getProperties();
}
$array = array();
foreach ($props as $prop) {
$getter = 'get'.ucfirst($prop->getName());
if (method_exists($this, $getter)) {
$empty = $this->$getter();
$empty = is_null($empty) || empty($empty);
if (!is_object($this->$getter())) {
if (($notEmptyValues && !$empty) || !$empty) {
$array[$prop->getName()] = $this->$getter();
}
} elseif (is_object($this->$getter())) {
if (method_exists($this->$getter(), 'getId')) {
$array[$prop->getName()] = $this->$getter()->getId();
} elseif ($this->$getter() instanceof \DateTime) {
$array[$prop->getName()] = $this->$getter()->format('d.m.Y');
} elseif ($this->$getter() instanceof \Doctrine\Common\Collections\Collection) {
$tmp = array();
foreach ($this->$getter() as $item) {
$tmp[] = $item->getId();
}
$array[$prop->getName()] = $tmp;
}
}
}
}
return $array;
} | php | public function toArray($notEmptyValues = false)
{
$props = $this->getReflection()->getProperties();
if ($this->getReflection()->getParentClass()) {
$temp = $this->getReflection()->getParentClass()->getProperties();
$props = array_merge($props, $temp);
}
if (strpos($this->getReflection()->getName(), '__CG__') !== FALSE) {
$props = $this->getReflection()->getParentClass()->getProperties();
}
$array = array();
foreach ($props as $prop) {
$getter = 'get'.ucfirst($prop->getName());
if (method_exists($this, $getter)) {
$empty = $this->$getter();
$empty = is_null($empty) || empty($empty);
if (!is_object($this->$getter())) {
if (($notEmptyValues && !$empty) || !$empty) {
$array[$prop->getName()] = $this->$getter();
}
} elseif (is_object($this->$getter())) {
if (method_exists($this->$getter(), 'getId')) {
$array[$prop->getName()] = $this->$getter()->getId();
} elseif ($this->$getter() instanceof \DateTime) {
$array[$prop->getName()] = $this->$getter()->format('d.m.Y');
} elseif ($this->$getter() instanceof \Doctrine\Common\Collections\Collection) {
$tmp = array();
foreach ($this->$getter() as $item) {
$tmp[] = $item->getId();
}
$array[$prop->getName()] = $tmp;
}
}
}
}
return $array;
} | [
"public",
"function",
"toArray",
"(",
"$",
"notEmptyValues",
"=",
"false",
")",
"{",
"$",
"props",
"=",
"$",
"this",
"->",
"getReflection",
"(",
")",
"->",
"getProperties",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getReflection",
"(",
")",
"->",
... | Converts object into array.
@return Array | [
"Converts",
"object",
"into",
"array",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/Entity/Entity.php#L35-L77 | train |
GrupaZero/cms | src/Gzero/Cms/Http/Controllers/Api/ContentController.php | ContentController.show | public function show($id)
{
$content = $this->repository->getById($id);
if (!$content) {
return $this->errorNotFound();
}
$this->authorize('read', $content);
return new ContentResource($content);
} | php | public function show($id)
{
$content = $this->repository->getById($id);
if (!$content) {
return $this->errorNotFound();
}
$this->authorize('read', $content);
return new ContentResource($content);
} | [
"public",
"function",
"show",
"(",
"$",
"id",
")",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"repository",
"->",
"getById",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"content",
")",
"{",
"return",
"$",
"this",
"->",
"errorNotFound",
"(",
... | Display a specified content.
@SWG\Get(
path="/contents/{id}",
tags={"content"},
summary="Returns a specific content by id",
description="Returns a specific content by id",
produces={"application/json"},
security={{"AdminAccess": {}}},
@SWG\Parameter(
name="id",
in="path",
description="Id of content that needs to be returned.",
required=true,
type="integer"
),
@SWG\Response(
response=200,
description="Successful operation",
@SWG\Schema(type="object", ref="#/definitions/Content"),
),
@SWG\Response(response=404, description="Content not found")
)
@param int $id content Id
@return ContentResource | [
"Display",
"a",
"specified",
"content",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Http/Controllers/Api/ContentController.php#L271-L281 | train |
alexislefebvre/AsyncTweetsBundle | src/Entity/TweetRepository.php | TweetRepository.removeOrphanMedias | private function removeOrphanMedias(Media $media)
{
if (count($media->getTweets()) == 0) {
$this->_em->remove($media);
}
} | php | private function removeOrphanMedias(Media $media)
{
if (count($media->getTweets()) == 0) {
$this->_em->remove($media);
}
} | [
"private",
"function",
"removeOrphanMedias",
"(",
"Media",
"$",
"media",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"media",
"->",
"getTweets",
"(",
")",
")",
"==",
"0",
")",
"{",
"$",
"this",
"->",
"_em",
"->",
"remove",
"(",
"$",
"media",
")",
";",
... | Remove Media not associated to any Tweet.
@param Media $media | [
"Remove",
"Media",
"not",
"associated",
"to",
"any",
"Tweet",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Entity/TweetRepository.php#L181-L186 | train |
alexislefebvre/AsyncTweetsBundle | src/Entity/TweetRepository.php | TweetRepository.removeTweet | protected function removeTweet($tweet)
{
$count = 0;
foreach ($tweet->getMedias() as $media) {
$tweet->removeMedia($media);
$this->removeOrphanMedias($media);
}
// Don't count tweets that were only retweeted
if ($tweet->isInTimeline()) {
$count = 1;
}
$this->_em->remove($tweet);
return $count;
} | php | protected function removeTweet($tweet)
{
$count = 0;
foreach ($tweet->getMedias() as $media) {
$tweet->removeMedia($media);
$this->removeOrphanMedias($media);
}
// Don't count tweets that were only retweeted
if ($tweet->isInTimeline()) {
$count = 1;
}
$this->_em->remove($tweet);
return $count;
} | [
"protected",
"function",
"removeTweet",
"(",
"$",
"tweet",
")",
"{",
"$",
"count",
"=",
"0",
";",
"foreach",
"(",
"$",
"tweet",
"->",
"getMedias",
"(",
")",
"as",
"$",
"media",
")",
"{",
"$",
"tweet",
"->",
"removeMedia",
"(",
"$",
"media",
")",
";... | Remove the tweet and return 1 is the deleted tweet is not a
retweet.
@param Tweet $tweet
@return int | [
"Remove",
"the",
"tweet",
"and",
"return",
"1",
"is",
"the",
"deleted",
"tweet",
"is",
"not",
"a",
"retweet",
"."
] | 76266fae7de978963e05dadb14c81f8398bb00a6 | https://github.com/alexislefebvre/AsyncTweetsBundle/blob/76266fae7de978963e05dadb14c81f8398bb00a6/src/Entity/TweetRepository.php#L196-L213 | train |
voslartomas/WebCMS2 | AdminModule/presenters/UpdatePresenter.php | UpdatePresenter.renderLog | public function renderLog()
{
$this->reloadContent();
$this->template->installLog = $this->getLog('../log/install.log');
$this->template->installErrorLog = $this->getLog('../log/install-error.log');
$this->template->updateLog = $this->getLog('../log/auto-update.log');
$this->template->errorLog = $this->getLog('../log/error.log');
} | php | public function renderLog()
{
$this->reloadContent();
$this->template->installLog = $this->getLog('../log/install.log');
$this->template->installErrorLog = $this->getLog('../log/install-error.log');
$this->template->updateLog = $this->getLog('../log/auto-update.log');
$this->template->errorLog = $this->getLog('../log/error.log');
} | [
"public",
"function",
"renderLog",
"(",
")",
"{",
"$",
"this",
"->",
"reloadContent",
"(",
")",
";",
"$",
"this",
"->",
"template",
"->",
"installLog",
"=",
"$",
"this",
"->",
"getLog",
"(",
"'../log/install.log'",
")",
";",
"$",
"this",
"->",
"template"... | render log tab | [
"render",
"log",
"tab"
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/presenters/UpdatePresenter.php#L347-L355 | train |
kadet1090/KeyLighter | Language/Perl.php | Perl.setupRules | public function setupRules()
{
$identifier = '\w+';
$number = '[+-]?(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?';
$this->rules->addMany([
'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
'context' => ['!keyword', '!comment', '!string', '!language', '!number'],
]),
'comment' => new Rule(new CommentMatcher(['#'])),
'keyword' => new Rule(new WordMatcher([
'case', 'continue', 'do', 'else', 'elsif', 'for', 'foreach',
'if', 'last', 'my', 'next', 'our', 'redo', 'reset', 'then',
'unless', 'until', 'while', 'use', 'print', 'new', 'BEGIN',
'sub', 'CHECK', 'INIT', 'END', 'return', 'exit'
])),
'operator.escape' => new Rule(new RegexMatcher('/(\\\.)/'), [
'context' => ['string']
]),
'string.nowdoc' => new Rule(
new RegexMatcher('/<<\s*\'(\w+)\';(?P<string>.*?)\R\1/sm', [
'string' => Token::NAME,
0 => 'keyword.nowdoc'
]), ['context' => ['!comment']]
),
'language.shell' => new Rule(new SubStringMatcher('`'), [
'context' => ['!operator.escape', '!comment', '!string', '!keyword.nowdoc'],
'factory' => new TokenFactory(ContextualToken::class),
]),
'variable.scalar' => new Rule(new RegexMatcher("/(\\\$$identifier)/")),
'variable.array' => new Rule(new RegexMatcher("/(\\@$identifier)/")),
'variable.hash' => new Rule(new RegexMatcher("/(\\%$identifier)/")),
'variable.property' => new Rule(new RegexMatcher("/\\\$$identifier{($identifier)}/")),
// Stupidly named var? Perl one, for sure.
'variable.special' => new Rule(new RegexMatcher('/([$@%][^\s\w]+[\w]*)/')),
'operator' => [
new Rule(new RegexMatcher('/(-[rwxoRWXOezsfdlpSbctugkTBMAC])/')),
new Rule(new WordMatcher([
'not', 'and', 'or', 'xor', 'goto', 'last', 'next', 'redo', 'dump',
'eq', 'ne', 'cmp', 'not', 'and', 'or', 'xor'
], ['atomic' => true])),
],
'call' => new Rule(new RegexMatcher('/([a-z]\w+)(?:\s*\(|\s+[$%@"\'`{])/i')),
'number' => [
new Rule(new RegexMatcher("/(\\b|\"|')$number\\1/", [
0 => Token::NAME
]), ['priority' => 5]),
],
'string.regex' => [
new OpenRule(new RegexMatcher('#~\s*[ms]?(/).*?/#m'), [
'context' => Validator::everywhere()
]),
new OpenRule(new RegexMatcher('#~\s*(s/).*?/#m')),
new Rule(new RegexMatcher('#(?=\/.*?(/[gimuy]{0,5}))#m'), [
'priority' => 1,
'factory' => new TokenFactory(ContextualToken::class),
'context' => ['!operator.escape', 'string.regex']
])
],
'symbol.iterator' => [
new Rule(new RegexMatcher('#(<\w+>)#s'))
]
]);
} | php | public function setupRules()
{
$identifier = '\w+';
$number = '[+-]?(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?';
$this->rules->addMany([
'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
'context' => ['!keyword', '!comment', '!string', '!language', '!number'],
]),
'comment' => new Rule(new CommentMatcher(['#'])),
'keyword' => new Rule(new WordMatcher([
'case', 'continue', 'do', 'else', 'elsif', 'for', 'foreach',
'if', 'last', 'my', 'next', 'our', 'redo', 'reset', 'then',
'unless', 'until', 'while', 'use', 'print', 'new', 'BEGIN',
'sub', 'CHECK', 'INIT', 'END', 'return', 'exit'
])),
'operator.escape' => new Rule(new RegexMatcher('/(\\\.)/'), [
'context' => ['string']
]),
'string.nowdoc' => new Rule(
new RegexMatcher('/<<\s*\'(\w+)\';(?P<string>.*?)\R\1/sm', [
'string' => Token::NAME,
0 => 'keyword.nowdoc'
]), ['context' => ['!comment']]
),
'language.shell' => new Rule(new SubStringMatcher('`'), [
'context' => ['!operator.escape', '!comment', '!string', '!keyword.nowdoc'],
'factory' => new TokenFactory(ContextualToken::class),
]),
'variable.scalar' => new Rule(new RegexMatcher("/(\\\$$identifier)/")),
'variable.array' => new Rule(new RegexMatcher("/(\\@$identifier)/")),
'variable.hash' => new Rule(new RegexMatcher("/(\\%$identifier)/")),
'variable.property' => new Rule(new RegexMatcher("/\\\$$identifier{($identifier)}/")),
// Stupidly named var? Perl one, for sure.
'variable.special' => new Rule(new RegexMatcher('/([$@%][^\s\w]+[\w]*)/')),
'operator' => [
new Rule(new RegexMatcher('/(-[rwxoRWXOezsfdlpSbctugkTBMAC])/')),
new Rule(new WordMatcher([
'not', 'and', 'or', 'xor', 'goto', 'last', 'next', 'redo', 'dump',
'eq', 'ne', 'cmp', 'not', 'and', 'or', 'xor'
], ['atomic' => true])),
],
'call' => new Rule(new RegexMatcher('/([a-z]\w+)(?:\s*\(|\s+[$%@"\'`{])/i')),
'number' => [
new Rule(new RegexMatcher("/(\\b|\"|')$number\\1/", [
0 => Token::NAME
]), ['priority' => 5]),
],
'string.regex' => [
new OpenRule(new RegexMatcher('#~\s*[ms]?(/).*?/#m'), [
'context' => Validator::everywhere()
]),
new OpenRule(new RegexMatcher('#~\s*(s/).*?/#m')),
new Rule(new RegexMatcher('#(?=\/.*?(/[gimuy]{0,5}))#m'), [
'priority' => 1,
'factory' => new TokenFactory(ContextualToken::class),
'context' => ['!operator.escape', 'string.regex']
])
],
'symbol.iterator' => [
new Rule(new RegexMatcher('#(<\w+>)#s'))
]
]);
} | [
"public",
"function",
"setupRules",
"(",
")",
"{",
"$",
"identifier",
"=",
"'\\w+'",
";",
"$",
"number",
"=",
"'[+-]?(?=\\d|\\.\\d)\\d*(\\.\\d*)?([Ee]([+-]?\\d+))?'",
";",
"$",
"this",
"->",
"rules",
"->",
"addMany",
"(",
"[",
"'string'",
"=>",
"CommonFeatures",
... | Tokenization rules definition | [
"Tokenization",
"rules",
"definition"
] | 6aac402b7fe0170edf3c5afbae652009951068af | https://github.com/kadet1090/KeyLighter/blob/6aac402b7fe0170edf3c5afbae652009951068af/Language/Perl.php#L38-L115 | train |
GrupaZero/cms | src/Gzero/Cms/Http/Controllers/Api/BlockController.php | BlockController.show | public function show($id)
{
$block = $this->repository->getById($id);
if (!$block) {
return $this->errorNotFound();
}
$this->authorize('read', $block);
return new BlockResource($block);
} | php | public function show($id)
{
$block = $this->repository->getById($id);
if (!$block) {
return $this->errorNotFound();
}
$this->authorize('read', $block);
return new BlockResource($block);
} | [
"public",
"function",
"show",
"(",
"$",
"id",
")",
"{",
"$",
"block",
"=",
"$",
"this",
"->",
"repository",
"->",
"getById",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"block",
")",
"{",
"return",
"$",
"this",
"->",
"errorNotFound",
"(",
")",... | Display a specified block.
@SWG\Get(
path="/blocks/{id}",
tags={"blocks"},
summary="Returns a specific block by id",
description="Returns a specific block by id",
produces={"application/json"},
security={{"AdminAccess": {}}},
@SWG\Parameter(
name="id",
in="path",
description="Id of block that needs to be returned.",
required=true,
type="integer"
),
@SWG\Response(
response=200,
description="Successful operation",
@SWG\Schema(type="object", ref="#/definitions/Block"),
),
@SWG\Response(response=404, description="Block not found")
)
@param int $id content Id
@return BlockResource | [
"Display",
"a",
"specified",
"block",
"."
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Http/Controllers/Api/BlockController.php#L199-L209 | train |
GrupaZero/cms | database/migrations/2015_11_26_115322_create_block.php | CreateBlock.seedBlockTypes | private function seedBlockTypes()
{
BlockType::firstOrCreate(['name' => 'basic', 'handler' => Gzero\Cms\Handlers\Block\Basic::class]);
BlockType::firstOrCreate(['name' => 'menu', 'handler' => Gzero\Cms\Handlers\Block\Menu::class]);
BlockType::firstOrCreate(['name' => 'slider', 'handler' => Gzero\Cms\Handlers\Block\Slider::class]);
} | php | private function seedBlockTypes()
{
BlockType::firstOrCreate(['name' => 'basic', 'handler' => Gzero\Cms\Handlers\Block\Basic::class]);
BlockType::firstOrCreate(['name' => 'menu', 'handler' => Gzero\Cms\Handlers\Block\Menu::class]);
BlockType::firstOrCreate(['name' => 'slider', 'handler' => Gzero\Cms\Handlers\Block\Slider::class]);
} | [
"private",
"function",
"seedBlockTypes",
"(",
")",
"{",
"BlockType",
"::",
"firstOrCreate",
"(",
"[",
"'name'",
"=>",
"'basic'",
",",
"'handler'",
"=>",
"Gzero",
"\\",
"Cms",
"\\",
"Handlers",
"\\",
"Block",
"\\",
"Basic",
"::",
"class",
"]",
")",
";",
"... | Seed block types
@return void | [
"Seed",
"block",
"types"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/database/migrations/2015_11_26_115322_create_block.php#L86-L91 | train |
voslartomas/WebCMS2 | FrontendModule/presenters/BasePresenter.php | BasePresenter.getStructures | private function getStructures($direct = true, $rootClass = 'nav navbar-nav', $dropDown = false, $rootId = '')
{
$repo = $this->em->getRepository('WebCMS\Entity\Page');
$structs = $repo->findBy(array(
'language' => $this->language,
'parent' => NULL,
));
$structures = array();
foreach ($structs as $s) {
$structures[$s->getTitle()] = $this->getStructure($this, $s, $repo, $direct, $rootClass, $dropDown, true, null, '', null, $rootId);
}
return $structures;
} | php | private function getStructures($direct = true, $rootClass = 'nav navbar-nav', $dropDown = false, $rootId = '')
{
$repo = $this->em->getRepository('WebCMS\Entity\Page');
$structs = $repo->findBy(array(
'language' => $this->language,
'parent' => NULL,
));
$structures = array();
foreach ($structs as $s) {
$structures[$s->getTitle()] = $this->getStructure($this, $s, $repo, $direct, $rootClass, $dropDown, true, null, '', null, $rootId);
}
return $structures;
} | [
"private",
"function",
"getStructures",
"(",
"$",
"direct",
"=",
"true",
",",
"$",
"rootClass",
"=",
"'nav navbar-nav'",
",",
"$",
"dropDown",
"=",
"false",
",",
"$",
"rootId",
"=",
"''",
")",
"{",
"$",
"repo",
"=",
"$",
"this",
"->",
"em",
"->",
"ge... | Load all system structures.
@return type | [
"Load",
"all",
"system",
"structures",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/FrontendModule/presenters/BasePresenter.php#L435-L450 | train |
voslartomas/WebCMS2 | FrontendModule/presenters/BasePresenter.php | BasePresenter.formatTemplateFiles | public function formatTemplateFiles()
{
$name = $this->getName();
$path = explode(':', $name);
if (isset($path[2])) {
$module = $path[1];
$presenter = $path[2];
} else {
$module = $path[0];
$presenter = $path[1];
}
$dir = dirname($this->getReflection()->getFileName());
$dir = is_dir("$dir/templates") ? $dir : dirname($dir);
$appPath = APP_DIR."/templates/".lcfirst($module)."-module/$presenter/$this->view.latte";
return array(
$appPath,
"$dir/templates/$presenter/$this->view.latte",
"$dir/templates/$presenter.$this->view.latte",
"$dir/templates/$presenter/$this->view.phtml",
"$dir/templates/$presenter.$this->view.phtml",
);
} | php | public function formatTemplateFiles()
{
$name = $this->getName();
$path = explode(':', $name);
if (isset($path[2])) {
$module = $path[1];
$presenter = $path[2];
} else {
$module = $path[0];
$presenter = $path[1];
}
$dir = dirname($this->getReflection()->getFileName());
$dir = is_dir("$dir/templates") ? $dir : dirname($dir);
$appPath = APP_DIR."/templates/".lcfirst($module)."-module/$presenter/$this->view.latte";
return array(
$appPath,
"$dir/templates/$presenter/$this->view.latte",
"$dir/templates/$presenter.$this->view.latte",
"$dir/templates/$presenter/$this->view.phtml",
"$dir/templates/$presenter.$this->view.phtml",
);
} | [
"public",
"function",
"formatTemplateFiles",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
";",
"$",
"path",
"=",
"explode",
"(",
"':'",
",",
"$",
"name",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"path",
"[",
"2",
"]",
... | Formats view template file names.
@return array | [
"Formats",
"view",
"template",
"file",
"names",
"."
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/FrontendModule/presenters/BasePresenter.php#L643-L669 | train |
CanalTP/NmmPortalBundle | Services/NavitiaTokenManager.php | NavitiaTokenManager.call | private function call($url, $method = 'GET')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
//Timeout in 5s
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->timeout);
$response = curl_exec($ch);
$errorMsg = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
$response = json_decode($response);
if (isset($response->error)) {
$errorMsg .= '(' . $response->error . ')';
}
throw new \Exception($httpCode . ' : ' . $errorMsg);
}
if ($response === false) {
return false;
}
return $response;
} | php | private function call($url, $method = 'GET')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
//Timeout in 5s
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->timeout);
$response = curl_exec($ch);
$errorMsg = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
$response = json_decode($response);
if (isset($response->error)) {
$errorMsg .= '(' . $response->error . ')';
}
throw new \Exception($httpCode . ' : ' . $errorMsg);
}
if ($response === false) {
return false;
}
return $response;
} | [
"private",
"function",
"call",
"(",
"$",
"url",
",",
"$",
"method",
"=",
"'GET'",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL",
",",
"$",
"url",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
"... | Make calls to WS
@param string $url
@param string $method
@return boolean if no result or string if succes
@throws \Exception if navitia call fail | [
"Make",
"calls",
"to",
"WS"
] | b1ad026a33897984206ea1691ad9e25db5854efb | https://github.com/CanalTP/NmmPortalBundle/blob/b1ad026a33897984206ea1691ad9e25db5854efb/Services/NavitiaTokenManager.php#L40-L67 | train |
CanalTP/NmmPortalBundle | Services/NavitiaTokenManager.php | NavitiaTokenManager.getInstancesIdsFromExternalsCoveragesIds | private function getInstancesIdsFromExternalsCoveragesIds(\Traversable $perimeters)
{
$userPerimeterNavitiaIds = array();
$instances = $this->getInstances();
foreach ($perimeters as $perimeter) {
$userPerimeterNavitiaId = array_search($perimeter->getExternalCoverageId(), $instances);
if ($userPerimeterNavitiaId) {
$userPerimeterNavitiaIds[] = array_search($perimeter->getExternalCoverageId(), $instances);
} else {
throw new NotFoundHttpException("Coverage not found: " . $perimeter->getExternalCoverageId() . " in tyr api (" . $this->tyrUrl . ") ");
}
}
return $userPerimeterNavitiaIds;
} | php | private function getInstancesIdsFromExternalsCoveragesIds(\Traversable $perimeters)
{
$userPerimeterNavitiaIds = array();
$instances = $this->getInstances();
foreach ($perimeters as $perimeter) {
$userPerimeterNavitiaId = array_search($perimeter->getExternalCoverageId(), $instances);
if ($userPerimeterNavitiaId) {
$userPerimeterNavitiaIds[] = array_search($perimeter->getExternalCoverageId(), $instances);
} else {
throw new NotFoundHttpException("Coverage not found: " . $perimeter->getExternalCoverageId() . " in tyr api (" . $this->tyrUrl . ") ");
}
}
return $userPerimeterNavitiaIds;
} | [
"private",
"function",
"getInstancesIdsFromExternalsCoveragesIds",
"(",
"\\",
"Traversable",
"$",
"perimeters",
")",
"{",
"$",
"userPerimeterNavitiaIds",
"=",
"array",
"(",
")",
";",
"$",
"instances",
"=",
"$",
"this",
"->",
"getInstances",
"(",
")",
";",
"forea... | From perimeters names, find navitia instances ids for add permissions
@param array $coverages | [
"From",
"perimeters",
"names",
"find",
"navitia",
"instances",
"ids",
"for",
"add",
"permissions"
] | b1ad026a33897984206ea1691ad9e25db5854efb | https://github.com/CanalTP/NmmPortalBundle/blob/b1ad026a33897984206ea1691ad9e25db5854efb/Services/NavitiaTokenManager.php#L211-L225 | train |
CanalTP/NmmPortalBundle | Services/NavitiaTokenManager.php | NavitiaTokenManager.getNavitiaApiAllId | private function getNavitiaApiAllId()
{
$response = $this->call($this->tyrUrl . '/' . $this->version . '/api/');
$apis = json_decode($response);
foreach ($apis as $api) {
if ($api->name == 'ALL') {
return $api;
}
}
} | php | private function getNavitiaApiAllId()
{
$response = $this->call($this->tyrUrl . '/' . $this->version . '/api/');
$apis = json_decode($response);
foreach ($apis as $api) {
if ($api->name == 'ALL') {
return $api;
}
}
} | [
"private",
"function",
"getNavitiaApiAllId",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"call",
"(",
"$",
"this",
"->",
"tyrUrl",
".",
"'/'",
".",
"$",
"this",
"->",
"version",
".",
"'/api/'",
")",
";",
"$",
"apis",
"=",
"json_decode",
"... | Return meta api 'ALL' id
@return type | [
"Return",
"meta",
"api",
"ALL",
"id"
] | b1ad026a33897984206ea1691ad9e25db5854efb | https://github.com/CanalTP/NmmPortalBundle/blob/b1ad026a33897984206ea1691ad9e25db5854efb/Services/NavitiaTokenManager.php#L232-L242 | train |
CanalTP/NmmPortalBundle | Services/NavitiaTokenManager.php | NavitiaTokenManager.createAuthorization | private function createAuthorization($userId, $instanceId)
{
$apiAll = $this->getNavitiaApiAllId();
$this->call($this->tyrUrl . '/' . $this->version . '/users/' . $userId . '/authorizations/?api_id=' . $apiAll->id . '&instance_id=' . $instanceId, 'POST');
return true;
} | php | private function createAuthorization($userId, $instanceId)
{
$apiAll = $this->getNavitiaApiAllId();
$this->call($this->tyrUrl . '/' . $this->version . '/users/' . $userId . '/authorizations/?api_id=' . $apiAll->id . '&instance_id=' . $instanceId, 'POST');
return true;
} | [
"private",
"function",
"createAuthorization",
"(",
"$",
"userId",
",",
"$",
"instanceId",
")",
"{",
"$",
"apiAll",
"=",
"$",
"this",
"->",
"getNavitiaApiAllId",
"(",
")",
";",
"$",
"this",
"->",
"call",
"(",
"$",
"this",
"->",
"tyrUrl",
".",
"'/'",
"."... | Add permissions to navitia user
@param int $userId
@param int $instanceId
@return boolean | [
"Add",
"permissions",
"to",
"navitia",
"user"
] | b1ad026a33897984206ea1691ad9e25db5854efb | https://github.com/CanalTP/NmmPortalBundle/blob/b1ad026a33897984206ea1691ad9e25db5854efb/Services/NavitiaTokenManager.php#L251-L257 | train |
nails/module-cdn | cdn/controllers/Crop.php | Crop.resize | private function resize(
$filePath,
$phpCropMethod
) {
// Set some PHPThumb options
$_options = [];
$_options['resizeUp'] = true;
$_options['jpegQuality'] = 80;
// --------------------------------------------------------------------------
/**
* Perform the resize
* Turn errors off, if something bad happens we want to
* output the serveBadSrc image and log the issue.
*/
$oldErrorReporting = error_reporting();
error_reporting(0);
$width = $this->width * $this->retinaMultiplier;
$height = $this->height * $this->retinaMultiplier;
$ext = strtoupper(substr($this->extension, 1));
if ($ext === 'JPEG') {
$ext = 'jpg';
}
try {
/**
* Catch any output, don't want anything going to the browser unless
* we're sure it's ok
*/
ob_start();
$PHPThumb = new \PHPThumb\GD($filePath, $_options);
// Prepare the parameters and call the method
$aParams = [
$width,
$height,
$this->cropQuadrant,
];
call_user_func_array([$PHPThumb, $phpCropMethod], $aParams);
// Save cache version
$PHPThumb->save($this->cdnCacheDir . $this->cdnCacheFile, $ext);
// Flush the buffer
ob_end_clean();
} catch (Exception $e) {
// Log the error
Factory::service('Logger')->line('CDN: ' . $phpCropMethod . ': ' . $e->getMessage());
// Switch error reporting back how it was
error_reporting($oldErrorReporting);
// Flush the buffer
ob_end_clean();
// Bad SRC
$this->serveBadSrc([
'width' => $width,
'height' => $height,
]);
}
$this->serveFromCache($this->cdnCacheFile, false);
// Switch error reporting back how it was
error_reporting($oldErrorReporting);
} | php | private function resize(
$filePath,
$phpCropMethod
) {
// Set some PHPThumb options
$_options = [];
$_options['resizeUp'] = true;
$_options['jpegQuality'] = 80;
// --------------------------------------------------------------------------
/**
* Perform the resize
* Turn errors off, if something bad happens we want to
* output the serveBadSrc image and log the issue.
*/
$oldErrorReporting = error_reporting();
error_reporting(0);
$width = $this->width * $this->retinaMultiplier;
$height = $this->height * $this->retinaMultiplier;
$ext = strtoupper(substr($this->extension, 1));
if ($ext === 'JPEG') {
$ext = 'jpg';
}
try {
/**
* Catch any output, don't want anything going to the browser unless
* we're sure it's ok
*/
ob_start();
$PHPThumb = new \PHPThumb\GD($filePath, $_options);
// Prepare the parameters and call the method
$aParams = [
$width,
$height,
$this->cropQuadrant,
];
call_user_func_array([$PHPThumb, $phpCropMethod], $aParams);
// Save cache version
$PHPThumb->save($this->cdnCacheDir . $this->cdnCacheFile, $ext);
// Flush the buffer
ob_end_clean();
} catch (Exception $e) {
// Log the error
Factory::service('Logger')->line('CDN: ' . $phpCropMethod . ': ' . $e->getMessage());
// Switch error reporting back how it was
error_reporting($oldErrorReporting);
// Flush the buffer
ob_end_clean();
// Bad SRC
$this->serveBadSrc([
'width' => $width,
'height' => $height,
]);
}
$this->serveFromCache($this->cdnCacheFile, false);
// Switch error reporting back how it was
error_reporting($oldErrorReporting);
} | [
"private",
"function",
"resize",
"(",
"$",
"filePath",
",",
"$",
"phpCropMethod",
")",
"{",
"// Set some PHPThumb options",
"$",
"_options",
"=",
"[",
"]",
";",
"$",
"_options",
"[",
"'resizeUp'",
"]",
"=",
"true",
";",
"$",
"_options",
"[",
"'jpegQuality'"... | Resize a static image
@param string $filePath The file to resize
@param string $phpCropMethod The PHPThumb method to use for resizing
@return void | [
"Resize",
"a",
"static",
"image"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/cdn/controllers/Crop.php#L281-L357 | train |
nails/module-cdn | cdn/controllers/Crop.php | Crop.resizeAnimated | private function resizeAnimated(
$filePath,
$phpCropMethod
) {
$hash = md5(microtime(true) . uniqid()) . uniqid();
$frames = [];
$cacheFiles = [];
$durations = [];
$gfe = new GifFrameExtractor\GifFrameExtractor();
$gc = new GifCreator\GifCreator();
$width = $this->width * $this->retinaMultiplier;
$height = $this->height * $this->retinaMultiplier;
// --------------------------------------------------------------------------
// Extract all the frames, resize them and save to the cache
$gfe->extract($filePath);
$i = 0;
foreach ($gfe->getFrames() as $frame) {
// Define the filename
$filename = $hash . '-' . $i . '.gif';
$tempFilename = $hash . '-' . $i . '-original.gif';
$i++;
// Set these for recompiling
$frames[] = $this->cdnCacheDir . $filename;
$cacheFiles[] = $this->cdnCacheDir . $tempFilename;
$durations[] = $frame['duration'];
// --------------------------------------------------------------------------
// Set some PHPThumb options
$options = [
'resizeUp' => true,
];
// --------------------------------------------------------------------------
// Perform the resize; first save the original frame to disk
imagegif($frame['image'], $this->cdnCacheDir . $tempFilename);
$PHPThumb = new \PHPThumb\GD($this->cdnCacheDir . $tempFilename, $options);
// Prepare the parameters and call the method
$aParams = [
$width,
$height,
$this->cropQuadrant,
];
call_user_func_array([$PHPThumb, $phpCropMethod], $aParams);
// --------------------------------------------------------------------------
// Save cache version
$PHPThumb->save($this->cdnCacheDir . $filename, strtoupper(substr($this->extension, 1)));
}
/**
* Recompile the re-sized images back into an animated gif and save to the cache
*
* @todo: We assume the gif loops infinitely but we should really check.
* Issue made on the library's GitHub asking for this feature.
* View here: https://github.com/Sybio/GifFrameExtractor/issues/3
*/
$gc->create($frames, $durations, 0);
$data = $gc->getGif();
// --------------------------------------------------------------------------
// Output to browser
header('Content-Type: image/gif', true);
echo $data;
// --------------------------------------------------------------------------
// Save to cache
Factory::helper('file');
write_file($this->cdnCacheDir . $this->cdnCacheFile, $data);
// --------------------------------------------------------------------------
// Remove cache frames
foreach ($frames as $frame) {
if (file_exists($frame)) {
unlink($frame);
}
}
foreach ($cacheFiles as $frame) {
if (file_exists($frame)) {
unlink($frame);
}
}
// --------------------------------------------------------------------------
/**
* Kill script, th, th, that's all folks.
* Stop the output class from hijacking our headers and
* setting an incorrect Content-Type
*/
exit(0);
} | php | private function resizeAnimated(
$filePath,
$phpCropMethod
) {
$hash = md5(microtime(true) . uniqid()) . uniqid();
$frames = [];
$cacheFiles = [];
$durations = [];
$gfe = new GifFrameExtractor\GifFrameExtractor();
$gc = new GifCreator\GifCreator();
$width = $this->width * $this->retinaMultiplier;
$height = $this->height * $this->retinaMultiplier;
// --------------------------------------------------------------------------
// Extract all the frames, resize them and save to the cache
$gfe->extract($filePath);
$i = 0;
foreach ($gfe->getFrames() as $frame) {
// Define the filename
$filename = $hash . '-' . $i . '.gif';
$tempFilename = $hash . '-' . $i . '-original.gif';
$i++;
// Set these for recompiling
$frames[] = $this->cdnCacheDir . $filename;
$cacheFiles[] = $this->cdnCacheDir . $tempFilename;
$durations[] = $frame['duration'];
// --------------------------------------------------------------------------
// Set some PHPThumb options
$options = [
'resizeUp' => true,
];
// --------------------------------------------------------------------------
// Perform the resize; first save the original frame to disk
imagegif($frame['image'], $this->cdnCacheDir . $tempFilename);
$PHPThumb = new \PHPThumb\GD($this->cdnCacheDir . $tempFilename, $options);
// Prepare the parameters and call the method
$aParams = [
$width,
$height,
$this->cropQuadrant,
];
call_user_func_array([$PHPThumb, $phpCropMethod], $aParams);
// --------------------------------------------------------------------------
// Save cache version
$PHPThumb->save($this->cdnCacheDir . $filename, strtoupper(substr($this->extension, 1)));
}
/**
* Recompile the re-sized images back into an animated gif and save to the cache
*
* @todo: We assume the gif loops infinitely but we should really check.
* Issue made on the library's GitHub asking for this feature.
* View here: https://github.com/Sybio/GifFrameExtractor/issues/3
*/
$gc->create($frames, $durations, 0);
$data = $gc->getGif();
// --------------------------------------------------------------------------
// Output to browser
header('Content-Type: image/gif', true);
echo $data;
// --------------------------------------------------------------------------
// Save to cache
Factory::helper('file');
write_file($this->cdnCacheDir . $this->cdnCacheFile, $data);
// --------------------------------------------------------------------------
// Remove cache frames
foreach ($frames as $frame) {
if (file_exists($frame)) {
unlink($frame);
}
}
foreach ($cacheFiles as $frame) {
if (file_exists($frame)) {
unlink($frame);
}
}
// --------------------------------------------------------------------------
/**
* Kill script, th, th, that's all folks.
* Stop the output class from hijacking our headers and
* setting an incorrect Content-Type
*/
exit(0);
} | [
"private",
"function",
"resizeAnimated",
"(",
"$",
"filePath",
",",
"$",
"phpCropMethod",
")",
"{",
"$",
"hash",
"=",
"md5",
"(",
"microtime",
"(",
"true",
")",
".",
"uniqid",
"(",
")",
")",
".",
"uniqid",
"(",
")",
";",
"$",
"frames",
"=",
"[",
"]... | Resize an animated image
@param string $filePath The file to resize
@param string $phpCropMethod The PHPThumb method to use for resizing
@return void | [
"Resize",
"an",
"animated",
"image"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/cdn/controllers/Crop.php#L369-L476 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Model/LineageNode.php | LineageNode.addFamily | public function addFamily(Family $fams) {
if($fams && !isset($this->linked_fams[$fams])) {
$this->linked_fams[$fams] = array();
}
} | php | public function addFamily(Family $fams) {
if($fams && !isset($this->linked_fams[$fams])) {
$this->linked_fams[$fams] = array();
}
} | [
"public",
"function",
"addFamily",
"(",
"Family",
"$",
"fams",
")",
"{",
"if",
"(",
"$",
"fams",
"&&",
"!",
"isset",
"(",
"$",
"this",
"->",
"linked_fams",
"[",
"$",
"fams",
"]",
")",
")",
"{",
"$",
"this",
"->",
"linked_fams",
"[",
"$",
"fams",
... | Add a spouse family to the node
@param Fisharebest\Webtrees\Family $fams | [
"Add",
"a",
"spouse",
"family",
"to",
"the",
"node"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Model/LineageNode.php#L59-L63 | train |
jon48/webtrees-lib | src/Webtrees/Module/PatronymicLineage/Model/LineageNode.php | LineageNode.addChild | public function addChild(Family $fams, LineageNode $child = null) {
if($fams) {
$this->addFamily($fams);
$tmp = $this->linked_fams[$fams];
$tmp[] = $child;
$this->linked_fams[$fams] = $tmp;
}
} | php | public function addChild(Family $fams, LineageNode $child = null) {
if($fams) {
$this->addFamily($fams);
$tmp = $this->linked_fams[$fams];
$tmp[] = $child;
$this->linked_fams[$fams] = $tmp;
}
} | [
"public",
"function",
"addChild",
"(",
"Family",
"$",
"fams",
",",
"LineageNode",
"$",
"child",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"fams",
")",
"{",
"$",
"this",
"->",
"addFamily",
"(",
"$",
"fams",
")",
";",
"$",
"tmp",
"=",
"$",
"this",
"->... | Add a child LineageNode to the node
@param Fisharebest\Webtrees\Family $fams
@param LineageNode $child | [
"Add",
"a",
"child",
"LineageNode",
"to",
"the",
"node"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/PatronymicLineage/Model/LineageNode.php#L71-L78 | train |
GrupaZero/cms | src/Gzero/Cms/ServiceProvider.php | ServiceProvider.registerViewComposers | protected function registerViewComposers()
{
view()->composer(
'gzero-cms::contents._disqus',
function ($view) {
$data = [];
$user = auth()->user();
if ($user && !$user->isGuest()) {
$data = [
"id" => $user["id"],
"username" => $user->getPresenter()->displayName(),
"email" => $user["email"],
//"avatar" => $user["avatar"],
];
}
$message = base64_encode(json_encode($data));
$timestamp = time();
$hmac = $this->dsqHmacSha1($message . ' ' . $timestamp, config('gzero-cms.disqus.api_secret'));
$view->with('remoteAuthS3', "$message $hmac $timestamp");
}
);
} | php | protected function registerViewComposers()
{
view()->composer(
'gzero-cms::contents._disqus',
function ($view) {
$data = [];
$user = auth()->user();
if ($user && !$user->isGuest()) {
$data = [
"id" => $user["id"],
"username" => $user->getPresenter()->displayName(),
"email" => $user["email"],
//"avatar" => $user["avatar"],
];
}
$message = base64_encode(json_encode($data));
$timestamp = time();
$hmac = $this->dsqHmacSha1($message . ' ' . $timestamp, config('gzero-cms.disqus.api_secret'));
$view->with('remoteAuthS3', "$message $hmac $timestamp");
}
);
} | [
"protected",
"function",
"registerViewComposers",
"(",
")",
"{",
"view",
"(",
")",
"->",
"composer",
"(",
"'gzero-cms::contents._disqus'",
",",
"function",
"(",
"$",
"view",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"user",
"=",
"auth",
"(",
")",
... | It registers view composers
@return void | [
"It",
"registers",
"view",
"composers"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/ServiceProvider.php#L183-L205 | train |
GrupaZero/cms | src/Gzero/Cms/ServiceProvider.php | ServiceProvider.registerListeners | protected function registerListeners()
{
Event::listen(RouteMatched::class, BlockLoad::class);
Event::listen(GzeroRouteMatched::class, BlockLoad::class);
Event::listen('block.*', BlockCacheClear::class);
} | php | protected function registerListeners()
{
Event::listen(RouteMatched::class, BlockLoad::class);
Event::listen(GzeroRouteMatched::class, BlockLoad::class);
Event::listen('block.*', BlockCacheClear::class);
} | [
"protected",
"function",
"registerListeners",
"(",
")",
"{",
"Event",
"::",
"listen",
"(",
"RouteMatched",
"::",
"class",
",",
"BlockLoad",
"::",
"class",
")",
";",
"Event",
"::",
"listen",
"(",
"GzeroRouteMatched",
"::",
"class",
",",
"BlockLoad",
"::",
"cl... | It registers event listeners
@return void | [
"It",
"registers",
"event",
"listeners"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/ServiceProvider.php#L270-L275 | train |
voslartomas/WebCMS2 | AdminModule/model/Authenticator.php | Authenticator.authenticate | public function authenticate(array $credentials)
{
list($username, $password) = $credentials;
$user = $this->users->findOneBy(array('username' => $username));
if (!$user) {
throw new NS\AuthenticationException("User not found.", self::IDENTITY_NOT_FOUND);
}
if ($user->password !== $this->calculateHash($password)) {
throw new NS\AuthenticationException("Invalid password.", self::INVALID_CREDENTIAL);
}
$permissions = array();
foreach ($user->getRole()->getPermissions() as $key => $per) {
$permissions[$per->getResource()] = $per->getRead();
}
return new NS\Identity($user->id, $user->getRole()->getName(), array(
'username' => $user->username,
'email' => $user->email,
'permissions' => $permissions,
));
} | php | public function authenticate(array $credentials)
{
list($username, $password) = $credentials;
$user = $this->users->findOneBy(array('username' => $username));
if (!$user) {
throw new NS\AuthenticationException("User not found.", self::IDENTITY_NOT_FOUND);
}
if ($user->password !== $this->calculateHash($password)) {
throw new NS\AuthenticationException("Invalid password.", self::INVALID_CREDENTIAL);
}
$permissions = array();
foreach ($user->getRole()->getPermissions() as $key => $per) {
$permissions[$per->getResource()] = $per->getRead();
}
return new NS\Identity($user->id, $user->getRole()->getName(), array(
'username' => $user->username,
'email' => $user->email,
'permissions' => $permissions,
));
} | [
"public",
"function",
"authenticate",
"(",
"array",
"$",
"credentials",
")",
"{",
"list",
"(",
"$",
"username",
",",
"$",
"password",
")",
"=",
"$",
"credentials",
";",
"$",
"user",
"=",
"$",
"this",
"->",
"users",
"->",
"findOneBy",
"(",
"array",
"(",... | Performs an authentication
@param array
@return Nette\Security\Identity
@throws Nette\Security\AuthenticationException | [
"Performs",
"an",
"authentication"
] | b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf | https://github.com/voslartomas/WebCMS2/blob/b39ea4b2fd30e87ff5e4fa81441cefa308e51fbf/AdminModule/model/Authenticator.php#L29-L52 | train |
jon48/webtrees-lib | src/Webtrees/Functions/FunctionsPrintLists.php | FunctionsPrintLists.sortableNames | public static function sortableNames(Individual $individual) {
$names = $individual->getAllNames();
$primary = $individual->getPrimaryName();
list($surn, $givn) = explode(',', $names[$primary]['sort']);
$givn = str_replace('@P.N.', 'AAAA', $givn);
$surn = str_replace('@N.N.', 'AAAA', $surn);
return array(
$surn . 'AAAA' . $givn,
$givn . 'AAAA' . $surn,
);
} | php | public static function sortableNames(Individual $individual) {
$names = $individual->getAllNames();
$primary = $individual->getPrimaryName();
list($surn, $givn) = explode(',', $names[$primary]['sort']);
$givn = str_replace('@P.N.', 'AAAA', $givn);
$surn = str_replace('@N.N.', 'AAAA', $surn);
return array(
$surn . 'AAAA' . $givn,
$givn . 'AAAA' . $surn,
);
} | [
"public",
"static",
"function",
"sortableNames",
"(",
"Individual",
"$",
"individual",
")",
"{",
"$",
"names",
"=",
"$",
"individual",
"->",
"getAllNames",
"(",
")",
";",
"$",
"primary",
"=",
"$",
"individual",
"->",
"getPrimaryName",
"(",
")",
";",
"list"... | Copy of core function, which is not public.
@param Individual $individual
@return string[]
@see \Fisharebest\Webtrees\Functions\FunctionsPrintLists | [
"Copy",
"of",
"core",
"function",
"which",
"is",
"not",
"public",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Functions/FunctionsPrintLists.php#L28-L41 | train |
GrupaZero/cms | src/Gzero/Cms/Jobs/UpdateContent.php | UpdateContent.handleThumb | protected function handleThumb()
{
if ($this->thumbId !== $this->content->thumb_id) {
if ($this->thumbId === null) {
return $this->content->thumb()->dissociate();
}
$thumb = File::find($this->thumbId);
if (empty($thumb)) {
throw new InvalidArgumentException('Thumbnail file does not exist');
}
return $this->content->thumb()->associate($thumb);
}
} | php | protected function handleThumb()
{
if ($this->thumbId !== $this->content->thumb_id) {
if ($this->thumbId === null) {
return $this->content->thumb()->dissociate();
}
$thumb = File::find($this->thumbId);
if (empty($thumb)) {
throw new InvalidArgumentException('Thumbnail file does not exist');
}
return $this->content->thumb()->associate($thumb);
}
} | [
"protected",
"function",
"handleThumb",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"thumbId",
"!==",
"$",
"this",
"->",
"content",
"->",
"thumb_id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"thumbId",
"===",
"null",
")",
"{",
"return",
"$",
"this",
... | It handles thumb relation
@throws InvalidArgumentException
@return \Illuminate\Database\Eloquent\Model | [
"It",
"handles",
"thumb",
"relation"
] | a7956966d2edec54fc99ebb61eeb2f01704aa2c2 | https://github.com/GrupaZero/cms/blob/a7956966d2edec54fc99ebb61eeb2f01704aa2c2/src/Gzero/Cms/Jobs/UpdateContent.php#L97-L110 | train |
nails/module-cdn | src/Api/Controller/Manager.php | Manager.getUrl | public function getUrl()
{
if (!userHasPermission('admin:cdn:manager:object:browse')) {
$oHttpCodes = Factory::service('HttpCodes');
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
return Factory::factory('ApiResponse', 'nails/module-api')
->setData(site_url(
'admin/cdn/manager?' .
http_build_query([
'bucket' => $oInput->get('bucket'),
'callback' => $oInput->get('callback'),
])
));
} | php | public function getUrl()
{
if (!userHasPermission('admin:cdn:manager:object:browse')) {
$oHttpCodes = Factory::service('HttpCodes');
throw new ApiException(
'You do not have permission to access this resource',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
return Factory::factory('ApiResponse', 'nails/module-api')
->setData(site_url(
'admin/cdn/manager?' .
http_build_query([
'bucket' => $oInput->get('bucket'),
'callback' => $oInput->get('callback'),
])
));
} | [
"public",
"function",
"getUrl",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:cdn:manager:object:browse'",
")",
")",
"{",
"$",
"oHttpCodes",
"=",
"Factory",
"::",
"service",
"(",
"'HttpCodes'",
")",
";",
"throw",
"new",
"ApiException",
"(",
... | Returns the URL for a manager
@return array | [
"Returns",
"the",
"URL",
"for",
"a",
"manager"
] | 1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef | https://github.com/nails/module-cdn/blob/1c2ff1cbdf2aa6a7162f92c8fdbcde87c506e1ef/src/Api/Controller/Manager.php#L33-L53 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaCalculator.php | SosaCalculator.computeAll | public function computeAll() {
$root_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
$indi = Individual::getInstance($root_id, $this->tree);
if($indi){
$this->sosa_provider->deleteAll();
$this->addNode($indi, 1);
$this->flushTmpSosaTable(true);
return true;
}
return false;
} | php | public function computeAll() {
$root_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
$indi = Individual::getInstance($root_id, $this->tree);
if($indi){
$this->sosa_provider->deleteAll();
$this->addNode($indi, 1);
$this->flushTmpSosaTable(true);
return true;
}
return false;
} | [
"public",
"function",
"computeAll",
"(",
")",
"{",
"$",
"root_id",
"=",
"$",
"this",
"->",
"tree",
"->",
"getUserPreference",
"(",
"$",
"this",
"->",
"user",
",",
"'MAJ_SOSA_ROOT_ID'",
")",
";",
"$",
"indi",
"=",
"Individual",
"::",
"getInstance",
"(",
"... | Compute all Sosa ancestors from the user's root individual.
@return bool Result of the computation | [
"Compute",
"all",
"Sosa",
"ancestors",
"from",
"the",
"user",
"s",
"root",
"individual",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaCalculator.php#L68-L78 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaCalculator.php | SosaCalculator.computeFromIndividual | public function computeFromIndividual(Individual $indi) {
$dindi = new \MyArtJaub\Webtrees\Individual($indi);
$current_sosas = $dindi->getSosaNumbers();
foreach($current_sosas as $current_sosa => $gen) {
$this->sosa_provider->deleteAncestors($current_sosa);
$this->addNode($indi, $current_sosa);
}
$this->flushTmpSosaTable(true);
return true;
} | php | public function computeFromIndividual(Individual $indi) {
$dindi = new \MyArtJaub\Webtrees\Individual($indi);
$current_sosas = $dindi->getSosaNumbers();
foreach($current_sosas as $current_sosa => $gen) {
$this->sosa_provider->deleteAncestors($current_sosa);
$this->addNode($indi, $current_sosa);
}
$this->flushTmpSosaTable(true);
return true;
} | [
"public",
"function",
"computeFromIndividual",
"(",
"Individual",
"$",
"indi",
")",
"{",
"$",
"dindi",
"=",
"new",
"\\",
"MyArtJaub",
"\\",
"Webtrees",
"\\",
"Individual",
"(",
"$",
"indi",
")",
";",
"$",
"current_sosas",
"=",
"$",
"dindi",
"->",
"getSosaN... | Compute all Sosa Ancestors from a specified Individual
@param Individual $indi
@return bool Result of the computation | [
"Compute",
"all",
"Sosa",
"Ancestors",
"from",
"a",
"specified",
"Individual"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaCalculator.php#L85-L94 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaCalculator.php | SosaCalculator.addNode | protected function addNode(Individual $indi, $sosa) {
$birth_year = $indi->getEstimatedBirthDate()->gregorianYear();
$death_year = $indi->getEstimatedDeathDate()->gregorianYear();
$this->tmp_sosa_table[] = array(
'indi' => $indi->getXref(),
'sosa' => $sosa,
'birth_year' => $birth_year,
'death_year' => $death_year
);
$this->flushTmpSosaTable();
if($fam = $indi->getPrimaryChildFamily()) {
if($husb = $fam->getHusband()) $this->addNode($husb, 2 * $sosa);
if($wife = $fam->getWife()) $this->addNode($wife, 2 * $sosa + 1);
}
} | php | protected function addNode(Individual $indi, $sosa) {
$birth_year = $indi->getEstimatedBirthDate()->gregorianYear();
$death_year = $indi->getEstimatedDeathDate()->gregorianYear();
$this->tmp_sosa_table[] = array(
'indi' => $indi->getXref(),
'sosa' => $sosa,
'birth_year' => $birth_year,
'death_year' => $death_year
);
$this->flushTmpSosaTable();
if($fam = $indi->getPrimaryChildFamily()) {
if($husb = $fam->getHusband()) $this->addNode($husb, 2 * $sosa);
if($wife = $fam->getWife()) $this->addNode($wife, 2 * $sosa + 1);
}
} | [
"protected",
"function",
"addNode",
"(",
"Individual",
"$",
"indi",
",",
"$",
"sosa",
")",
"{",
"$",
"birth_year",
"=",
"$",
"indi",
"->",
"getEstimatedBirthDate",
"(",
")",
"->",
"gregorianYear",
"(",
")",
";",
"$",
"death_year",
"=",
"$",
"indi",
"->",... | Recursive method to add individual to the Sosa table, and flush it regularly
@param Individual $indi Individual to add
@param int $sosa Individual's sosa | [
"Recursive",
"method",
"to",
"add",
"individual",
"to",
"the",
"Sosa",
"table",
"and",
"flush",
"it",
"regularly"
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaCalculator.php#L101-L118 | train |
jon48/webtrees-lib | src/Webtrees/Module/Sosa/Model/SosaCalculator.php | SosaCalculator.flushTmpSosaTable | protected function flushTmpSosaTable($force = false) {
if( count($this->tmp_sosa_table)> 0 &&
($force || count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT)){
$this->sosa_provider->insertOrUpdate($this->tmp_sosa_table);
$this->tmp_sosa_table = array();
}
} | php | protected function flushTmpSosaTable($force = false) {
if( count($this->tmp_sosa_table)> 0 &&
($force || count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT)){
$this->sosa_provider->insertOrUpdate($this->tmp_sosa_table);
$this->tmp_sosa_table = array();
}
} | [
"protected",
"function",
"flushTmpSosaTable",
"(",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"tmp_sosa_table",
")",
">",
"0",
"&&",
"(",
"$",
"force",
"||",
"count",
"(",
"$",
"this",
"->",
"tmp_sosa_table",
")",... | Write sosas in the table, if the number of items is superior to the limit, or if forced.
@param bool $force Should the flush be forced | [
"Write",
"sosas",
"in",
"the",
"table",
"if",
"the",
"number",
"of",
"items",
"is",
"superior",
"to",
"the",
"limit",
"or",
"if",
"forced",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/Sosa/Model/SosaCalculator.php#L125-L131 | train |
c4studio/chronos | src/Chronos/Content/app/Console/Kernel.php | Kernel.schedule | protected function schedule(Schedule $schedule)
{
parent::schedule($schedule);
// Activate scheduled posts
$schedule->call(function() {
$content = Content::where('status_scheduled', '<=', Carbon::now())->get();
foreach ($content as $item) {
$item->status = 1;
$item->status_scheduled = null;
$item->save();
}
})->everyMinute();
} | php | protected function schedule(Schedule $schedule)
{
parent::schedule($schedule);
// Activate scheduled posts
$schedule->call(function() {
$content = Content::where('status_scheduled', '<=', Carbon::now())->get();
foreach ($content as $item) {
$item->status = 1;
$item->status_scheduled = null;
$item->save();
}
})->everyMinute();
} | [
"protected",
"function",
"schedule",
"(",
"Schedule",
"$",
"schedule",
")",
"{",
"parent",
"::",
"schedule",
"(",
"$",
"schedule",
")",
";",
"// Activate scheduled posts",
"$",
"schedule",
"->",
"call",
"(",
"function",
"(",
")",
"{",
"$",
"content",
"=",
... | Define the package's command schedule.
@param \Illuminate\Console\Scheduling\Schedule $schedule
@return void | [
"Define",
"the",
"package",
"s",
"command",
"schedule",
"."
] | df7f3a9794afaade3bee8f6be1223c98e4936cb2 | https://github.com/c4studio/chronos/blob/df7f3a9794afaade3bee8f6be1223c98e4936cb2/src/Chronos/Content/app/Console/Kernel.php#L18-L32 | train |
jon48/webtrees-lib | src/Webtrees/Module/AdminTasks/Model/TaskProvider.php | TaskProvider.loadTask | protected function loadTask($task_name) {
try {
if (file_exists($this->root_path . $task_name .'.php')) {
$task = include $this->root_path . $task_name .'.php';
if($task instanceof AbstractTask) {
$task->setProvider($this);
return $task;
}
}
}
catch(\Exception $ex) { }
return null;
} | php | protected function loadTask($task_name) {
try {
if (file_exists($this->root_path . $task_name .'.php')) {
$task = include $this->root_path . $task_name .'.php';
if($task instanceof AbstractTask) {
$task->setProvider($this);
return $task;
}
}
}
catch(\Exception $ex) { }
return null;
} | [
"protected",
"function",
"loadTask",
"(",
"$",
"task_name",
")",
"{",
"try",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"root_path",
".",
"$",
"task_name",
".",
"'.php'",
")",
")",
"{",
"$",
"task",
"=",
"include",
"$",
"this",
"->",
"roo... | Load a task object from a file.
@param string $task_name Name of the task to load. | [
"Load",
"a",
"task",
"object",
"from",
"a",
"file",
"."
] | e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7 | https://github.com/jon48/webtrees-lib/blob/e8097cdfcdbb3c9e885e7e06fe7683ed39267bb7/src/Webtrees/Module/AdminTasks/Model/TaskProvider.php#L43-L56 | train |
Rareloop/primer-core | src/Primer/Renderable/RenderList.php | RenderList.add | public function add($pattern)
{
if (is_array($pattern)) {
$this->items += $pattern;
} else {
$this->items[] = $pattern;
}
} | php | public function add($pattern)
{
if (is_array($pattern)) {
$this->items += $pattern;
} else {
$this->items[] = $pattern;
}
} | [
"public",
"function",
"add",
"(",
"$",
"pattern",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"pattern",
")",
")",
"{",
"$",
"this",
"->",
"items",
"+=",
"$",
"pattern",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"items",
"[",
"]",
"=",
"$",
"pat... | Add items to the list of items to render
@param [Pattern|Group] $pattern | [
"Add",
"items",
"to",
"the",
"list",
"of",
"items",
"to",
"render"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Renderable/RenderList.php#L30-L37 | train |
Rareloop/primer-core | src/Primer/Renderable/RenderList.php | RenderList.render | public function render($showChrome = true)
{
$html = "";
foreach ($this->items as $item) {
$html .= $item->render($showChrome);
}
return $html;
} | php | public function render($showChrome = true)
{
$html = "";
foreach ($this->items as $item) {
$html .= $item->render($showChrome);
}
return $html;
} | [
"public",
"function",
"render",
"(",
"$",
"showChrome",
"=",
"true",
")",
"{",
"$",
"html",
"=",
"\"\"",
";",
"foreach",
"(",
"$",
"this",
"->",
"items",
"as",
"$",
"item",
")",
"{",
"$",
"html",
".=",
"$",
"item",
"->",
"render",
"(",
"$",
"show... | Render the list of items
@param boolean $showChrome [description]
@return [type] [description] | [
"Render",
"the",
"list",
"of",
"items"
] | fe098d6794a4add368f97672397dc93d223a1786 | https://github.com/Rareloop/primer-core/blob/fe098d6794a4add368f97672397dc93d223a1786/src/Primer/Renderable/RenderList.php#L45-L54 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.