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
inpsyde/Wonolog
src/Controller.php
Controller.use_default_hook_listeners
public function use_default_hook_listeners() { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) { $registry ->register_listener( new HookListener\DbErrorListener() ) ->register_listener( new HookListener\FailedLoginListener() ) ->register_listener( new HookListener\HttpApiListener() ) ->register_listener( new HookListener\MailerListener() ) ->register_listener( new HookListener\QueryErrorsListener() ) ->register_listener( new HookListener\CronDebugListener() ) ->register_listener( new HookListener\WpDieHandlerListener() ); } ); return $this; }
php
public function use_default_hook_listeners() { static $done = FALSE; if ( $done ) { return $this; } $done = TRUE; add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) { $registry ->register_listener( new HookListener\DbErrorListener() ) ->register_listener( new HookListener\FailedLoginListener() ) ->register_listener( new HookListener\HttpApiListener() ) ->register_listener( new HookListener\MailerListener() ) ->register_listener( new HookListener\QueryErrorsListener() ) ->register_listener( new HookListener\CronDebugListener() ) ->register_listener( new HookListener\WpDieHandlerListener() ); } ); return $this; }
[ "public", "function", "use_default_hook_listeners", "(", ")", "{", "static", "$", "done", "=", "FALSE", ";", "if", "(", "$", "done", ")", "{", "return", "$", "this", ";", "}", "$", "done", "=", "TRUE", ";", "add_action", "(", "HookListenersRegistry", "::...
Tell Wonolog to use all default hook listeners. @return Controller
[ "Tell", "Wonolog", "to", "use", "all", "default", "hook", "listeners", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L310-L335
train
inpsyde/Wonolog
src/Controller.php
Controller.use_hook_listener
public function use_hook_listener( HookListenerInterface $listener ) { add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) use ( $listener ) { $registry->register_listener( $listener ); } ); return $this; }
php
public function use_hook_listener( HookListenerInterface $listener ) { add_action( HookListenersRegistry::ACTION_REGISTER, function ( HookListenersRegistry $registry ) use ( $listener ) { $registry->register_listener( $listener ); } ); return $this; }
[ "public", "function", "use_hook_listener", "(", "HookListenerInterface", "$", "listener", ")", "{", "add_action", "(", "HookListenersRegistry", "::", "ACTION_REGISTER", ",", "function", "(", "HookListenersRegistry", "$", "registry", ")", "use", "(", "$", "listener", ...
Tell Wonolog to use given hook listener. @param HookListenerInterface $listener @return Controller
[ "Tell", "Wonolog", "to", "use", "given", "hook", "listener", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L344-L355
train
inpsyde/Wonolog
src/Handler/DefaultHandlerFactory.php
DefaultHandlerFactory.maybe_create_htaccess
private function maybe_create_htaccess( $folder ) { if ( ! $folder || ! is_dir( $folder ) || ! is_writable( $folder ) || file_exists( "{$folder}/.htaccess" ) || ! defined( 'WP_CONTENT_DIR' ) ) { return $folder; } $target_dir = realpath( $folder ); $content_dir = realpath( WP_CONTENT_DIR ); // Sorry, we can't allow logs to be put straight in content folder. That's too dangerous. if ( $target_dir === $content_dir ) { $target_dir .= DIRECTORY_SEPARATOR . 'wonolog'; } // If target dir is outside content dir, its security is up to user. if ( strpos( $target_dir, $content_dir ) !== 0 ) { return $target_dir; } // Let's disable error reporting: too much file operations which might fail, nothing can log them, and package // is fully functional even if failing happens. Silence looks like best option here. set_error_handler( '__return_true' ); $handle = fopen( "{$folder}/.htaccess", 'w' ); if ( $handle && flock( $handle, LOCK_EX ) ) { $htaccess = <<<'HTACCESS' <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Deny from all </IfModule> HTACCESS; if ( fwrite( $handle, $htaccess ) ) { flock( $handle, LOCK_UN ); chmod( "{$folder}/.htaccess", 0444 ); } } fclose( $handle ); restore_error_handler(); return $target_dir; }
php
private function maybe_create_htaccess( $folder ) { if ( ! $folder || ! is_dir( $folder ) || ! is_writable( $folder ) || file_exists( "{$folder}/.htaccess" ) || ! defined( 'WP_CONTENT_DIR' ) ) { return $folder; } $target_dir = realpath( $folder ); $content_dir = realpath( WP_CONTENT_DIR ); // Sorry, we can't allow logs to be put straight in content folder. That's too dangerous. if ( $target_dir === $content_dir ) { $target_dir .= DIRECTORY_SEPARATOR . 'wonolog'; } // If target dir is outside content dir, its security is up to user. if ( strpos( $target_dir, $content_dir ) !== 0 ) { return $target_dir; } // Let's disable error reporting: too much file operations which might fail, nothing can log them, and package // is fully functional even if failing happens. Silence looks like best option here. set_error_handler( '__return_true' ); $handle = fopen( "{$folder}/.htaccess", 'w' ); if ( $handle && flock( $handle, LOCK_EX ) ) { $htaccess = <<<'HTACCESS' <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Deny from all </IfModule> HTACCESS; if ( fwrite( $handle, $htaccess ) ) { flock( $handle, LOCK_UN ); chmod( "{$folder}/.htaccess", 0444 ); } } fclose( $handle ); restore_error_handler(); return $target_dir; }
[ "private", "function", "maybe_create_htaccess", "(", "$", "folder", ")", "{", "if", "(", "!", "$", "folder", "||", "!", "is_dir", "(", "$", "folder", ")", "||", "!", "is_writable", "(", "$", "folder", ")", "||", "file_exists", "(", "\"{$folder}/.htaccess\"...
When the log root folder is inside WordPress content folder, the logs are going to be publicly accessible, and that is in best case a privacy leakage issue, in worst case a security threat. We try to write an .htaccess file to prevent access to them. This guarantees nothing, because .htaccess can be ignored depending web server in use and its configuration, but at least we tried. To configure a custom log folder outside content folder is also highly recommended in documentation. @param string $folder @return string
[ "When", "the", "log", "root", "folder", "is", "inside", "WordPress", "content", "folder", "the", "logs", "are", "going", "to", "be", "publicly", "accessible", "and", "that", "is", "in", "best", "case", "a", "privacy", "leakage", "issue", "in", "worst", "ca...
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Handler/DefaultHandlerFactory.php#L173-L225
train
inpsyde/Wonolog
src/HookListener/HttpApiListener.php
HttpApiListener.log_http_error
private function log_http_error( $data, $context, $class, array $args = [], $url = '' ) { $msg = 'WP HTTP API Error'; $response = is_array( $data ) && isset( $data[ 'response' ] ) && is_array( $data[ 'response' ] ) ? shortcode_atts( [ 'message' => '', 'code' => '', 'body' => '' ], $data[ 'response' ] ) : [ 'message' => '', 'code' => '', 'body' => '' ]; if ( is_wp_error( $data ) ) { $msg .= ': ' . $data->get_error_message(); } elseif ( is_string( $response[ 'message' ] ) && $response[ 'message' ] ) { $msg .= ': ' . $response[ 'message' ]; } $log_context = [ 'transport' => $class, 'context' => $context, 'query_args' => $args, 'url' => $url, ]; if ( $response[ 'body' ] && is_string( $response[ 'body' ] ) ) { $log_context[ 'response_body' ] = strlen( $response[ 'body' ] ) <= 300 ? $response[ 'body' ] : substr( $response[ 'body' ], 0, 300 ) . '...'; } if ( array_key_exists( 'code', $response ) && is_scalar( $response[ 'code' ] ) ) { $msg .= " - Response code: {$response[ 'code' ]}"; ( is_array( $data ) && ! empty( $data[ 'headers' ] ) ) and $log_context[ 'headers' ] = $data[ 'headers' ]; } return new Error( rtrim( $msg, '.' ) . '.', Channels::HTTP, $log_context ); }
php
private function log_http_error( $data, $context, $class, array $args = [], $url = '' ) { $msg = 'WP HTTP API Error'; $response = is_array( $data ) && isset( $data[ 'response' ] ) && is_array( $data[ 'response' ] ) ? shortcode_atts( [ 'message' => '', 'code' => '', 'body' => '' ], $data[ 'response' ] ) : [ 'message' => '', 'code' => '', 'body' => '' ]; if ( is_wp_error( $data ) ) { $msg .= ': ' . $data->get_error_message(); } elseif ( is_string( $response[ 'message' ] ) && $response[ 'message' ] ) { $msg .= ': ' . $response[ 'message' ]; } $log_context = [ 'transport' => $class, 'context' => $context, 'query_args' => $args, 'url' => $url, ]; if ( $response[ 'body' ] && is_string( $response[ 'body' ] ) ) { $log_context[ 'response_body' ] = strlen( $response[ 'body' ] ) <= 300 ? $response[ 'body' ] : substr( $response[ 'body' ], 0, 300 ) . '...'; } if ( array_key_exists( 'code', $response ) && is_scalar( $response[ 'code' ] ) ) { $msg .= " - Response code: {$response[ 'code' ]}"; ( is_array( $data ) && ! empty( $data[ 'headers' ] ) ) and $log_context[ 'headers' ] = $data[ 'headers' ]; } return new Error( rtrim( $msg, '.' ) . '.', Channels::HTTP, $log_context ); }
[ "private", "function", "log_http_error", "(", "$", "data", ",", "$", "context", ",", "$", "class", ",", "array", "$", "args", "=", "[", "]", ",", "$", "url", "=", "''", ")", "{", "$", "msg", "=", "'WP HTTP API Error'", ";", "$", "response", "=", "i...
Log any error for HTTP API. @param \WP_Error|array $data @param string $context @param string $class @param array $args @param string $url @return Error
[ "Log", "any", "error", "for", "HTTP", "API", "." ]
87ed9a60c6f5cc3a057db857273dc504efc5ad9f
https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/HttpApiListener.php#L169-L201
train
phpsci/phpsci
src/PHPSci/Utils/ValidationUtils.php
ValidationUtils.check_X_y
public static function check_X_y(\CArray $X, \CArray $y, bool $accept_sparse=false, bool $copy=False, bool $force_all_finite=True, bool $ensure_2d=True, bool $allow_nd=False, bool $multi_output=False, int $ensure_min_samples=1, int $ensure_min_features=1, bool $y_numeric=False, $estimator=null) { return [$X, $y]; }
php
public static function check_X_y(\CArray $X, \CArray $y, bool $accept_sparse=false, bool $copy=False, bool $force_all_finite=True, bool $ensure_2d=True, bool $allow_nd=False, bool $multi_output=False, int $ensure_min_samples=1, int $ensure_min_features=1, bool $y_numeric=False, $estimator=null) { return [$X, $y]; }
[ "public", "static", "function", "check_X_y", "(", "\\", "CArray", "$", "X", ",", "\\", "CArray", "$", "y", ",", "bool", "$", "accept_sparse", "=", "false", ",", "bool", "$", "copy", "=", "False", ",", "bool", "$", "force_all_finite", "=", "True", ",", ...
Input validation for standard estimators. @param \CArray $X @param \CArray $y @param bool $accept_sparse @param bool $copy @param bool $force_all_finite @param bool $ensure_2d @param bool $allow_nd @param bool $multi_output @param int $ensure_min_samples @param int $ensure_min_features @param bool $y_numeric @param bool $warn_on_dtype @param null $estimator @return array
[ "Input", "validation", "for", "standard", "estimators", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/ValidationUtils.php#L32-L38
train
phpsci/phpsci
src/PHPSci/Utils/DatasetUtils.php
DatasetUtils.make_dataset
public static function make_dataset(\CArray $X, \CArray $y, $sample_weight, $random_state=null) : array { $seed = rand(0, 10); $dataset = new ArrayDataset($X, $y, $sample_weight, $seed); $intercept_decay = 1.0; return [$dataset, $intercept_decay]; }
php
public static function make_dataset(\CArray $X, \CArray $y, $sample_weight, $random_state=null) : array { $seed = rand(0, 10); $dataset = new ArrayDataset($X, $y, $sample_weight, $seed); $intercept_decay = 1.0; return [$dataset, $intercept_decay]; }
[ "public", "static", "function", "make_dataset", "(", "\\", "CArray", "$", "X", ",", "\\", "CArray", "$", "y", ",", "$", "sample_weight", ",", "$", "random_state", "=", "null", ")", ":", "array", "{", "$", "seed", "=", "rand", "(", "0", ",", "10", "...
Create ``Dataset`` abstraction for sparse and dense inputs. This also returns the ``intercept_decay`` which is different for sparse datasets. @param \CArray $X @param \CArray $y @param $sample_weight @param null $random_state @return array
[ "Create", "Dataset", "abstraction", "for", "sparse", "and", "dense", "inputs", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/DatasetUtils.php#L23-L29
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.add
public static function add(\CArray $a, \CArray $b): \CArray { return parent::add($a, $b); }
php
public static function add(\CArray $a, \CArray $b): \CArray { return parent::add($a, $b); }
[ "public", "static", "function", "add", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "add", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Add arguments element-wise. @param \CArray $a Target CArray a @param \CArray $b Target CArray b @return \CArray The sum of $a and $b, element-wise.
[ "Add", "arguments", "element", "-", "wise", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L36-L39
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.subtract
public static function subtract(\CArray $a, \CArray $b): \CArray { return parent::subtract($a, $b); }
php
public static function subtract(\CArray $a, \CArray $b): \CArray { return parent::subtract($a, $b); }
[ "public", "static", "function", "subtract", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "subtract", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Subtract two CArrays, element-wise. @param \CArray $a Target CArray $a @param \CArray $b Target CArray $b @return \CArray The difference of $a and $b, element-wise.
[ "Subtract", "two", "CArrays", "element", "-", "wise", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L49-L52
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.sum
public static function sum(\CArray $a, int $axis = null): \CArray { if (!isset($axis)) { return parent::sum($a); } return parent::sum($a, $axis); }
php
public static function sum(\CArray $a, int $axis = null): \CArray { if (!isset($axis)) { return parent::sum($a); } return parent::sum($a, $axis); }
[ "public", "static", "function", "sum", "(", "\\", "CArray", "$", "a", ",", "int", "$", "axis", "=", "null", ")", ":", "\\", "CArray", "{", "if", "(", "!", "isset", "(", "$", "axis", ")", ")", "{", "return", "parent", "::", "sum", "(", "$", "a",...
Sum of target CArray elements over a given axis. @param \CArray $a Target CArray @param int $axis (Optional) Axis or axes along which a sum is performed. Defaults to null. @return \CArray An CArray with the same shape as $a, with the specified axis removed.
[ "Sum", "of", "target", "CArray", "elements", "over", "a", "given", "axis", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L63-L70
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.eye
public static function eye(int $x, int $y, int $k = 0): \CArray { return parent::eye($x, $y, $k); }
php
public static function eye(int $x, int $y, int $k = 0): \CArray { return parent::eye($x, $y, $k); }
[ "public", "static", "function", "eye", "(", "int", "$", "x", ",", "int", "$", "y", ",", "int", "$", "k", "=", "0", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "eye", "(", "$", "x", ",", "$", "y", ",", "$", "k", ")", ";", "}" ]
Return CArray filled with zeros and ones in the diagonal provided diagonal index. @param int $x Number of rows (2-D) or width (1-D) @param int $y Number of cols (2-D) or 0 (1-D) @param int $k (Optional) Diagonal Index. Defaults to 0. @return \CArray
[ "Return", "CArray", "filled", "with", "zeros", "and", "ones", "in", "the", "diagonal", "provided", "diagonal", "index", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L286-L289
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.ones
public static function ones(int $x, int $y): \CArray { return parent::ones($x, $y); }
php
public static function ones(int $x, int $y): \CArray { return parent::ones($x, $y); }
[ "public", "static", "function", "ones", "(", "int", "$", "x", ",", "int", "$", "y", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "ones", "(", "$", "x", ",", "$", "y", ")", ";", "}" ]
Return new CArray with same shape as target CArray filled with zeros. @param int $x Number of rows (2-D) or width (1-D) @param int $y Number of cols (2-D) or 0 (1-D) @return \CArray CArray with shape ($x, $y) filled with ones.
[ "Return", "new", "CArray", "with", "same", "shape", "as", "target", "CArray", "filled", "with", "zeros", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L313-L316
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.full
public static function full($num, int $x, int $y): \CArray { return parent::full($num, $x, $y); }
php
public static function full($num, int $x, int $y): \CArray { return parent::full($num, $x, $y); }
[ "public", "static", "function", "full", "(", "$", "num", ",", "int", "$", "x", ",", "int", "$", "y", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "full", "(", "$", "num", ",", "$", "x", ",", "$", "y", ")", ";", "}" ]
Return new CArray filled with user provided number. @param double $num Number to fill the new CArray @param int $x Number of rows (2-D) or width (1-D) @param int $y Number of cols (2-D) or 0 (1-D) @return \CArray New CArray with shape ($x, $y) filled with $num
[ "Return", "new", "CArray", "filled", "with", "user", "provided", "number", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L365-L368
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.arange
public static function arange($stop, $start, $step): \CArray { return parent::arange($stop, $start, $step); }
php
public static function arange($stop, $start, $step): \CArray { return parent::arange($stop, $start, $step); }
[ "public", "static", "function", "arange", "(", "$", "stop", ",", "$", "start", ",", "$", "step", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "arange", "(", "$", "stop", ",", "$", "start", ",", "$", "step", ")", ";", "}" ]
CArray with evenly spaced values within a given interval. @param $stop End of interval @param $start (Optional) Start of interval. Default is 0. @param $step (Optional) Spacing between values. Default is 1. @return \CArray CArray with evenly spaced values.
[ "CArray", "with", "evenly", "spaced", "values", "within", "a", "given", "interval", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L419-L422
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.linspace
public static function linspace($start, $stop, int $num): \CArray { return parent::linspace($start, $stop, $num); }
php
public static function linspace($start, $stop, int $num): \CArray { return parent::linspace($start, $stop, $num); }
[ "public", "static", "function", "linspace", "(", "$", "start", ",", "$", "stop", ",", "int", "$", "num", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "linspace", "(", "$", "start", ",", "$", "stop", ",", "$", "num", ")", ";", "}" ]
CArray with evenly spaced numbers over a specified interval. @param $start The starting value of the sequence. @param $stop The end value of the sequence @param int $num Number of samples to generate. Default is 50. @return \CArray
[ "CArray", "with", "evenly", "spaced", "numbers", "over", "a", "specified", "interval", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L433-L436
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.logspace
public static function logspace($start, $stop, int $num, $base): \CArray { return parent::logspace($start, $stop, $num, $base); }
php
public static function logspace($start, $stop, int $num, $base): \CArray { return parent::logspace($start, $stop, $num, $base); }
[ "public", "static", "function", "logspace", "(", "$", "start", ",", "$", "stop", ",", "int", "$", "num", ",", "$", "base", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "logspace", "(", "$", "start", ",", "$", "stop", ",", "$", "num", ...
CArray with numbers spaced evenly on a log scale. @param $start The starting value of the sequence. @param $stop The final value of the sequence @param int $num (optional) Number of samples to generate. Default is 50. @param $base (optional) The base of the log space. @return \CArray $num samples, equally spaced on a log scale.
[ "CArray", "with", "numbers", "spaced", "evenly", "on", "a", "log", "scale", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L448-L451
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.matmul
public static function matmul(\CArray $a, \CArray $b): \CArray { return parent::matmul($a, $b); }
php
public static function matmul(\CArray $a, \CArray $b): \CArray { return parent::matmul($a, $b); }
[ "public", "static", "function", "matmul", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "matmul", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Matrix product of two CArrays. - If both arguments are 2-D they are multiplied like conventional matrices. - If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. - If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. Multiplication by a scalar is not allowed. @param \CArray $a Target $a CArray @param \CArray $b Target $b CArray @return \CArray Dot product of $a and $b. If both are 1D, them a 0 dimensional (scalar) CArray will be returned
[ "Matrix", "product", "of", "two", "CArrays", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L483-L486
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.inner
public static function inner(\CArray $a, \CArray $b): \CArray { return parent::inner($a, $b); }
php
public static function inner(\CArray $a, \CArray $b): \CArray { return parent::inner($a, $b); }
[ "public", "static", "function", "inner", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "inner", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Inner product of two CArrays. If 1D - Ordinary inner product of vectors If 2D - Sum product over the last axes. @param \CArray $a Target $a CArray - Last Dimension must match $b @param \CArray $b Target $b CArray - Last Dimension must match $a @return \CArray Inner product of $a and $b
[ "Inner", "product", "of", "two", "CArrays", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L499-L502
train
phpsci/phpsci
src/PHPSci/Kernel/CArray/Wrapper.php
Wrapper.solve
public static function solve(\CArray $a, \CArray $b): \CArray { return parent::solve($a, $b); }
php
public static function solve(\CArray $a, \CArray $b): \CArray { return parent::solve($a, $b); }
[ "public", "static", "function", "solve", "(", "\\", "CArray", "$", "a", ",", "\\", "CArray", "$", "b", ")", ":", "\\", "CArray", "{", "return", "parent", "::", "solve", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
Solve a linear matrix equation @param \CArray $a Coefficient CArray @param \CArray $b Ordinate CArray @return \CArray Solution of the system $a x = $b. Returned shape is same as $b.
[ "Solve", "a", "linear", "matrix", "equation" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Kernel/CArray/Wrapper.php#L561-L564
train
phpsci/phpsci
src/PHPSci/NaiveBayes/GaussianNB.php
GaussianNB.fit
public function fit(\CArray $X, \CArray $y, \CArray $sample_weight = null) { list($X, $y) = ValidationUtils::check_X_y($X, $y); return $this->_partial_fit($X, $y, CArray::unique($y), true, $sample_weight); }
php
public function fit(\CArray $X, \CArray $y, \CArray $sample_weight = null) { list($X, $y) = ValidationUtils::check_X_y($X, $y); return $this->_partial_fit($X, $y, CArray::unique($y), true, $sample_weight); }
[ "public", "function", "fit", "(", "\\", "CArray", "$", "X", ",", "\\", "CArray", "$", "y", ",", "\\", "CArray", "$", "sample_weight", "=", "null", ")", "{", "list", "(", "$", "X", ",", "$", "y", ")", "=", "ValidationUtils", "::", "check_X_y", "(", ...
Fit Gaussian Naive Bayes according to X, y @param \CArray $X @param \CArray $y @param \CArray|null $sample_weight @return void @throws \PHPSci\Exceptions\ValueErrorException
[ "Fit", "Gaussian", "Naive", "Bayes", "according", "to", "X", "y" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/NaiveBayes/GaussianNB.php#L195-L199
train
phpsci/phpsci
src/PHPSci/Utils/MulticlassUtils.php
MulticlassUtils._check_partial_fit_first_call
public static function _check_partial_fit_first_call(Classifier $clf, \CArray $classes = null) { if($clf->classes_() == null && !isset($classes) ) { throw new ValueErrorException("classes must be passed on the first call to partial_fit."); } if(isset($classes)) { if($clf->classes_()) { } else { $clf->classes_(CArray::unique($classes)); return true; } } # classes is None and clf.classes_ has already previously been set: # nothing to do return false; }
php
public static function _check_partial_fit_first_call(Classifier $clf, \CArray $classes = null) { if($clf->classes_() == null && !isset($classes) ) { throw new ValueErrorException("classes must be passed on the first call to partial_fit."); } if(isset($classes)) { if($clf->classes_()) { } else { $clf->classes_(CArray::unique($classes)); return true; } } # classes is None and clf.classes_ has already previously been set: # nothing to do return false; }
[ "public", "static", "function", "_check_partial_fit_first_call", "(", "Classifier", "$", "clf", ",", "\\", "CArray", "$", "classes", "=", "null", ")", "{", "if", "(", "$", "clf", "->", "classes_", "(", ")", "==", "null", "&&", "!", "isset", "(", "$", "...
Private helper function for factorizing common classes param logic Estimators that implement the ``partial_fit`` API need to be provided with the list of possible classes at the first call to partial_fit. Subsequent calls to partial_fit should check that ``classes`` is still consistent with a previous value of ``clf.classes_`` when provided. This function returns True if it detects that this was the first call to ``partial_fit`` on ``clf``. In that case the ``classes_`` attribute is also set on ``clf``. @see https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/multiclass.py @param Classifier $clf @param \CArray|null $classes @return bool @throws ValueErrorException
[ "Private", "helper", "function", "for", "factorizing", "common", "classes", "param", "logic" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/MulticlassUtils.php#L34-L51
train
phpsci/phpsci
src/PHPSci/Utils/Datasets/SequentialDataset.php
SequentialDataset.next
public function next(\CArray $x_data_ptr = null, int $x_ind_ptr = null, int $nnz = null, float $y, float $sample_weight = null) { $current_index = $this->_get_next_index(); return $this->_sample($x_data_ptr, $x_ind_ptr, $nnz, $y, $sample_weight, $current_index); }
php
public function next(\CArray $x_data_ptr = null, int $x_ind_ptr = null, int $nnz = null, float $y, float $sample_weight = null) { $current_index = $this->_get_next_index(); return $this->_sample($x_data_ptr, $x_ind_ptr, $nnz, $y, $sample_weight, $current_index); }
[ "public", "function", "next", "(", "\\", "CArray", "$", "x_data_ptr", "=", "null", ",", "int", "$", "x_ind_ptr", "=", "null", ",", "int", "$", "nnz", "=", "null", ",", "float", "$", "y", ",", "float", "$", "sample_weight", "=", "null", ")", "{", "$...
Get the next example ``x`` from the dataset. This method gets the next sample looping sequentially over all samples. The order can be shuffled with the method ``shuffle``. Shuffling once before iterating over all samples corresponds to a random draw without replacement. It is used for instance in SGD solver. @param \CArray $x_data_ptr A pointer to the double array which holds the feature values of the next example. @param int $x_ind_ptr A pointer to the int array which holds the feature indices of the next example. @param int $nnz A pointer to an int holding the number of non-zero values of the next example. @param float $y The target value of the next example. @param float $sample_weight The weight of the next example.
[ "Get", "the", "next", "example", "x", "from", "the", "dataset", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/Datasets/SequentialDataset.php#L106-L110
train
phpsci/phpsci
src/PHPSci/NaiveBayes/BaseNaiveBayes.php
BaseNaiveBayes.predict
public function predict(\CArray $X) { $predicted_classes = []; $jll = $this->_joint_log_likelihood($X); $predictions = CArray::toArray(CArray::argmax($jll, 1)); foreach($predictions as $pred) { $predicted_classes[] = $this->classes_[[(int)$pred]]; } return $predicted_classes; }
php
public function predict(\CArray $X) { $predicted_classes = []; $jll = $this->_joint_log_likelihood($X); $predictions = CArray::toArray(CArray::argmax($jll, 1)); foreach($predictions as $pred) { $predicted_classes[] = $this->classes_[[(int)$pred]]; } return $predicted_classes; }
[ "public", "function", "predict", "(", "\\", "CArray", "$", "X", ")", "{", "$", "predicted_classes", "=", "[", "]", ";", "$", "jll", "=", "$", "this", "->", "_joint_log_likelihood", "(", "$", "X", ")", ";", "$", "predictions", "=", "CArray", "::", "to...
Perform classification on an array of test vectors X. @param \CArray $X @return void
[ "Perform", "classification", "on", "an", "array", "of", "test", "vectors", "X", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/NaiveBayes/BaseNaiveBayes.php#L28-L37
train
phpsci/phpsci
src/PHPSci/Utils/WeightUtils.php
WeightUtils.compute_class_weight
public static function compute_class_weight(\CArray $class_weight = null, \CArray $classes, \CArray $y) : \CArray { if(CArray::unique($y)->x - CArray::unique($classes)->x) { throw new ValueErrorException("classes should include all valid labels that can be in y"); } if(!isset($class_weight) || $class_weight->x == 0) { # uniform class weights $weight = CArray::ones($classes->x, 0); } return $weight; }
php
public static function compute_class_weight(\CArray $class_weight = null, \CArray $classes, \CArray $y) : \CArray { if(CArray::unique($y)->x - CArray::unique($classes)->x) { throw new ValueErrorException("classes should include all valid labels that can be in y"); } if(!isset($class_weight) || $class_weight->x == 0) { # uniform class weights $weight = CArray::ones($classes->x, 0); } return $weight; }
[ "public", "static", "function", "compute_class_weight", "(", "\\", "CArray", "$", "class_weight", "=", "null", ",", "\\", "CArray", "$", "classes", ",", "\\", "CArray", "$", "y", ")", ":", "\\", "CArray", "{", "if", "(", "CArray", "::", "unique", "(", ...
Estimate class weights for unbalanced datasets. @see https://github.com/scikit-learn/scikit-learn/blob/a7e17117bb15eb3f51ebccc1bd53e42fcb4e6cd8/sklearn/utils/class_weight.py#L9 @param \CArray $class_weight @param \CArray $classes @param \CArray $y @return \CArray|void @throws ValueErrorException
[ "Estimate", "class", "weights", "for", "unbalanced", "datasets", "." ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Utils/WeightUtils.php#L24-L35
train
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.drawLabels
private function drawLabels() { $min_value = CArray::amin($this->data[0]); $max_value = CArray::amax($this->data[0]); $left = CArray::toArray( CArray::linspace($min_value, 0, 5, false) ); $right = CArray::toArray( CArray::linspace(0, $max_value, 5) ); # Remove 0 so it don't repeat array_shift($right); $bottom_values = array_merge( $left, $right ); $padding = CArray::toArray( CArray::linspace($this->grid_padding, $this->gridWidth(), count($bottom_values)) ); foreach($bottom_values as $k => $value) { $this->addLine( $padding[$k] + ($this->grid_padding/2), $this->height - $this->grid_padding, $padding[$k] + ($this->grid_padding/2), $this->height - ($this->grid_padding/1.5) ); $this->addText( $value, $padding[$k] + ($this->grid_padding/2.5), $this->height - ($this->grid_padding/2) ); } $min_value = CArray::amin($this->data[1]); $max_value = CArray::amax($this->data[1]); $side_values = CArray::toArray( CArray::linspace($min_value, $max_value, 6, false) ); $padding = CArray::toArray( CArray::linspace($this->gridHeight(), $this->grid_padding, count($side_values)) ); foreach($side_values as $k => $value) { $this->addLine( $this->grid_padding, $padding[$k] + ($this->grid_padding/2), ($this->grid_padding/1.5), $padding[$k] + ($this->grid_padding/2) ); $this->addText( round($value, 2), $this->grid_padding * 0.2, $padding[$k] + ($this->grid_padding/2.5) ); } }
php
private function drawLabels() { $min_value = CArray::amin($this->data[0]); $max_value = CArray::amax($this->data[0]); $left = CArray::toArray( CArray::linspace($min_value, 0, 5, false) ); $right = CArray::toArray( CArray::linspace(0, $max_value, 5) ); # Remove 0 so it don't repeat array_shift($right); $bottom_values = array_merge( $left, $right ); $padding = CArray::toArray( CArray::linspace($this->grid_padding, $this->gridWidth(), count($bottom_values)) ); foreach($bottom_values as $k => $value) { $this->addLine( $padding[$k] + ($this->grid_padding/2), $this->height - $this->grid_padding, $padding[$k] + ($this->grid_padding/2), $this->height - ($this->grid_padding/1.5) ); $this->addText( $value, $padding[$k] + ($this->grid_padding/2.5), $this->height - ($this->grid_padding/2) ); } $min_value = CArray::amin($this->data[1]); $max_value = CArray::amax($this->data[1]); $side_values = CArray::toArray( CArray::linspace($min_value, $max_value, 6, false) ); $padding = CArray::toArray( CArray::linspace($this->gridHeight(), $this->grid_padding, count($side_values)) ); foreach($side_values as $k => $value) { $this->addLine( $this->grid_padding, $padding[$k] + ($this->grid_padding/2), ($this->grid_padding/1.5), $padding[$k] + ($this->grid_padding/2) ); $this->addText( round($value, 2), $this->grid_padding * 0.2, $padding[$k] + ($this->grid_padding/2.5) ); } }
[ "private", "function", "drawLabels", "(", ")", "{", "$", "min_value", "=", "CArray", "::", "amin", "(", "$", "this", "->", "data", "[", "0", "]", ")", ";", "$", "max_value", "=", "CArray", "::", "amax", "(", "$", "this", "->", "data", "[", "0", "...
Draw Y Bottom Labels
[ "Draw", "Y", "Bottom", "Labels" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L167-L233
train
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.addDot
public function addDot($x, $y, $w, $h, $rgb = [0, 0, 255]) { // choose a color for the ellipse $ellipseColor = imagecolorallocate($this->image(), $rgb[0], $rgb[1], $rgb[2]); // draw the blue ellipse imagefilledellipse($this->image(), $x, $y, $w, $h, $ellipseColor); }
php
public function addDot($x, $y, $w, $h, $rgb = [0, 0, 255]) { // choose a color for the ellipse $ellipseColor = imagecolorallocate($this->image(), $rgb[0], $rgb[1], $rgb[2]); // draw the blue ellipse imagefilledellipse($this->image(), $x, $y, $w, $h, $ellipseColor); }
[ "public", "function", "addDot", "(", "$", "x", ",", "$", "y", ",", "$", "w", ",", "$", "h", ",", "$", "rgb", "=", "[", "0", ",", "0", ",", "255", "]", ")", "{", "// choose a color for the ellipse", "$", "ellipseColor", "=", "imagecolorallocate", "(",...
Add dot to image @param $x @param $y @param $w @param $h @param array $rgb
[ "Add", "dot", "to", "image" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L278-L284
train
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.addRectangle
public function addRectangle($x1, $y1, $x2, $y2, $colors = [0, 0, 0]) { $color = imagecolorallocate($this->image(), $colors[0], $colors[1], $colors[2]); imagerectangle ( $this->image() , $x1 , $y1 , $x2 , $y2 , $color ); }
php
public function addRectangle($x1, $y1, $x2, $y2, $colors = [0, 0, 0]) { $color = imagecolorallocate($this->image(), $colors[0], $colors[1], $colors[2]); imagerectangle ( $this->image() , $x1 , $y1 , $x2 , $y2 , $color ); }
[ "public", "function", "addRectangle", "(", "$", "x1", ",", "$", "y1", ",", "$", "x2", ",", "$", "y2", ",", "$", "colors", "=", "[", "0", ",", "0", ",", "0", "]", ")", "{", "$", "color", "=", "imagecolorallocate", "(", "$", "this", "->", "image"...
Add Rectangle to Graph @param $x1 @param $y1 @param $x2 @param $y2 @param array $colors
[ "Add", "Rectangle", "to", "Graph" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L294-L298
train
phpsci/phpsci
src/PHPSci/Plot/Plotter.php
Plotter.generateGrid
private function generateGrid() { $this->addRectangle( $this->grid_padding, ($this->height-$this->grid_padding), ($this->width-$this->grid_padding), $this->grid_padding ); }
php
private function generateGrid() { $this->addRectangle( $this->grid_padding, ($this->height-$this->grid_padding), ($this->width-$this->grid_padding), $this->grid_padding ); }
[ "private", "function", "generateGrid", "(", ")", "{", "$", "this", "->", "addRectangle", "(", "$", "this", "->", "grid_padding", ",", "(", "$", "this", "->", "height", "-", "$", "this", "->", "grid_padding", ")", ",", "(", "$", "this", "->", "width", ...
Generate Graph Grid
[ "Generate", "Graph", "Grid" ]
d25b705ad63e4af8ed1dbc8a1c4f776a97312286
https://github.com/phpsci/phpsci/blob/d25b705ad63e4af8ed1dbc8a1c4f776a97312286/src/PHPSci/Plot/Plotter.php#L303-L311
train
polyfony-inc/polyfony
Private/Polyfony/Query/Convert.php
Convert.valueFromDatabase
public static function valueFromDatabase($column_name, $raw_value, $get_it_raw=false) { // if we want the raw result ok, but exclude arrays that can never be gotten raw if($get_it_raw === true && substr($column_name,-6,6) != '_array') { // return as is $value = $raw_value; } // if the column_name contains an array elseif(substr($column_name,-6,6) == '_array') { // decode the array $value = json_decode($raw_value,true); } // if the column_name contains a size value elseif(substr($column_name,-5,5) == '_size') { // convert to human size $value = \Polyfony\Format::size($raw_value); } // if the column_name contains a datetime elseif(substr($column_name,-9,9) == '_datetime') { // if the value is set $value = date('d/m/Y H:i', $raw_value); } // if the column_name contains a date elseif( substr($column_name,-5,5) == '_date' || substr($column_name,-3,3) == '_at' || substr($column_name,-3,3) == '_on' ) { // if the value is set $value = date('d/m/Y', $raw_value); } // not a magic column name else { // we secure it against XSS $value = \Polyfony\Format::htmlSafe($raw_value); } // return the converted (or not) value return $value; }
php
public static function valueFromDatabase($column_name, $raw_value, $get_it_raw=false) { // if we want the raw result ok, but exclude arrays that can never be gotten raw if($get_it_raw === true && substr($column_name,-6,6) != '_array') { // return as is $value = $raw_value; } // if the column_name contains an array elseif(substr($column_name,-6,6) == '_array') { // decode the array $value = json_decode($raw_value,true); } // if the column_name contains a size value elseif(substr($column_name,-5,5) == '_size') { // convert to human size $value = \Polyfony\Format::size($raw_value); } // if the column_name contains a datetime elseif(substr($column_name,-9,9) == '_datetime') { // if the value is set $value = date('d/m/Y H:i', $raw_value); } // if the column_name contains a date elseif( substr($column_name,-5,5) == '_date' || substr($column_name,-3,3) == '_at' || substr($column_name,-3,3) == '_on' ) { // if the value is set $value = date('d/m/Y', $raw_value); } // not a magic column name else { // we secure it against XSS $value = \Polyfony\Format::htmlSafe($raw_value); } // return the converted (or not) value return $value; }
[ "public", "static", "function", "valueFromDatabase", "(", "$", "column_name", ",", "$", "raw_value", ",", "$", "get_it_raw", "=", "false", ")", "{", "// if we want the raw result ok, but exclude arrays that can never be gotten raw", "if", "(", "$", "get_it_raw", "===", ...
convert a value comming from the database, to its original type
[ "convert", "a", "value", "comming", "from", "the", "database", "to", "its", "original", "type" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Convert.php#L9-L48
train
polyfony-inc/polyfony
Private/Polyfony/Query/Convert.php
Convert.columnToPlaceholder
public static function columnToPlaceholder( string $quote_symbol, string $column, $allow_wildcard = false ) :array { // apply the secure regex for the column name $column = preg_replace(($allow_wildcard ? '/[^a-zA-Z0-9_\.\*]/' : '/[^a-zA-Z0-9_\.]/'), '', $column); // cleanup the placeholder $placeholder = str_replace(['.', '*'], '_', strtolower($column)); // return cleaned column return([$quote_symbol . $column . $quote_symbol, $placeholder]); }
php
public static function columnToPlaceholder( string $quote_symbol, string $column, $allow_wildcard = false ) :array { // apply the secure regex for the column name $column = preg_replace(($allow_wildcard ? '/[^a-zA-Z0-9_\.\*]/' : '/[^a-zA-Z0-9_\.]/'), '', $column); // cleanup the placeholder $placeholder = str_replace(['.', '*'], '_', strtolower($column)); // return cleaned column return([$quote_symbol . $column . $quote_symbol, $placeholder]); }
[ "public", "static", "function", "columnToPlaceholder", "(", "string", "$", "quote_symbol", ",", "string", "$", "column", ",", "$", "allow_wildcard", "=", "false", ")", ":", "array", "{", "// apply the secure regex for the column name", "$", "column", "=", "preg_repl...
get a column placeholder to build queries with
[ "get", "a", "column", "placeholder", "to", "build", "queries", "with" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Convert.php#L98-L109
train
ventoviro/windwalker-core
src/Core/Cache/CacheManager.php
CacheManager.getCache
public function getCache( string $name = 'windwalker', string $storage = 'array', string $serializer = 'php', array $options = [] ): CacheInterface { $config = $this->config; $debug = $config->get('system.debug', false); $enabled = $config->get('cache.enabled', false); $forceEnabled = $options['force_enabled'] ?? false; if (!$forceEnabled && ($debug || !$enabled) && !$this->ignoreGlobal) { $storage = 'null'; $serializer = 'raw'; } return $this->create($name, $storage, $serializer, $options); }
php
public function getCache( string $name = 'windwalker', string $storage = 'array', string $serializer = 'php', array $options = [] ): CacheInterface { $config = $this->config; $debug = $config->get('system.debug', false); $enabled = $config->get('cache.enabled', false); $forceEnabled = $options['force_enabled'] ?? false; if (!$forceEnabled && ($debug || !$enabled) && !$this->ignoreGlobal) { $storage = 'null'; $serializer = 'raw'; } return $this->create($name, $storage, $serializer, $options); }
[ "public", "function", "getCache", "(", "string", "$", "name", "=", "'windwalker'", ",", "string", "$", "storage", "=", "'array'", ",", "string", "$", "serializer", "=", "'php'", ",", "array", "$", "options", "=", "[", "]", ")", ":", "CacheInterface", "{"...
Create cache object. @param string $name @param string $storage @param string $serializer @param array $options @return CacheInterface @throws \ReflectionException @throws \Windwalker\DI\Exception\DependencyResolutionException @deprecated Use getCacheInstance() instead.
[ "Create", "cache", "object", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Cache/CacheManager.php#L132-L151
train
ventoviro/windwalker-core
src/Core/Cache/CacheManager.php
CacheManager.ignoreGlobal
public function ignoreGlobal(?bool $bool = null): bool { if ($bool === null) { return $this->ignoreGlobal; } $this->ignoreGlobal = (bool) $bool; return $bool; }
php
public function ignoreGlobal(?bool $bool = null): bool { if ($bool === null) { return $this->ignoreGlobal; } $this->ignoreGlobal = (bool) $bool; return $bool; }
[ "public", "function", "ignoreGlobal", "(", "?", "bool", "$", "bool", "=", "null", ")", ":", "bool", "{", "if", "(", "$", "bool", "===", "null", ")", "{", "return", "$", "this", "->", "ignoreGlobal", ";", "}", "$", "this", "->", "ignoreGlobal", "=", ...
Method to get property IgnoreGlobal @param boolean $bool @return boolean
[ "Method", "to", "get", "property", "IgnoreGlobal" ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Cache/CacheManager.php#L333-L342
train
polyfony-inc/polyfony
Private/Polyfony/Query/Conditions.php
Conditions.where
public function where(array $conditions) { // for each provided strict condition foreach($conditions as $column => $value) { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$column); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} = :{$placeholder} )"; // save the value $this->Values[":{$placeholder}"] = $value; } // return self to the next method return $this; }
php
public function where(array $conditions) { // for each provided strict condition foreach($conditions as $column => $value) { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$column); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} = :{$placeholder} )"; // save the value $this->Values[":{$placeholder}"] = $value; } // return self to the next method return $this; }
[ "public", "function", "where", "(", "array", "$", "conditions", ")", "{", "// for each provided strict condition", "foreach", "(", "$", "conditions", "as", "$", "column", "=>", "$", "value", ")", "{", "// secure the column name", "list", "(", "$", "column", ",",...
add a condition
[ "add", "a", "condition" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Conditions.php#L9-L24
train
polyfony-inc/polyfony
Private/Polyfony/Query/Conditions.php
Conditions.whereEmpty
public function whereEmpty($conditions) { // if provided conditions are an array if(is_array($conditions)) { // for each condition foreach($conditions as $column) { // add the condition $this->whereEmpty($column); } } else { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$conditions); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} == :empty_{$placeholder} OR {$column} IS NULL )"; // add the empty value $this->Values[":empty_{$placeholder}"] = ''; } // return self to the next method return $this; }
php
public function whereEmpty($conditions) { // if provided conditions are an array if(is_array($conditions)) { // for each condition foreach($conditions as $column) { // add the condition $this->whereEmpty($column); } } else { // secure the column name list( $column, $placeholder ) = Convert::columnToPlaceholder($this->Quote ,$conditions); // save the condition $this->Conditions[] = "{$this->Operator} ( {$column} == :empty_{$placeholder} OR {$column} IS NULL )"; // add the empty value $this->Values[":empty_{$placeholder}"] = ''; } // return self to the next method return $this; }
[ "public", "function", "whereEmpty", "(", "$", "conditions", ")", "{", "// if provided conditions are an array", "if", "(", "is_array", "(", "$", "conditions", ")", ")", "{", "// for each condition", "foreach", "(", "$", "conditions", "as", "$", "column", ")", "{...
we are still supporting NON-array parameter, this will be removed at some point in time
[ "we", "are", "still", "supporting", "NON", "-", "array", "parameter", "this", "will", "be", "removed", "at", "some", "point", "in", "time" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Query/Conditions.php#L185-L207
train
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.disconnect
public static function disconnect() :void { // first authenticate self::enforce(); // then close the session self::$_account->closeSession(); // and redirect to the exit route or fallback to the login route Response::setRedirect(Config::get('router', 'exit_route') ?: Config::get('router', 'login_route')); // render the response Response::render(); }
php
public static function disconnect() :void { // first authenticate self::enforce(); // then close the session self::$_account->closeSession(); // and redirect to the exit route or fallback to the login route Response::setRedirect(Config::get('router', 'exit_route') ?: Config::get('router', 'login_route')); // render the response Response::render(); }
[ "public", "static", "function", "disconnect", "(", ")", ":", "void", "{", "// first authenticate", "self", "::", "enforce", "(", ")", ";", "// then close the session", "self", "::", "$", "_account", "->", "closeSession", "(", ")", ";", "// and redirect to the exit...
authenticate then close the session
[ "authenticate", "then", "close", "the", "session" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L49-L63
train
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.authenticate
protected static function authenticate() :void { // if we did not authenticate before if(!self::$_account) { // search for an enabled account with that session key and a non expired session $account = \Models\Accounts::getFirstEnabledWithNonExpiredSession( // the session key Cook::get(Config::get('security', 'cookie')) ); // if the cookie session key doesn't match any existing account session, we deny access $account ?: self::refuse( 'Your session is no longer valid', 403, true); // if the stored key and dynamically generated mismatch, we deny access $account->hasMatchingDynamicKey() ?: self::refuse( 'Your signature has changed since your last visit, please log-in again', 403, true); // if account has expired, we deny access !$account->hasItsValidityExpired() ?: self::refuse( "Your account has expired, it was valid until {$account->get('account_expiration_date')}", 403, true); // update our credentials self::$_account = $account; // set access as granted self::$_granted = true; } }
php
protected static function authenticate() :void { // if we did not authenticate before if(!self::$_account) { // search for an enabled account with that session key and a non expired session $account = \Models\Accounts::getFirstEnabledWithNonExpiredSession( // the session key Cook::get(Config::get('security', 'cookie')) ); // if the cookie session key doesn't match any existing account session, we deny access $account ?: self::refuse( 'Your session is no longer valid', 403, true); // if the stored key and dynamically generated mismatch, we deny access $account->hasMatchingDynamicKey() ?: self::refuse( 'Your signature has changed since your last visit, please log-in again', 403, true); // if account has expired, we deny access !$account->hasItsValidityExpired() ?: self::refuse( "Your account has expired, it was valid until {$account->get('account_expiration_date')}", 403, true); // update our credentials self::$_account = $account; // set access as granted self::$_granted = true; } }
[ "protected", "static", "function", "authenticate", "(", ")", ":", "void", "{", "// if we did not authenticate before", "if", "(", "!", "self", "::", "$", "_account", ")", "{", "// search for an enabled account with that session key and a non expired session", "$", "account"...
internal authentication method that will grant access based on an existing session
[ "internal", "authentication", "method", "that", "will", "grant", "access", "based", "on", "an", "existing", "session" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L66-L94
train
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.login
protected static function login() :void { // look for users with this login $account = \Models\Accounts::getFirstEnabledWithLogin( Request::post( Config::get('security', 'login') ) ); // if the account does not exist/is not found if(!$account) { // we deny access self::refuse('Account does not exist or is disabled'); } // if the account has been forced by that ip recently if($account->hasFailedLoginAttemptsRecentFrom(self::getSafeRemoteAddress())) { // extend the lock on the account $account->extendLoginBan(); // refuse access self::refuse('Please wait '.Config::get('security', 'waiting_duration').' seconds before trying again'); } // if the account has expired if($account->hasItsValidityExpired()) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse("Your account has expired, it was valid until {$account->get('account_expiration_date')}"); } // if the posted password doesn't match the account's password if(!$account->hasThisPassword(Request::post(Config::get('security', 'password')))) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse('Wrong password'); } // if we failed to open a session if(!$account->tryOpeningSession()) { // we report that something is wrong self::refuse('Your session failed to open, make sure your browser accepts cookies', 500); } // then session has been opened else { // log the loggin action Logger::info("Account {$account->get('login')} has logged in"); // put the user inside of us self::$_account = $account; // set the most basic authentication block as being true/passed self::$_granted = true; // if we have an url in the session, redirect to it (and remove it) !Session::has('previously_requested_url') ?: self::redirectToThePreviouslyRequestedUrl(); } }
php
protected static function login() :void { // look for users with this login $account = \Models\Accounts::getFirstEnabledWithLogin( Request::post( Config::get('security', 'login') ) ); // if the account does not exist/is not found if(!$account) { // we deny access self::refuse('Account does not exist or is disabled'); } // if the account has been forced by that ip recently if($account->hasFailedLoginAttemptsRecentFrom(self::getSafeRemoteAddress())) { // extend the lock on the account $account->extendLoginBan(); // refuse access self::refuse('Please wait '.Config::get('security', 'waiting_duration').' seconds before trying again'); } // if the account has expired if($account->hasItsValidityExpired()) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse("Your account has expired, it was valid until {$account->get('account_expiration_date')}"); } // if the posted password doesn't match the account's password if(!$account->hasThisPassword(Request::post(Config::get('security', 'password')))) { // register that failure $account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent()); // refuse access self::refuse('Wrong password'); } // if we failed to open a session if(!$account->tryOpeningSession()) { // we report that something is wrong self::refuse('Your session failed to open, make sure your browser accepts cookies', 500); } // then session has been opened else { // log the loggin action Logger::info("Account {$account->get('login')} has logged in"); // put the user inside of us self::$_account = $account; // set the most basic authentication block as being true/passed self::$_granted = true; // if we have an url in the session, redirect to it (and remove it) !Session::has('previously_requested_url') ?: self::redirectToThePreviouslyRequestedUrl(); } }
[ "protected", "static", "function", "login", "(", ")", ":", "void", "{", "// look for users with this login", "$", "account", "=", "\\", "Models", "\\", "Accounts", "::", "getFirstEnabledWithLogin", "(", "Request", "::", "post", "(", "Config", "::", "get", "(", ...
internal login method that will open a session
[ "internal", "login", "method", "that", "will", "open", "a", "session" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L97-L146
train
polyfony-inc/polyfony
Private/Polyfony/Security.php
Security.getSignature
public static function getSignature($mixed) :string { // compute a hash with (the provided string + salt + user agent + remote ip) return(hash(Config::get('security','algo'), self::getSafeUserAgent() . self::getSafeRemoteAddress() . Config::get('security','salt') . is_string($mixed) ? $mixed : json_encode($mixed) )); }
php
public static function getSignature($mixed) :string { // compute a hash with (the provided string + salt + user agent + remote ip) return(hash(Config::get('security','algo'), self::getSafeUserAgent() . self::getSafeRemoteAddress() . Config::get('security','salt') . is_string($mixed) ? $mixed : json_encode($mixed) )); }
[ "public", "static", "function", "getSignature", "(", "$", "mixed", ")", ":", "string", "{", "// compute a hash with (the provided string + salt + user agent + remote ip)", "return", "(", "hash", "(", "Config", "::", "get", "(", "'security'", ",", "'algo'", ")", ",", ...
internal method for generating unique signatures
[ "internal", "method", "for", "generating", "unique", "signatures" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Security.php#L172-L178
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.setStructure
public function setStructure(array $layouts) { $computedLayouts = []; foreach ($layouts as $l) { $loop = isset($l['loop']) ? (int)$l['loop'] : 1; unset($l['loop']); for ($i=0; $i<$loop; $i++) { $computedLayouts[] = $l; } } $this->structure = $computedLayouts; return $this; }
php
public function setStructure(array $layouts) { $computedLayouts = []; foreach ($layouts as $l) { $loop = isset($l['loop']) ? (int)$l['loop'] : 1; unset($l['loop']); for ($i=0; $i<$loop; $i++) { $computedLayouts[] = $l; } } $this->structure = $computedLayouts; return $this; }
[ "public", "function", "setStructure", "(", "array", "$", "layouts", ")", "{", "$", "computedLayouts", "=", "[", "]", ";", "foreach", "(", "$", "layouts", "as", "$", "l", ")", "{", "$", "loop", "=", "isset", "(", "$", "l", "[", "'loop'", "]", ")", ...
Prepare the layouts configuration in a simpler, ready, data structure. This function goes through the layout options to expand loops into extra layout data... @param array $layouts The original layout data, typically from configuration. @return array Computed layouts, ready for looping
[ "Prepare", "the", "layouts", "configuration", "in", "a", "simpler", "ready", "data", "structure", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L54-L68
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.rowIndex
public function rowIndex($position = null) { if ($position === null) { $position = $this->position(); } $i = 0; $p = 0; foreach ($this->structure as $row_ident => $row) { $numCells = count($row['columns']); $p += $numCells; if ($p > $position) { return $i; } $i++; } return null; }
php
public function rowIndex($position = null) { if ($position === null) { $position = $this->position(); } $i = 0; $p = 0; foreach ($this->structure as $row_ident => $row) { $numCells = count($row['columns']); $p += $numCells; if ($p > $position) { return $i; } $i++; } return null; }
[ "public", "function", "rowIndex", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "$", "i", "=", "0", ";", "$", "p", "=",...
Get the row index at a certain position @param integer $position Optional. Forced position. @return integer|null
[ "Get", "the", "row", "index", "at", "a", "certain", "position" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L95-L112
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.rowData
public function rowData($position = null) { if ($position === null) { $position = $this->position(); } $rowIndex = $this->rowIndex($position); if (isset($this->structure[$rowIndex])) { return $this->structure[$rowIndex]; } else { return null; } }
php
public function rowData($position = null) { if ($position === null) { $position = $this->position(); } $rowIndex = $this->rowIndex($position); if (isset($this->structure[$rowIndex])) { return $this->structure[$rowIndex]; } else { return null; } }
[ "public", "function", "rowData", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "$", "rowIndex", "=", "$", "this", "->", "...
Get the row information If no `$position` is specified, then the current position will be used. @param integer $position Optional. Forced position. @return array|null
[ "Get", "the", "row", "information" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L122-L134
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.rowNumCells
public function rowNumCells($position = null) { if ($position === null) { $position = $this->position(); } // Get the data ta position $row = $this->rowData($position); $numCells = isset($row['columns']) ? count($row['columns']) : null; return $numCells; }
php
public function rowNumCells($position = null) { if ($position === null) { $position = $this->position(); } // Get the data ta position $row = $this->rowData($position); $numCells = isset($row['columns']) ? count($row['columns']) : null; return $numCells; }
[ "public", "function", "rowNumCells", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "// Get the data ta position", "$", "row", "...
Get the number of cells at current position This can be different than the number of columns, in case @param integer $position Optional. Forced position. @return integer
[ "Get", "the", "number", "of", "cells", "at", "current", "position" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L164-L174
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.cellRowIndex
public function cellRowIndex($position = null) { if ($position === null) { $position = $this->position(); } $first = $this->rowFirstCellIndex($position); return ($position - $first); }
php
public function cellRowIndex($position = null) { if ($position === null) { $position = $this->position(); } $first = $this->rowFirstCellIndex($position); return ($position - $first); }
[ "public", "function", "cellRowIndex", "(", "$", "position", "=", "null", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "position", "=", "$", "this", "->", "position", "(", ")", ";", "}", "$", "first", "=", "$", "this", "->", ...
Get the cell index in the current row @param integer $position Optional. Forced position. @return integer
[ "Get", "the", "cell", "index", "in", "the", "current", "row" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L217-L225
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Layout/LayoutTrait.php
LayoutTrait.numCellsTotal
public function numCellsTotal() { $numCells = 0; foreach ($this->structure as $row) { $rowCols = isset($row['columns']) ? count($row['columns']) : 0; $numCells += $rowCols; } return $numCells; }
php
public function numCellsTotal() { $numCells = 0; foreach ($this->structure as $row) { $rowCols = isset($row['columns']) ? count($row['columns']) : 0; $numCells += $rowCols; } return $numCells; }
[ "public", "function", "numCellsTotal", "(", ")", "{", "$", "numCells", "=", "0", ";", "foreach", "(", "$", "this", "->", "structure", "as", "$", "row", ")", "{", "$", "rowCols", "=", "isset", "(", "$", "row", "[", "'columns'", "]", ")", "?", "count...
Get the total number of cells, in all rows @return integer
[ "Get", "the", "total", "number", "of", "cells", "in", "all", "rows" ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Layout/LayoutTrait.php#L232-L240
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/dissemination/parameter/UriPart.php
UriPart.transform
public function transform(string $value, string ...$parts): string { $value = parse_url($value); $toUnset = ['scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment']; $toUnset = array_intersect(array_diff($toUnset, $parts), array_keys($value)); foreach ($toUnset as $i) { unset($value[$i]); } $scheme = isset($value['scheme']) ? $value['scheme'] . '://' : ''; $host = isset($value['host']) ? $value['host'] : ''; $port = isset($value['port']) ? ':' . $value['port'] : ''; $user = isset($value['user']) ? $value['user'] : ''; $pass = isset($value['pass']) ? ':' . $value['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($value['path']) ? $value['path'] : ''; $query = isset($value['query']) ? '?' . $value['query'] : ''; $fragment = isset($value['fragment']) ? '#' . $value['fragment'] : ''; return $scheme . $user . $pass . $host . $port . $path . $query . $fragment; }
php
public function transform(string $value, string ...$parts): string { $value = parse_url($value); $toUnset = ['scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment']; $toUnset = array_intersect(array_diff($toUnset, $parts), array_keys($value)); foreach ($toUnset as $i) { unset($value[$i]); } $scheme = isset($value['scheme']) ? $value['scheme'] . '://' : ''; $host = isset($value['host']) ? $value['host'] : ''; $port = isset($value['port']) ? ':' . $value['port'] : ''; $user = isset($value['user']) ? $value['user'] : ''; $pass = isset($value['pass']) ? ':' . $value['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($value['path']) ? $value['path'] : ''; $query = isset($value['query']) ? '?' . $value['query'] : ''; $fragment = isset($value['fragment']) ? '#' . $value['fragment'] : ''; return $scheme . $user . $pass . $host . $port . $path . $query . $fragment; }
[ "public", "function", "transform", "(", "string", "$", "value", ",", "string", "...", "$", "parts", ")", ":", "string", "{", "$", "value", "=", "parse_url", "(", "$", "value", ")", ";", "$", "toUnset", "=", "[", "'scheme'", ",", "'host'", ",", "'port...
Extracts given URL parts. @param string $value URL to be transformed @param ... $parts parts to be extracted. One of: scheme (e.g. "https", "ftp", etc.), host, port, user, pass, path, query, fragment (part of the URL following #) @return string
[ "Extracts", "given", "URL", "parts", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/dissemination/parameter/UriPart.php#L55-L75
train
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.data_uri
public static function data_uri(string $path) { ref\cast::string($path, true); ref\file::path($path, true); if ((false !== $path) && @\is_file($path)) { $content = \base64_encode(@\file_get_contents($path)); $finfo = mime::finfo($path); return "data:{$finfo['mime']};base64,{$content}"; } return false; }
php
public static function data_uri(string $path) { ref\cast::string($path, true); ref\file::path($path, true); if ((false !== $path) && @\is_file($path)) { $content = \base64_encode(@\file_get_contents($path)); $finfo = mime::finfo($path); return "data:{$finfo['mime']};base64,{$content}"; } return false; }
[ "public", "static", "function", "data_uri", "(", "string", "$", "path", ")", "{", "ref", "\\", "cast", "::", "string", "(", "$", "path", ",", "true", ")", ";", "ref", "\\", "file", "::", "path", "(", "$", "path", ",", "true", ")", ";", "if", "(",...
Get Data-URI From File @param string $path Path. @return string|bool Data-URI or false.
[ "Get", "Data", "-", "URI", "From", "File" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L170-L182
train
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.empty_dir
public static function empty_dir(string $path) { if (! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($file = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' !== $file) && ('..' !== $file)) { return false; } } \closedir($handle); return true; } return false; }
php
public static function empty_dir(string $path) { if (! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($file = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' !== $file) && ('..' !== $file)) { return false; } } \closedir($handle); return true; } return false; }
[ "public", "static", "function", "empty_dir", "(", "string", "$", "path", ")", "{", "if", "(", "!", "@", "\\", "is_readable", "(", "$", "path", ")", "||", "!", "@", "\\", "is_dir", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "// ...
Is Directory Empty? @param string $path Path. @return bool True/false.
[ "Is", "Directory", "Empty?" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L205-L223
train
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.mkdir
public static function mkdir(string $path, $chmod=null) { // Figure out a good default CHMOD. if (! $chmod || ! \is_numeric($chmod)) { $chmod = (\fileperms(__DIR__) & 0777 | 0755); } // Sanitize the path. ref\file::path($path, false); if (! $path || (false !== \strpos($path, '://'))) { return false; } // We only need to proceed if the path doesn't exist. if (! @\is_dir($path)) { ref\file::untrailingslash($path); // Figure out where we need to begin. $base = \dirname($path); while ($base && ('.' !== $base) && ! @\is_dir($base)) { $base = \dirname($base); } // Make it. if (! @\mkdir($path, 0777, true)) { return false; } // Fix permissions. if ($path !== $base) { // If we fell deep enough that base became relative, // let's move it back. if (! $base || ('.' === $base)) { $base = __DIR__; } // Base should be inside path. If not, something weird // has happened. if (0 !== mb::strpos($path, $base)) { return true; } $path = mb::substr($path, mb::strlen($base), null); ref\file::unleadingslash($path); $parts = \explode('/', $path); $path = $base; // Loop through each subdirectory to set the appropriate // permissions. foreach ($parts as $v) { $path .= ('/' === \substr($path, -1)) ? $v : "/$v"; if (! @\chmod($path, $chmod)) { return true; } } } else { @\chmod($path, $chmod); } } return true; }
php
public static function mkdir(string $path, $chmod=null) { // Figure out a good default CHMOD. if (! $chmod || ! \is_numeric($chmod)) { $chmod = (\fileperms(__DIR__) & 0777 | 0755); } // Sanitize the path. ref\file::path($path, false); if (! $path || (false !== \strpos($path, '://'))) { return false; } // We only need to proceed if the path doesn't exist. if (! @\is_dir($path)) { ref\file::untrailingslash($path); // Figure out where we need to begin. $base = \dirname($path); while ($base && ('.' !== $base) && ! @\is_dir($base)) { $base = \dirname($base); } // Make it. if (! @\mkdir($path, 0777, true)) { return false; } // Fix permissions. if ($path !== $base) { // If we fell deep enough that base became relative, // let's move it back. if (! $base || ('.' === $base)) { $base = __DIR__; } // Base should be inside path. If not, something weird // has happened. if (0 !== mb::strpos($path, $base)) { return true; } $path = mb::substr($path, mb::strlen($base), null); ref\file::unleadingslash($path); $parts = \explode('/', $path); $path = $base; // Loop through each subdirectory to set the appropriate // permissions. foreach ($parts as $v) { $path .= ('/' === \substr($path, -1)) ? $v : "/$v"; if (! @\chmod($path, $chmod)) { return true; } } } else { @\chmod($path, $chmod); } } return true; }
[ "public", "static", "function", "mkdir", "(", "string", "$", "path", ",", "$", "chmod", "=", "null", ")", "{", "// Figure out a good default CHMOD.", "if", "(", "!", "$", "chmod", "||", "!", "\\", "is_numeric", "(", "$", "chmod", ")", ")", "{", "$", "c...
Resursively Make Directory PHP's mkdir function can be recursive, but the permissions are only set correctly on the innermost folder created. @param string $path Path. @param int $chmod CHMOD. @return bool True/false.
[ "Resursively", "Make", "Directory" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L352-L413
train
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.readfile_chunked
public static function readfile_chunked(string $file, bool $retbytes=true) { if (! $file || ! @\is_file($file)) { return false; } $buffer = ''; $cnt = 0; $chunk_size = 1024 * 1024; if (false === ($handle = @\fopen($file, 'rb'))) { return false; } while (! @\feof($handle)) { $buffer = @\fread($handle, $chunk_size); echo $buffer; \ob_flush(); \flush(); if ($retbytes) { $cnt += \strlen($buffer); } } $status = @\fclose($handle); // Return number of bytes delivered like readfile() does. if ($retbytes && $status) { return $cnt; } return $status; }
php
public static function readfile_chunked(string $file, bool $retbytes=true) { if (! $file || ! @\is_file($file)) { return false; } $buffer = ''; $cnt = 0; $chunk_size = 1024 * 1024; if (false === ($handle = @\fopen($file, 'rb'))) { return false; } while (! @\feof($handle)) { $buffer = @\fread($handle, $chunk_size); echo $buffer; \ob_flush(); \flush(); if ($retbytes) { $cnt += \strlen($buffer); } } $status = @\fclose($handle); // Return number of bytes delivered like readfile() does. if ($retbytes && $status) { return $cnt; } return $status; }
[ "public", "static", "function", "readfile_chunked", "(", "string", "$", "file", ",", "bool", "$", "retbytes", "=", "true", ")", "{", "if", "(", "!", "$", "file", "||", "!", "@", "\\", "is_file", "(", "$", "file", ")", ")", "{", "return", "false", "...
Read File in Chunks This greatly reduces overhead if serving files through a PHP gateway script. @param string $file Path. @param bool $retbytes Return bytes served like `readfile()`. @return mixed Bytes served or status.
[ "Read", "File", "in", "Chunks" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L437-L468
train
Blobfolio/blob-common
lib/blobfolio/common/file.php
file.rmdir
public static function rmdir(string $path) { ref\file::path($path, true); if (! $path || ! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($entry = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' === $entry) || ('..' === $entry)) { continue; } $file = "{$path}{$entry}"; // Delete files. if (@\is_file($file)) { @\unlink($file); } // Recursively delete directories. else { static::rmdir($file); } } \closedir($handle); } if (static::empty_dir($path)) { @\rmdir($path); } return ! @\file_exists($path); }
php
public static function rmdir(string $path) { ref\file::path($path, true); if (! $path || ! @\is_readable($path) || ! @\is_dir($path)) { return false; } // Scan all files in dir. if ($handle = @\opendir($path)) { while (false !== ($entry = @\readdir($handle))) { // Anything but a dot === not empty. if (('.' === $entry) || ('..' === $entry)) { continue; } $file = "{$path}{$entry}"; // Delete files. if (@\is_file($file)) { @\unlink($file); } // Recursively delete directories. else { static::rmdir($file); } } \closedir($handle); } if (static::empty_dir($path)) { @\rmdir($path); } return ! @\file_exists($path); }
[ "public", "static", "function", "rmdir", "(", "string", "$", "path", ")", "{", "ref", "\\", "file", "::", "path", "(", "$", "path", ",", "true", ")", ";", "if", "(", "!", "$", "path", "||", "!", "@", "\\", "is_readable", "(", "$", "path", ")", ...
Recursively Remove A Directory @param string $path Path. @return bool True/false.
[ "Recursively", "Remove", "A", "Directory" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/file.php#L501-L534
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.setGroups
public function setGroups(array $groups) { $this->groups = []; foreach ($groups as $groupIdent => $group) { $this->addGroup($groupIdent, $group); } return $this; }
php
public function setGroups(array $groups) { $this->groups = []; foreach ($groups as $groupIdent => $group) { $this->addGroup($groupIdent, $group); } return $this; }
[ "public", "function", "setGroups", "(", "array", "$", "groups", ")", "{", "$", "this", "->", "groups", "=", "[", "]", ";", "foreach", "(", "$", "groups", "as", "$", "groupIdent", "=>", "$", "group", ")", "{", "$", "this", "->", "addGroup", "(", "$"...
Set the object's form groups. @param array $groups A collection of group structures. @return FormInterface Chainable
[ "Set", "the", "object", "s", "form", "groups", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L227-L236
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.addGroup
public function addGroup($groupIdent, $group) { if ($group === false || $group === null) { return $this; } $group = $this->parseFormGroup($groupIdent, $group); if (isset($group['ident'])) { $groupIdent = $group['ident']; } $this->groups[$groupIdent] = $group; return $this; }
php
public function addGroup($groupIdent, $group) { if ($group === false || $group === null) { return $this; } $group = $this->parseFormGroup($groupIdent, $group); if (isset($group['ident'])) { $groupIdent = $group['ident']; } $this->groups[$groupIdent] = $group; return $this; }
[ "public", "function", "addGroup", "(", "$", "groupIdent", ",", "$", "group", ")", "{", "if", "(", "$", "group", "===", "false", "||", "$", "group", "===", "null", ")", "{", "return", "$", "this", ";", "}", "$", "group", "=", "$", "this", "->", "p...
Add a form group. @param string $groupIdent The group identifier. @param array|FormGroupInterface $group The group object or structure. @throws InvalidArgumentException If the identifier is not a string or the group is invalid. @return FormInterface Chainable
[ "Add", "a", "form", "group", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L284-L299
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.groups
public function groups(callable $groupCallback = null) { $groups = $this->groups; uasort($groups, [ $this, 'sortItemsByPriority' ]); $groupCallback = (isset($groupCallback) ? $groupCallback : $this->groupCallback); $groups = $this->finalizeFormGroups($groups); $i = 1; foreach ($groups as $group) { if ($groupCallback) { $groupCallback($group); } $GLOBALS['widget_template'] = $group->template(); if (!$this->selectedFormGroup() && $this->isTabbable()) { $group->setIsHidden(false); if ($i > 1) { $group->setIsHidden(true); } } $i++; yield $group; $GLOBALS['widget_template'] = ''; } }
php
public function groups(callable $groupCallback = null) { $groups = $this->groups; uasort($groups, [ $this, 'sortItemsByPriority' ]); $groupCallback = (isset($groupCallback) ? $groupCallback : $this->groupCallback); $groups = $this->finalizeFormGroups($groups); $i = 1; foreach ($groups as $group) { if ($groupCallback) { $groupCallback($group); } $GLOBALS['widget_template'] = $group->template(); if (!$this->selectedFormGroup() && $this->isTabbable()) { $group->setIsHidden(false); if ($i > 1) { $group->setIsHidden(true); } } $i++; yield $group; $GLOBALS['widget_template'] = ''; } }
[ "public", "function", "groups", "(", "callable", "$", "groupCallback", "=", "null", ")", "{", "$", "groups", "=", "$", "this", "->", "groups", ";", "uasort", "(", "$", "groups", ",", "[", "$", "this", ",", "'sortItemsByPriority'", "]", ")", ";", "$", ...
Retrieve the form groups. @param callable $groupCallback Optional callback applied to each form group. @return FormGroupInterface[]|Generator
[ "Retrieve", "the", "form", "groups", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L404-L433
train
locomotivemtl/charcoal-ui
src/Charcoal/Ui/Form/FormTrait.php
FormTrait.setGroupDisplayMode
public function setGroupDisplayMode($mode) { if (!is_string($mode)) { throw new InvalidArgumentException( 'Display mode must be a string' ); } if ($mode === 'tabs') { $mode = 'tab'; } $this->groupDisplayMode = $mode; return $this; }
php
public function setGroupDisplayMode($mode) { if (!is_string($mode)) { throw new InvalidArgumentException( 'Display mode must be a string' ); } if ($mode === 'tabs') { $mode = 'tab'; } $this->groupDisplayMode = $mode; return $this; }
[ "public", "function", "setGroupDisplayMode", "(", "$", "mode", ")", "{", "if", "(", "!", "is_string", "(", "$", "mode", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Display mode must be a string'", ")", ";", "}", "if", "(", "$", "mode", ...
Set the widget's content group display mode. Currently only supports "tab". @param string $mode Group display mode. @throws InvalidArgumentException If the display mode is not a string. @return ObjectFormWidget Chainable.
[ "Set", "the", "widget", "s", "content", "group", "display", "mode", "." ]
0070f35d89ea24ae93720734d261c02a10e218b6
https://github.com/locomotivemtl/charcoal-ui/blob/0070f35d89ea24ae93720734d261c02a10e218b6/src/Charcoal/Ui/Form/FormTrait.php#L558-L573
train
diff-sniffer/core
src/Runner.php
Runner.run
public function run(Changeset $changeset) { $diff = new Diff($changeset->getDiff()); if (!count($diff)) { return 0; } $reporter = new Reporter($diff, $this->config); $runner = new BaseRunner(); $runner->config = $this->config; $runner->reporter = $reporter; $runner->init(); $it = new Iterator($diff, $changeset, $runner->ruleset, $this->config); /** @var File $file */ foreach ($it as $file) { $runner->processFile($file); } $reporter->printReports(); return (int) ($reporter->totalErrors || $reporter->totalWarnings); }
php
public function run(Changeset $changeset) { $diff = new Diff($changeset->getDiff()); if (!count($diff)) { return 0; } $reporter = new Reporter($diff, $this->config); $runner = new BaseRunner(); $runner->config = $this->config; $runner->reporter = $reporter; $runner->init(); $it = new Iterator($diff, $changeset, $runner->ruleset, $this->config); /** @var File $file */ foreach ($it as $file) { $runner->processFile($file); } $reporter->printReports(); return (int) ($reporter->totalErrors || $reporter->totalWarnings); }
[ "public", "function", "run", "(", "Changeset", "$", "changeset", ")", "{", "$", "diff", "=", "new", "Diff", "(", "$", "changeset", "->", "getDiff", "(", ")", ")", ";", "if", "(", "!", "count", "(", "$", "diff", ")", ")", "{", "return", "0", ";", ...
Runs CodeSniffer against specified changeset @param Changeset $changeset Changeset instance @return int @throws DeepExitException @throws Exception
[ "Runs", "CodeSniffer", "against", "specified", "changeset" ]
583369a5f5c91496862f6bdf60b69565da4bc05d
https://github.com/diff-sniffer/core/blob/583369a5f5c91496862f6bdf60b69565da4bc05d/src/Runner.php#L34-L59
train
Blobfolio/blob-common
wp/lib/blobcommon.php
blobcommon.get_release_info
protected static function get_release_info(string $key, $template) { // PHP 5.6.0 compatibility has been dropped, so nobody can // update until they update PHP. if (\version_compare(\PHP_VERSION, '7.2.0') < 0) { return false; } // Already pulled it? if (isset(static::$_release[$key])) { return static::$_release[$key]; } // WordPress hides relevant functionality in this file. require_once \ABSPATH . 'wp-admin/includes/plugin.php'; $uri = \get_file_data( \BLOBCOMMON_INDEX, array('json'=>$key), 'plugin' ); $uri = $uri['json']; r_sanitize::url($uri); if (! $uri) { static::$_release[$key] = false; return static::$_release[$key]; } // Cache this to the transient table for a little bit. $transient_key = 'blob-common_remote_' . \md5($uri . $key); if (false !== (static::$_release[$key] = \get_transient($transient_key))) { return static::$_release[$key]; } // Read the file. $response = \wp_remote_get($uri); if (200 !== \wp_remote_retrieve_response_code($response)) { static::$_release[$key] = false; return static::$_release[$key]; } // Decode the JSON. static::$_release[$key] = data::json_decode_array( \wp_remote_retrieve_body($response), $template ); // Add the URI we discovered, just in case. static::$_release[$key]['json_uri'] = $uri; // Cache it for a while. \set_transient($transient_key, static::$_release[$key], \HOUR_IN_SECONDS); // And we're done. return static::$_release[$key]; }
php
protected static function get_release_info(string $key, $template) { // PHP 5.6.0 compatibility has been dropped, so nobody can // update until they update PHP. if (\version_compare(\PHP_VERSION, '7.2.0') < 0) { return false; } // Already pulled it? if (isset(static::$_release[$key])) { return static::$_release[$key]; } // WordPress hides relevant functionality in this file. require_once \ABSPATH . 'wp-admin/includes/plugin.php'; $uri = \get_file_data( \BLOBCOMMON_INDEX, array('json'=>$key), 'plugin' ); $uri = $uri['json']; r_sanitize::url($uri); if (! $uri) { static::$_release[$key] = false; return static::$_release[$key]; } // Cache this to the transient table for a little bit. $transient_key = 'blob-common_remote_' . \md5($uri . $key); if (false !== (static::$_release[$key] = \get_transient($transient_key))) { return static::$_release[$key]; } // Read the file. $response = \wp_remote_get($uri); if (200 !== \wp_remote_retrieve_response_code($response)) { static::$_release[$key] = false; return static::$_release[$key]; } // Decode the JSON. static::$_release[$key] = data::json_decode_array( \wp_remote_retrieve_body($response), $template ); // Add the URI we discovered, just in case. static::$_release[$key]['json_uri'] = $uri; // Cache it for a while. \set_transient($transient_key, static::$_release[$key], \HOUR_IN_SECONDS); // And we're done. return static::$_release[$key]; }
[ "protected", "static", "function", "get_release_info", "(", "string", "$", "key", ",", "$", "template", ")", "{", "// PHP 5.6.0 compatibility has been dropped, so nobody can", "// update until they update PHP.", "if", "(", "\\", "version_compare", "(", "\\", "PHP_VERSION", ...
Parse Release File Both the plugin and library have JSON files containing release information. These files tell WordPress whether or not an update is available, and where to find it. @param string $key Header key containing JSON URI. @param array $template Data template. @return array Info.
[ "Parse", "Release", "File" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/wp/lib/blobcommon.php#L188-L242
train
Blobfolio/blob-common
wp/lib/blobcommon.php
blobcommon.check_plugin
protected static function check_plugin($key=null) { if (\is_null(static::$_plugin)) { // Pull the remote info and store it for later. if (false === ($remote = static::get_release_info('Info URI', static::PLUGIN_TEMPLATE))) { static::$_plugin = false; return static::$_plugin; } // Use the main plugin headers as the basis. static::$_plugin = \get_plugin_data(\BLOBCOMMON_INDEX, false, false); // And add in what we pulled remotely. static::$_plugin['InfoURI'] = $remote['json_uri']; static::$_plugin['DownloadVersion'] = $remote['Version']; static::$_plugin['DownloadURI'] = $remote['DownloadURI']; } // Requesting just one key? if (! \is_null($key)) { return \array_key_exists($key, static::$_plugin) ? static::$_plugin[$key] : false; } // Send everything! return static::$_plugin; }
php
protected static function check_plugin($key=null) { if (\is_null(static::$_plugin)) { // Pull the remote info and store it for later. if (false === ($remote = static::get_release_info('Info URI', static::PLUGIN_TEMPLATE))) { static::$_plugin = false; return static::$_plugin; } // Use the main plugin headers as the basis. static::$_plugin = \get_plugin_data(\BLOBCOMMON_INDEX, false, false); // And add in what we pulled remotely. static::$_plugin['InfoURI'] = $remote['json_uri']; static::$_plugin['DownloadVersion'] = $remote['Version']; static::$_plugin['DownloadURI'] = $remote['DownloadURI']; } // Requesting just one key? if (! \is_null($key)) { return \array_key_exists($key, static::$_plugin) ? static::$_plugin[$key] : false; } // Send everything! return static::$_plugin; }
[ "protected", "static", "function", "check_plugin", "(", "$", "key", "=", "null", ")", "{", "if", "(", "\\", "is_null", "(", "static", "::", "$", "_plugin", ")", ")", "{", "// Pull the remote info and store it for later.", "if", "(", "false", "===", "(", "$",...
Check Plugin Info Unlike with the Phar library, this function only gathers the release information. Downloads are handled some other way. @param string $key Key. @return mixed Details, detail, false.
[ "Check", "Plugin", "Info" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/wp/lib/blobcommon.php#L339-L363
train
ventoviro/windwalker-core
src/Core/Composer/StarterInstaller.php
StarterInstaller.rootInstall
public static function rootInstall(Event $event) { include getcwd() . '/vendor/autoload.php'; $io = $event->getIO(); static::genSecretCode($io); static::genSecretConfig($io); // Complete $io->write('Install complete.'); }
php
public static function rootInstall(Event $event) { include getcwd() . '/vendor/autoload.php'; $io = $event->getIO(); static::genSecretCode($io); static::genSecretConfig($io); // Complete $io->write('Install complete.'); }
[ "public", "static", "function", "rootInstall", "(", "Event", "$", "event", ")", "{", "include", "getcwd", "(", ")", ".", "'/vendor/autoload.php'", ";", "$", "io", "=", "$", "event", "->", "getIO", "(", ")", ";", "static", "::", "genSecretCode", "(", "$",...
Do install. @param Event $event The command event. @return void
[ "Do", "install", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Composer/StarterInstaller.php#L31-L43
train
ventoviro/windwalker-core
src/Core/Composer/StarterInstaller.php
StarterInstaller.genSecretCode
protected static function genSecretCode(IOInterface $io) { $file = getcwd() . '/etc/conf/system.php'; $config = file_get_contents($file); $hash = 'Windwalker-' . hrtime(true); $salt = $io->ask("\nSalt to generate secret [{$hash}]: ", $hash); $config = str_replace('This-token-is-not-safe', md5(hrtime(true) . $salt), $config); file_put_contents($file, $config); $io->write('Auto created secret key.'); }
php
protected static function genSecretCode(IOInterface $io) { $file = getcwd() . '/etc/conf/system.php'; $config = file_get_contents($file); $hash = 'Windwalker-' . hrtime(true); $salt = $io->ask("\nSalt to generate secret [{$hash}]: ", $hash); $config = str_replace('This-token-is-not-safe', md5(hrtime(true) . $salt), $config); file_put_contents($file, $config); $io->write('Auto created secret key.'); }
[ "protected", "static", "function", "genSecretCode", "(", "IOInterface", "$", "io", ")", "{", "$", "file", "=", "getcwd", "(", ")", ".", "'/etc/conf/system.php'", ";", "$", "config", "=", "file_get_contents", "(", "$", "file", ")", ";", "$", "hash", "=", ...
Generate secret code. @param IOInterface $io @return void
[ "Generate", "secret", "code", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Composer/StarterInstaller.php#L52-L67
train
ventoviro/windwalker-core
src/Debugger/View/Database/DatabaseHtmlView.php
DatabaseHtmlView.highlightQuery
public function highlightQuery($query) { $newlineKeywords = '#\b(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|CASE)\b#i'; $query = htmlspecialchars($query, ENT_QUOTES); $query = preg_replace($newlineKeywords, '<br />&#160;&#160;\\0', $query); $regex = [ '/(=)/' => '<strong class="text-error">$1</strong>', // All uppercase words have a special meaning. '/(?<!\w|>)([A-Z_]{2,})(?!\w)/x' => '<span class="text-info">$1</span>', ]; $query = preg_replace(array_keys($regex), array_values($regex), $query); $query = str_replace('*', '<strong style="color: red;">*</strong>', $query); return $query; }
php
public function highlightQuery($query) { $newlineKeywords = '#\b(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|CASE)\b#i'; $query = htmlspecialchars($query, ENT_QUOTES); $query = preg_replace($newlineKeywords, '<br />&#160;&#160;\\0', $query); $regex = [ '/(=)/' => '<strong class="text-error">$1</strong>', // All uppercase words have a special meaning. '/(?<!\w|>)([A-Z_]{2,})(?!\w)/x' => '<span class="text-info">$1</span>', ]; $query = preg_replace(array_keys($regex), array_values($regex), $query); $query = str_replace('*', '<strong style="color: red;">*</strong>', $query); return $query; }
[ "public", "function", "highlightQuery", "(", "$", "query", ")", "{", "$", "newlineKeywords", "=", "'#\\b(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|CASE)\\b#i'", ";", "$", "query", "=", "htmlspecialchars", "(", "$", "query", ",", "ENT_QUOTES", ...
Simple highlight for SQL queries. @param string $query The query to highlight. @return string Highlighted query string.
[ "Simple", "highlight", "for", "SQL", "queries", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Debugger/View/Database/DatabaseHtmlView.php#L50-L72
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Product/Services/IdentResultsService.php
IdentResultsService.getListByRequestIds
public function getListByRequestIds($ids) { $parts = []; foreach ($ids as $id) { $parts[] = 'request.id:' . $id; } $qp = new QueryParams(); $qp->query = join(' OR ', $parts); return $this->getList($qp); }
php
public function getListByRequestIds($ids) { $parts = []; foreach ($ids as $id) { $parts[] = 'request.id:' . $id; } $qp = new QueryParams(); $qp->query = join(' OR ', $parts); return $this->getList($qp); }
[ "public", "function", "getListByRequestIds", "(", "$", "ids", ")", "{", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "ids", "as", "$", "id", ")", "{", "$", "parts", "[", "]", "=", "'request.id:'", ".", "$", "id", ";", "}", "$", "qp", ...
Returns an array of IdentResult instances for a given array of IdentRequest ids. @param array $ids The request ids. @return BaseCollection The obtained results. @throws ClientError @throws GuzzleException @throws ApiError @throws AuthError
[ "Returns", "an", "array", "of", "IdentResult", "instances", "for", "a", "given", "array", "of", "IdentRequest", "ids", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Product/Services/IdentResultsService.php#L30-L39
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Product/Services/IdentResultsService.php
IdentResultsService.process
private function process(IdentResult &$result) { if (isset($result->person)) { foreach ($result->person as $p) { $attachments = $p->attachments; if (!empty($attachments)) { foreach ($attachments as $attachment) { $this->initMediaResource($attachment); } } } } }
php
private function process(IdentResult &$result) { if (isset($result->person)) { foreach ($result->person as $p) { $attachments = $p->attachments; if (!empty($attachments)) { foreach ($attachments as $attachment) { $this->initMediaResource($attachment); } } } } }
[ "private", "function", "process", "(", "IdentResult", "&", "$", "result", ")", "{", "if", "(", "isset", "(", "$", "result", "->", "person", ")", ")", "{", "foreach", "(", "$", "result", "->", "person", "as", "$", "p", ")", "{", "$", "attachments", ...
Handles proper attachments initialization after retrieval of a ident result. @param IdentResult $result
[ "Handles", "proper", "attachments", "initialization", "after", "retrieval", "of", "a", "ident", "result", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Product/Services/IdentResultsService.php#L79-L91
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.array_compare
public static function array_compare(&$arr1, &$arr2) { // Obviously bad data. if (! \is_array($arr1) || ! \is_array($arr2)) { return false; } $length = \count($arr1); // Length mismatch. if (\count($arr2) !== $length) { return false; } // Different keys, we don't need to check further. if (\count(\array_intersect_key($arr1, $arr2)) !== $length) { return false; } // We will ignore keys for non-associative arrays. if ( (cast::array_type($arr1) !== 'associative') && (cast::array_type($arr2) !== 'associative') ) { return \count(\array_intersect($arr1, $arr2)) === $length; } // Check each item. foreach ($arr1 as $k=>$v) { if (! isset($arr2[$k])) { return false; } // Recursive? if (\is_array($arr1[$k]) && \is_array($arr2[$k])) { if (! static::array_compare($arr1[$k], $arr2[$k])) { return false; } } elseif ($arr1[$k] !== $arr2[$k]) { return false; } } return true; }
php
public static function array_compare(&$arr1, &$arr2) { // Obviously bad data. if (! \is_array($arr1) || ! \is_array($arr2)) { return false; } $length = \count($arr1); // Length mismatch. if (\count($arr2) !== $length) { return false; } // Different keys, we don't need to check further. if (\count(\array_intersect_key($arr1, $arr2)) !== $length) { return false; } // We will ignore keys for non-associative arrays. if ( (cast::array_type($arr1) !== 'associative') && (cast::array_type($arr2) !== 'associative') ) { return \count(\array_intersect($arr1, $arr2)) === $length; } // Check each item. foreach ($arr1 as $k=>$v) { if (! isset($arr2[$k])) { return false; } // Recursive? if (\is_array($arr1[$k]) && \is_array($arr2[$k])) { if (! static::array_compare($arr1[$k], $arr2[$k])) { return false; } } elseif ($arr1[$k] !== $arr2[$k]) { return false; } } return true; }
[ "public", "static", "function", "array_compare", "(", "&", "$", "arr1", ",", "&", "$", "arr2", ")", "{", "// Obviously bad data.", "if", "(", "!", "\\", "is_array", "(", "$", "arr1", ")", "||", "!", "\\", "is_array", "(", "$", "arr2", ")", ")", "{", ...
Compare Two Arrays @param array $arr1 Array. @param array $arr2 Array. @return bool True/false.
[ "Compare", "Two", "Arrays" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L22-L66
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.array_pop
public static function array_pop(array &$arr) { if (! \count($arr)) { return false; } $reversed = \array_reverse($arr); return static::array_pop_top($reversed); }
php
public static function array_pop(array &$arr) { if (! \count($arr)) { return false; } $reversed = \array_reverse($arr); return static::array_pop_top($reversed); }
[ "public", "static", "function", "array_pop", "(", "array", "&", "$", "arr", ")", "{", "if", "(", "!", "\\", "count", "(", "$", "arr", ")", ")", "{", "return", "false", ";", "}", "$", "reversed", "=", "\\", "array_reverse", "(", "$", "arr", ")", "...
Return the last value of an array. This is like array_pop() but non-destructive. @param array $arr Array. @return mixed Value. False on error.
[ "Return", "the", "last", "value", "of", "an", "array", "." ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L275-L282
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.array_pop_rand
public static function array_pop_rand(array &$arr) { $length = \count($arr); if (! $length) { return false; } // Nothing random about an array with one thing. if (1 === $length) { return static::array_pop_top($arr); } $keys = \array_keys($arr); $index = static::random_int(0, $length - 1); return $arr[$keys[$index]]; }
php
public static function array_pop_rand(array &$arr) { $length = \count($arr); if (! $length) { return false; } // Nothing random about an array with one thing. if (1 === $length) { return static::array_pop_top($arr); } $keys = \array_keys($arr); $index = static::random_int(0, $length - 1); return $arr[$keys[$index]]; }
[ "public", "static", "function", "array_pop_rand", "(", "array", "&", "$", "arr", ")", "{", "$", "length", "=", "\\", "count", "(", "$", "arr", ")", ";", "if", "(", "!", "$", "length", ")", "{", "return", "false", ";", "}", "// Nothing random about an a...
Return a random array element. @param array $arr Array. @return mixed Value. False on error.
[ "Return", "a", "random", "array", "element", "." ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L290-L306
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.array_pop_top
public static function array_pop_top(array &$arr) { if (! \count($arr)) { return false; } \reset($arr); return $arr[\key($arr)]; }
php
public static function array_pop_top(array &$arr) { if (! \count($arr)) { return false; } \reset($arr); return $arr[\key($arr)]; }
[ "public", "static", "function", "array_pop_top", "(", "array", "&", "$", "arr", ")", "{", "if", "(", "!", "\\", "count", "(", "$", "arr", ")", ")", "{", "return", "false", ";", "}", "\\", "reset", "(", "$", "arr", ")", ";", "return", "$", "arr", ...
Return the first value of an array. @param array $arr Array. @return mixed Value. False on error.
[ "Return", "the", "first", "value", "of", "an", "array", "." ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L314-L321
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.cc_exp_months
public static function cc_exp_months(string $format='m - M') { $months = array(); for ($x = 1; $x <= 12; ++$x) { $months[$x] = \date($format, \strtotime('2000-' . \sprintf('%02d', $x) . '-01')); } return $months; }
php
public static function cc_exp_months(string $format='m - M') { $months = array(); for ($x = 1; $x <= 12; ++$x) { $months[$x] = \date($format, \strtotime('2000-' . \sprintf('%02d', $x) . '-01')); } return $months; }
[ "public", "static", "function", "cc_exp_months", "(", "string", "$", "format", "=", "'m - M'", ")", "{", "$", "months", "=", "array", "(", ")", ";", "for", "(", "$", "x", "=", "1", ";", "$", "x", "<=", "12", ";", "++", "$", "x", ")", "{", "$", ...
Generate Credit Card Expiration Months @param string $format Date format. @return array Months.
[ "Generate", "Credit", "Card", "Expiration", "Months" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L329-L335
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.cc_exp_years
public static function cc_exp_years(int $length=10) { if ($length < 1) { $length = 10; } $years = array(); for ($x = 0; $x < $length; ++$x) { $year = (int) (\date('Y') + $x); $years[$year] = $year; } return $years; }
php
public static function cc_exp_years(int $length=10) { if ($length < 1) { $length = 10; } $years = array(); for ($x = 0; $x < $length; ++$x) { $year = (int) (\date('Y') + $x); $years[$year] = $year; } return $years; }
[ "public", "static", "function", "cc_exp_years", "(", "int", "$", "length", "=", "10", ")", "{", "if", "(", "$", "length", "<", "1", ")", "{", "$", "length", "=", "10", ";", "}", "$", "years", "=", "array", "(", ")", ";", "for", "(", "$", "x", ...
Generate Credit Card Expiration Years @param int $length Number of years. @return array Years.
[ "Generate", "Credit", "Card", "Expiration", "Years" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L343-L355
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.datediff
public static function datediff($date1, $date2) { ref\sanitize::date($date1); ref\sanitize::date($date2); // Same or bad dates. if ( ! \is_string($date1) || ! \is_string($date2) || ($date1 === $date2) || ('0000-00-00' === $date1) || ('0000-00-00' === $date2) ) { return 0; } // Prefer DateTime. if (\class_exists('DateTime')) { $date1 = new \DateTime($date1); $date2 = new \DateTime($date2); $diff = $date1->diff($date2); return \abs($diff->days); } // Fallback to counting seconds. $date1 = \strtotime($date1); $date2 = \strtotime($date2); return \ceil(\abs($date2 - $date1) / 60 / 60 / 24); }
php
public static function datediff($date1, $date2) { ref\sanitize::date($date1); ref\sanitize::date($date2); // Same or bad dates. if ( ! \is_string($date1) || ! \is_string($date2) || ($date1 === $date2) || ('0000-00-00' === $date1) || ('0000-00-00' === $date2) ) { return 0; } // Prefer DateTime. if (\class_exists('DateTime')) { $date1 = new \DateTime($date1); $date2 = new \DateTime($date2); $diff = $date1->diff($date2); return \abs($diff->days); } // Fallback to counting seconds. $date1 = \strtotime($date1); $date2 = \strtotime($date2); return \ceil(\abs($date2 - $date1) / 60 / 60 / 24); }
[ "public", "static", "function", "datediff", "(", "$", "date1", ",", "$", "date2", ")", "{", "ref", "\\", "sanitize", "::", "date", "(", "$", "date1", ")", ";", "ref", "\\", "sanitize", "::", "date", "(", "$", "date2", ")", ";", "// Same or bad dates.",...
Days Between Dates @param string $date1 Date. @param string $date2 Date. @return int Difference in Days.
[ "Days", "Between", "Dates" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L364-L392
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.in_range
public static function in_range($value, $min=null, $max=null) { return sanitize::to_range($value, $min, $max) === $value; }
php
public static function in_range($value, $min=null, $max=null) { return sanitize::to_range($value, $min, $max) === $value; }
[ "public", "static", "function", "in_range", "(", "$", "value", ",", "$", "min", "=", "null", ",", "$", "max", "=", "null", ")", "{", "return", "sanitize", "::", "to_range", "(", "$", "value", ",", "$", "min", ",", "$", "max", ")", "===", "$", "va...
Is Value In Range? @param mixed $value Value. @param mixed $min Min. @param mixed $max Max. @return bool True/false.
[ "Is", "Value", "In", "Range?" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L414-L416
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.ip_in_range
public static function ip_in_range(string $ip, $min, $max=null) { ref\sanitize::ip($ip, true); if (! \is_string($min)) { return false; } // Bad IP. if (! $ip) { return false; } // Is $min a range? if (false !== \strpos($min, '/')) { if (false === ($range = format::cidr_to_range($min))) { return false; } $min = $range['min']; $max = $range['max']; } // Max is required otherwise. elseif (null === $max) { return false; } // Convert everything to a number. ref\format::ip_to_number($ip); ref\format::ip_to_number($min); ref\format::ip_to_number($max); if ( (false !== $ip) && (false !== $min) && (false !== $max) ) { return static::in_range($ip, $min, $max); } return false; }
php
public static function ip_in_range(string $ip, $min, $max=null) { ref\sanitize::ip($ip, true); if (! \is_string($min)) { return false; } // Bad IP. if (! $ip) { return false; } // Is $min a range? if (false !== \strpos($min, '/')) { if (false === ($range = format::cidr_to_range($min))) { return false; } $min = $range['min']; $max = $range['max']; } // Max is required otherwise. elseif (null === $max) { return false; } // Convert everything to a number. ref\format::ip_to_number($ip); ref\format::ip_to_number($min); ref\format::ip_to_number($max); if ( (false !== $ip) && (false !== $min) && (false !== $max) ) { return static::in_range($ip, $min, $max); } return false; }
[ "public", "static", "function", "ip_in_range", "(", "string", "$", "ip", ",", "$", "min", ",", "$", "max", "=", "null", ")", "{", "ref", "\\", "sanitize", "::", "ip", "(", "$", "ip", ",", "true", ")", ";", "if", "(", "!", "\\", "is_string", "(", ...
IP in Range? Check to see if an IP is in range. This either accepts a minimum and maximum IP, or a CIDR. @param string $ip String. @param string $min Min or CIDR. @param string $max Max. @return bool True/false.
[ "IP", "in", "Range?" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L430-L468
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.is_utf8
public static function is_utf8($str) { if (\is_numeric($str) || \is_bool($str)) { return true; } elseif (\is_string($str)) { return (bool) \preg_match('//u', $str); } return false; }
php
public static function is_utf8($str) { if (\is_numeric($str) || \is_bool($str)) { return true; } elseif (\is_string($str)) { return (bool) \preg_match('//u', $str); } return false; }
[ "public", "static", "function", "is_utf8", "(", "$", "str", ")", "{", "if", "(", "\\", "is_numeric", "(", "$", "str", ")", "||", "\\", "is_bool", "(", "$", "str", ")", ")", "{", "return", "true", ";", "}", "elseif", "(", "\\", "is_string", "(", "...
Is Value Valid UTF-8? @param string $str String. @return bool True/false.
[ "Is", "Value", "Valid", "UTF", "-", "8?" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L496-L505
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.json_decode_array
public static function json_decode_array($json, $defaults=null, bool $strict=true, bool $recursive=true) { ref\format::json_decode($json); if ((null === $json) || (\is_string($json) && ! $json)) { $json = array(); } else { ref\cast::array($json); } if (\is_array($defaults)) { return static::parse_args($json, $defaults, $strict, $recursive); } else { return $json; } }
php
public static function json_decode_array($json, $defaults=null, bool $strict=true, bool $recursive=true) { ref\format::json_decode($json); if ((null === $json) || (\is_string($json) && ! $json)) { $json = array(); } else { ref\cast::array($json); } if (\is_array($defaults)) { return static::parse_args($json, $defaults, $strict, $recursive); } else { return $json; } }
[ "public", "static", "function", "json_decode_array", "(", "$", "json", ",", "$", "defaults", "=", "null", ",", "bool", "$", "strict", "=", "true", ",", "bool", "$", "recursive", "=", "true", ")", "{", "ref", "\\", "format", "::", "json_decode", "(", "$...
JSON Decode As Array This ensures a JSON string is always decoded to an array, optionally matching the structure of a template object. @param string $json JSON. @param mixed $defaults Template. @param bool $strict Enforce types if templating. @param bool $recursive Recursive templating. @return array Data.
[ "JSON", "Decode", "As", "Array" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L520-L536
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.length_in_range
public static function length_in_range(string $str, $min=null, $max=null) { if ((null !== $min) && ! \is_int($min)) { ref\cast::int($min, true); } if ((null !== $max) && ! \is_int($max)) { ref\cast::int($max, true); } $length = mb::strlen($str); if ((null !== $min) && (null !== $max) && $min > $max) { static::switcheroo($min, $max); } if ((null !== $min) && $min > $length) { return false; } if ((null !== $max) && $max < $length) { return false; } return true; }
php
public static function length_in_range(string $str, $min=null, $max=null) { if ((null !== $min) && ! \is_int($min)) { ref\cast::int($min, true); } if ((null !== $max) && ! \is_int($max)) { ref\cast::int($max, true); } $length = mb::strlen($str); if ((null !== $min) && (null !== $max) && $min > $max) { static::switcheroo($min, $max); } if ((null !== $min) && $min > $length) { return false; } if ((null !== $max) && $max < $length) { return false; } return true; }
[ "public", "static", "function", "length_in_range", "(", "string", "$", "str", ",", "$", "min", "=", "null", ",", "$", "max", "=", "null", ")", "{", "if", "(", "(", "null", "!==", "$", "min", ")", "&&", "!", "\\", "is_int", "(", "$", "min", ")", ...
Length in Range See if the length of a string is between two extremes. @param string $str String. @param int $min Min length. @param int $max Max length. @return bool True/false.
[ "Length", "in", "Range" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L548-L570
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.random_int
public static function random_int(int $min=0, int $max=1) { if ($min > $max) { static::switcheroo($min, $max); } return \random_int($min, $max); }
php
public static function random_int(int $min=0, int $max=1) { if ($min > $max) { static::switcheroo($min, $max); } return \random_int($min, $max); }
[ "public", "static", "function", "random_int", "(", "int", "$", "min", "=", "0", ",", "int", "$", "max", "=", "1", ")", "{", "if", "(", "$", "min", ">", "$", "max", ")", "{", "static", "::", "switcheroo", "(", "$", "min", ",", "$", "max", ")", ...
Generate Random Integer This will use the most secure function available for the environment. @param int $min Min. @param int $max Max. @return int Random number.
[ "Generate", "Random", "Integer" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L629-L635
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.random_string
public static function random_string(int $length=10, $soup=null) { if ($length < 1) { return ''; } if (\is_array($soup) && \count($soup)) { ref\cast::string($soup); $soup = \implode('', $soup); ref\sanitize::printable($soup); $soup = \preg_replace('/\s/u', '', $soup); $soup = \array_unique(mb::str_split($soup, 1, true)); $soup = \array_values($soup); if (! \count($soup)) { return ''; } } // Use default soup. if (! \is_array($soup) || ! \count($soup)) { $soup = constants::RANDOM_CHARS; } // Pick nine entries at random. $salt = ''; $max = \count($soup) - 1; for ($x = 0; $x < $length; ++$x) { $salt .= $soup[static::random_int(0, $max)]; } return $salt; }
php
public static function random_string(int $length=10, $soup=null) { if ($length < 1) { return ''; } if (\is_array($soup) && \count($soup)) { ref\cast::string($soup); $soup = \implode('', $soup); ref\sanitize::printable($soup); $soup = \preg_replace('/\s/u', '', $soup); $soup = \array_unique(mb::str_split($soup, 1, true)); $soup = \array_values($soup); if (! \count($soup)) { return ''; } } // Use default soup. if (! \is_array($soup) || ! \count($soup)) { $soup = constants::RANDOM_CHARS; } // Pick nine entries at random. $salt = ''; $max = \count($soup) - 1; for ($x = 0; $x < $length; ++$x) { $salt .= $soup[static::random_int(0, $max)]; } return $salt; }
[ "public", "static", "function", "random_string", "(", "int", "$", "length", "=", "10", ",", "$", "soup", "=", "null", ")", "{", "if", "(", "$", "length", "<", "1", ")", "{", "return", "''", ";", "}", "if", "(", "\\", "is_array", "(", "$", "soup",...
Generate Random String By default the string will only contain unambiguous uppercase letters and numbers. Alternate alphabets can be passed instead. @param int $length Length. @param array $soup Alternate alphabet. @return string Random string.
[ "Generate", "Random", "String" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L648-L680
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.switcheroo
public static function switcheroo(&$var1, &$var2) { $tmp = $var1; $var1 = $var2; $var2 = $tmp; return true; }
php
public static function switcheroo(&$var1, &$var2) { $tmp = $var1; $var1 = $var2; $var2 = $tmp; return true; }
[ "public", "static", "function", "switcheroo", "(", "&", "$", "var1", ",", "&", "$", "var2", ")", "{", "$", "tmp", "=", "$", "var1", ";", "$", "var1", "=", "$", "var2", ";", "$", "var2", "=", "$", "tmp", ";", "return", "true", ";", "}" ]
Switch Two Variables @param mixed $var1 Variable. @param mixed $var2 Variable. @return bool True.
[ "Switch", "Two", "Variables" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L689-L695
train
Blobfolio/blob-common
lib/blobfolio/common/data.php
data.unsetcookie
public static function unsetcookie(string $name, string $path='', string $domain='', bool $secure=false, bool $httponly=false) { if (! \headers_sent()) { \setcookie($name, false, -1, $path, $domain, $secure, $httponly); if (isset($_COOKIE[$name])) { unset($_COOKIE[$name]); } return true; } return false; }
php
public static function unsetcookie(string $name, string $path='', string $domain='', bool $secure=false, bool $httponly=false) { if (! \headers_sent()) { \setcookie($name, false, -1, $path, $domain, $secure, $httponly); if (isset($_COOKIE[$name])) { unset($_COOKIE[$name]); } return true; } return false; }
[ "public", "static", "function", "unsetcookie", "(", "string", "$", "name", ",", "string", "$", "path", "=", "''", ",", "string", "$", "domain", "=", "''", ",", "bool", "$", "secure", "=", "false", ",", "bool", "$", "httponly", "=", "false", ")", "{",...
Delete a Cookie A companion to PHP's `setcookie()` function. It attempts to remove the cookie. The same path, etc., values should be passed as were used to first set it. @param string $name Name. @param string $path Path. @param string $domain Domain. @param bool $secure SSL only. @param bool $httponly HTTP only. @return bool True/false.
[ "Delete", "a", "Cookie" ]
7b43d5526cc9d09853771d950b2956e98e680db1
https://github.com/Blobfolio/blob-common/blob/7b43d5526cc9d09853771d950b2956e98e680db1/lib/blobfolio/common/data.php#L711-L723
train
polyfony-inc/polyfony
Private/Polyfony/Uploader.php
Uploader.source
public function source($path, $override_chroot = true) { // if chroot is enabled, restrict the path to the chroot $this->Source = Filesystem::chroot($path, $override_chroot); // return self return($this); }
php
public function source($path, $override_chroot = true) { // if chroot is enabled, restrict the path to the chroot $this->Source = Filesystem::chroot($path, $override_chroot); // return self return($this); }
[ "public", "function", "source", "(", "$", "path", ",", "$", "override_chroot", "=", "true", ")", "{", "// if chroot is enabled, restrict the path to the chroot", "$", "this", "->", "Source", "=", "Filesystem", "::", "chroot", "(", "$", "path", ",", "$", "overrid...
set the source file path, disable chroot before of the tmp folder
[ "set", "the", "source", "file", "path", "disable", "chroot", "before", "of", "the", "tmp", "folder" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Uploader.php#L42-L47
train
polyfony-inc/polyfony
Private/Polyfony/Uploader.php
Uploader.destination
public function destination($path, $override_chroot = false) { // set the path $this->Destination = Filesystem::chroot($path, $override_chroot); // return self return($this); }
php
public function destination($path, $override_chroot = false) { // set the path $this->Destination = Filesystem::chroot($path, $override_chroot); // return self return($this); }
[ "public", "function", "destination", "(", "$", "path", ",", "$", "override_chroot", "=", "false", ")", "{", "// set the path", "$", "this", "->", "Destination", "=", "Filesystem", "::", "chroot", "(", "$", "path", ",", "$", "override_chroot", ")", ";", "//...
set the destination
[ "set", "the", "destination" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Uploader.php#L50-L55
train
polyfony-inc/polyfony
Private/Polyfony/Uploader.php
Uploader.limitTypes
public function limitTypes($allowed) { // if allowed is an array if(is_array($allowed)) { // push the whole table $this->Limits->Types = $allowed; } // allowed is a string else { // push it $this->Limits->Types[] = $allowed; } // return self return($this); }
php
public function limitTypes($allowed) { // if allowed is an array if(is_array($allowed)) { // push the whole table $this->Limits->Types = $allowed; } // allowed is a string else { // push it $this->Limits->Types[] = $allowed; } // return self return($this); }
[ "public", "function", "limitTypes", "(", "$", "allowed", ")", "{", "// if allowed is an array", "if", "(", "is_array", "(", "$", "allowed", ")", ")", "{", "// push the whole table", "$", "this", "->", "Limits", "->", "Types", "=", "$", "allowed", ";", "}", ...
limit types to array or mimetypes
[ "limit", "types", "to", "array", "or", "mimetypes" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Uploader.php#L69-L82
train
hnhdigital-os/laravel-model-schema
src/Model.php
Model.schemaCache
private static function schemaCache(...$args) { if (count($args) == 1) { $key = array_pop($args); if (isset(static::$schema_cache[$key])) { return static::$schema_cache[$key]; } return false; } list($key, $value) = $args; static::$schema_cache[$key] = $value; }
php
private static function schemaCache(...$args) { if (count($args) == 1) { $key = array_pop($args); if (isset(static::$schema_cache[$key])) { return static::$schema_cache[$key]; } return false; } list($key, $value) = $args; static::$schema_cache[$key] = $value; }
[ "private", "static", "function", "schemaCache", "(", "...", "$", "args", ")", "{", "if", "(", "count", "(", "$", "args", ")", "==", "1", ")", "{", "$", "key", "=", "array_pop", "(", "$", "args", ")", ";", "if", "(", "isset", "(", "static", "::", ...
Set or get Cache for this key. @param string $key @param array $data @return void
[ "Set", "or", "get", "Cache", "for", "this", "key", "." ]
ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e
https://github.com/hnhdigital-os/laravel-model-schema/blob/ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e/src/Model.php#L174-L188
train
hnhdigital-os/laravel-model-schema
src/Model.php
Model.getSchemaCache
private function getSchemaCache($key) { if (isset($this->model_schema_cache[$key])) { return $this->model_schema_cache[$key]; } return false; }
php
private function getSchemaCache($key) { if (isset($this->model_schema_cache[$key])) { return $this->model_schema_cache[$key]; } return false; }
[ "private", "function", "getSchemaCache", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "model_schema_cache", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "model_schema_cache", "[", "$", "key", "]", ";", "...
Get cache for this key. @param string $key @return void
[ "Get", "cache", "for", "this", "key", "." ]
ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e
https://github.com/hnhdigital-os/laravel-model-schema/blob/ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e/src/Model.php#L270-L277
train
hnhdigital-os/laravel-model-schema
src/Model.php
Model.setSchema
public function setSchema($entry, $keys, $value, $reset = false, $reset_value = null) { // Reset existing values in the schema. if ($reset) { $current = $this->getSchema($entry); foreach ($current as $key => $value) { if (is_null($reset_value)) { unset($this->schema[$key][$entry]); continue; } array_set($this->model_schema, $key.'.'.$entry, $reset_value); } } // Keys can be a single string attribute. if (!is_array($keys)) { $keys = [$keys]; } // Update each of the keys. foreach ($keys as $key) { array_set($this->model_schema, $key.'.'.$entry, $value); } // Break the cache. $this->breakSchemaCache($entry.'_0'); $this->breakSchemaCache($entry.'_1'); return $this; }
php
public function setSchema($entry, $keys, $value, $reset = false, $reset_value = null) { // Reset existing values in the schema. if ($reset) { $current = $this->getSchema($entry); foreach ($current as $key => $value) { if (is_null($reset_value)) { unset($this->schema[$key][$entry]); continue; } array_set($this->model_schema, $key.'.'.$entry, $reset_value); } } // Keys can be a single string attribute. if (!is_array($keys)) { $keys = [$keys]; } // Update each of the keys. foreach ($keys as $key) { array_set($this->model_schema, $key.'.'.$entry, $value); } // Break the cache. $this->breakSchemaCache($entry.'_0'); $this->breakSchemaCache($entry.'_1'); return $this; }
[ "public", "function", "setSchema", "(", "$", "entry", ",", "$", "keys", ",", "$", "value", ",", "$", "reset", "=", "false", ",", "$", "reset_value", "=", "null", ")", "{", "// Reset existing values in the schema.", "if", "(", "$", "reset", ")", "{", "$",...
Set an entry within the schema. @param string $entry @param string|array $keys @param bool $reset @param mixed $reset_value @return array
[ "Set", "an", "entry", "within", "the", "schema", "." ]
ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e
https://github.com/hnhdigital-os/laravel-model-schema/blob/ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e/src/Model.php#L301-L331
train
hnhdigital-os/laravel-model-schema
src/Model.php
Model.cache
protected function cache($key, $value) { if (array_has($this->model_cache, $key)) { return array_get($this->model_cache, $key); } if (is_callable($value)) { $result = $value(); } else { $result = $value; } array_set($this->model_cache, $key, $result); return $result; }
php
protected function cache($key, $value) { if (array_has($this->model_cache, $key)) { return array_get($this->model_cache, $key); } if (is_callable($value)) { $result = $value(); } else { $result = $value; } array_set($this->model_cache, $key, $result); return $result; }
[ "protected", "function", "cache", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "array_has", "(", "$", "this", "->", "model_cache", ",", "$", "key", ")", ")", "{", "return", "array_get", "(", "$", "this", "->", "model_cache", ",", "$", "...
Cache this value. @param string $key @param mixed $value @return mixed
[ "Cache", "this", "value", "." ]
ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e
https://github.com/hnhdigital-os/laravel-model-schema/blob/ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e/src/Model.php#L357-L372
train
hnhdigital-os/laravel-model-schema
src/Model.php
Model.boot
protected static function boot() { parent::boot(); // Boot event for creating this model. // Set default values if specified. // Validate dirty attributes before commiting to save. static::creating(function ($model) { $model->setDefaultValuesForAttributes(); if (!$model->savingValidation()) { $validator = $model->getValidator(); $issues = $validator->errors()->all(); $message = sprintf( "Validation failed on creating %s.\n%s", $model->getTable(), implode("\n", $issues) ); throw new Exceptions\ValidationException($message, 0, null, $validator); } }); // Boot event once model has been created. // Add missing attributes using the schema. static::created(function ($model) { $model->addMissingAttributes(); }); // Boot event for updating this model. // Validate dirty attributes before commiting to save. static::updating(function ($model) { if (!$model->savingValidation()) { $validator = $model->getValidator(); $issues = $validator->errors()->all(); $message = sprintf( "Validation failed on saving %s (%s).\n%s", $model->getTable(), $model->getKey(), implode("\n", $issues) ); throw new Exceptions\ValidationException($message, 0, null, $validator); } }); }
php
protected static function boot() { parent::boot(); // Boot event for creating this model. // Set default values if specified. // Validate dirty attributes before commiting to save. static::creating(function ($model) { $model->setDefaultValuesForAttributes(); if (!$model->savingValidation()) { $validator = $model->getValidator(); $issues = $validator->errors()->all(); $message = sprintf( "Validation failed on creating %s.\n%s", $model->getTable(), implode("\n", $issues) ); throw new Exceptions\ValidationException($message, 0, null, $validator); } }); // Boot event once model has been created. // Add missing attributes using the schema. static::created(function ($model) { $model->addMissingAttributes(); }); // Boot event for updating this model. // Validate dirty attributes before commiting to save. static::updating(function ($model) { if (!$model->savingValidation()) { $validator = $model->getValidator(); $issues = $validator->errors()->all(); $message = sprintf( "Validation failed on saving %s (%s).\n%s", $model->getTable(), $model->getKey(), implode("\n", $issues) ); throw new Exceptions\ValidationException($message, 0, null, $validator); } }); }
[ "protected", "static", "function", "boot", "(", ")", "{", "parent", "::", "boot", "(", ")", ";", "// Boot event for creating this model.", "// Set default values if specified.", "// Validate dirty attributes before commiting to save.", "static", "::", "creating", "(", "functi...
Boot events. @return void
[ "Boot", "events", "." ]
ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e
https://github.com/hnhdigital-os/laravel-model-schema/blob/ca0c51e9862aac43d19cf06fb8bb810d6bc7d41e/src/Model.php#L379-L425
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Auth/OauthProvider.php
OauthProvider.appyAuthorization
public function appyAuthorization(RequestInterface $request, array $options = null) { // Only sign requests using "auth"="oauth" // IMPORTANT: you have to create special auth client (GuzzleHttp\Client) if you want to get all the request authorized if (!isset($options['auth']) || $options['auth'] != 'oauth') { return $request; } // get Access token for current request $accessToken = $this->getAccessToken(); if (is_string($accessToken)) { return $request->withHeader('Authorization', 'Bearer ' . $accessToken); } else { throw new ClientError('Authentication error, invalid on no access token data returned.'); } }
php
public function appyAuthorization(RequestInterface $request, array $options = null) { // Only sign requests using "auth"="oauth" // IMPORTANT: you have to create special auth client (GuzzleHttp\Client) if you want to get all the request authorized if (!isset($options['auth']) || $options['auth'] != 'oauth') { return $request; } // get Access token for current request $accessToken = $this->getAccessToken(); if (is_string($accessToken)) { return $request->withHeader('Authorization', 'Bearer ' . $accessToken); } else { throw new ClientError('Authentication error, invalid on no access token data returned.'); } }
[ "public", "function", "appyAuthorization", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", "=", "null", ")", "{", "// Only sign requests using \"auth\"=\"oauth\"", "// IMPORTANT: you have to create special auth client (GuzzleHttp\\Client) if you want to get all...
Adds the authorization header if an access token was found @param RequestInterface $request @param array $options @return RequestInterface If the access token could not properly set to the request. @throws ClientError @throws ApiError @throws AuthError
[ "Adds", "the", "authorization", "header", "if", "an", "access", "token", "was", "found" ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Auth/OauthProvider.php#L105-L120
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Auth/OauthProvider.php
OauthProvider.updateToken
private function updateToken(RefreshTokenCredentials $refreshToken = null, $deviceCode = null) { $tokenData = null; // array of url parameters that will be sent in auth request $params = []; if ($refreshToken == null && !empty($deviceCode)) { $tokenData = $this->pollDeviceAccessToken($deviceCode); if ($tokenData === false) { return false; } } else { $this->setParams($params, $refreshToken == null ? $this->credentials : $refreshToken); try { $response = $this->post($params); $tokenData = MapperUtil::mapResponse($response); } catch (Exception $e) { throw($this->mapError($e, 'Error obtaining access token.')); } } if (empty($tokenData)) { throw new ClientError('Error obtaining access token.'); } // Process the returned data, both expired_in and refresh_token are optional parameters $this->accessToken = ['access_token' => $tokenData->access_token,]; if (isset($tokenData->expires_in)) { $this->accessToken['expires_in'] = time() + $tokenData->expires_in; } // Save access token to storage $this->storage->set('access_token', $this->accessToken); if (isset($tokenData->refresh_token)) { $this->refreshToken = $tokenData->refresh_token; // Save refresh token to storage $this->storage->set('refresh_token', $this->refreshToken); } // never delete existing refresh token return true; }
php
private function updateToken(RefreshTokenCredentials $refreshToken = null, $deviceCode = null) { $tokenData = null; // array of url parameters that will be sent in auth request $params = []; if ($refreshToken == null && !empty($deviceCode)) { $tokenData = $this->pollDeviceAccessToken($deviceCode); if ($tokenData === false) { return false; } } else { $this->setParams($params, $refreshToken == null ? $this->credentials : $refreshToken); try { $response = $this->post($params); $tokenData = MapperUtil::mapResponse($response); } catch (Exception $e) { throw($this->mapError($e, 'Error obtaining access token.')); } } if (empty($tokenData)) { throw new ClientError('Error obtaining access token.'); } // Process the returned data, both expired_in and refresh_token are optional parameters $this->accessToken = ['access_token' => $tokenData->access_token,]; if (isset($tokenData->expires_in)) { $this->accessToken['expires_in'] = time() + $tokenData->expires_in; } // Save access token to storage $this->storage->set('access_token', $this->accessToken); if (isset($tokenData->refresh_token)) { $this->refreshToken = $tokenData->refresh_token; // Save refresh token to storage $this->storage->set('refresh_token', $this->refreshToken); } // never delete existing refresh token return true; }
[ "private", "function", "updateToken", "(", "RefreshTokenCredentials", "$", "refreshToken", "=", "null", ",", "$", "deviceCode", "=", "null", ")", "{", "$", "tokenData", "=", "null", ";", "// array of url parameters that will be sent in auth request", "$", "params", "=...
Function to update token based on GrantTypeInterface @param RefreshTokenCredentials|null $refreshToken Refresh token to update existing token or null to obtain new token. @param null|string $deviceCode @return bool False on pending auth, true else. @throws ClientError @throws ApiError @throws AuthError @throws Exception
[ "Function", "to", "update", "token", "based", "on", "GrantTypeInterface" ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Auth/OauthProvider.php#L201-L244
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Auth/OauthProvider.php
OauthProvider.obtainDeviceVerification
private function obtainDeviceVerification() { if (!$this->credentials instanceof DeviceCredentials) { throw new ClientError('Invalid credentials set up, must be of type ' . DeviceCredentials::class); } $params = []; $this->setParams($params, $this->credentials); // if the guzzle gets response http_status other than 200, it will throw an exception even when there is response available try { $response = $this->post($params); return MapperUtil::mapResponse($response, new AuthCodes(), $this->logger); } catch (ClientException $e) { throw $this->mapError($e, 'Error requesting device codes.'); } }
php
private function obtainDeviceVerification() { if (!$this->credentials instanceof DeviceCredentials) { throw new ClientError('Invalid credentials set up, must be of type ' . DeviceCredentials::class); } $params = []; $this->setParams($params, $this->credentials); // if the guzzle gets response http_status other than 200, it will throw an exception even when there is response available try { $response = $this->post($params); return MapperUtil::mapResponse($response, new AuthCodes(), $this->logger); } catch (ClientException $e) { throw $this->mapError($e, 'Error requesting device codes.'); } }
[ "private", "function", "obtainDeviceVerification", "(", ")", "{", "if", "(", "!", "$", "this", "->", "credentials", "instanceof", "DeviceCredentials", ")", "{", "throw", "new", "ClientError", "(", "'Invalid credentials set up, must be of type '", ".", "DeviceCredentials...
Function to get device verification codes. @return mixed @throws ClientError @throws ApiError @throws AuthError @throws Exception
[ "Function", "to", "get", "device", "verification", "codes", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Auth/OauthProvider.php#L254-L271
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Auth/OauthProvider.php
OauthProvider.pollDeviceAccessToken
private function pollDeviceAccessToken($deviceCode) { if (!$this->credentials instanceof DeviceCredentials) { throw new ClientError('Invalid credentials set up, must be of type ' . DeviceCredentials::class); } $this->credentials->deviceCode = $deviceCode; $params = []; $this->setParams($params, $this->credentials); try { $response = $this->post($params); return MapperUtil::mapResponse($response); } catch (Exception $e) { // check for auth pending case $err = $this->mapError($e, 'Error during device authentication.'); if ($err instanceof AuthDeniedException && $err->getError() != null && $err->getError()->error === 'authorization_pending' ) { return false; } throw $err; } finally { // must reset to be ready for new auth attempt $this->credentials->deviceCode = null; } }
php
private function pollDeviceAccessToken($deviceCode) { if (!$this->credentials instanceof DeviceCredentials) { throw new ClientError('Invalid credentials set up, must be of type ' . DeviceCredentials::class); } $this->credentials->deviceCode = $deviceCode; $params = []; $this->setParams($params, $this->credentials); try { $response = $this->post($params); return MapperUtil::mapResponse($response); } catch (Exception $e) { // check for auth pending case $err = $this->mapError($e, 'Error during device authentication.'); if ($err instanceof AuthDeniedException && $err->getError() != null && $err->getError()->error === 'authorization_pending' ) { return false; } throw $err; } finally { // must reset to be ready for new auth attempt $this->credentials->deviceCode = null; } }
[ "private", "function", "pollDeviceAccessToken", "(", "$", "deviceCode", ")", "{", "if", "(", "!", "$", "this", "->", "credentials", "instanceof", "DeviceCredentials", ")", "{", "throw", "new", "ClientError", "(", "'Invalid credentials set up, must be of type '", ".", ...
Function to get access token data for device authorization. This method may be invoked multiple times until it returns the token data. @param string $deviceCode The device code obtained by obtainDeviceVerification(). @throws \Exception If a error happens. @return mixed | boolean Returns false if the authorization is still pending on server side and the access token data on success.
[ "Function", "to", "get", "access", "token", "data", "for", "device", "authorization", ".", "This", "method", "may", "be", "invoked", "multiple", "times", "until", "it", "returns", "the", "token", "data", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Auth/OauthProvider.php#L281-L308
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Product/Smart/TransactionsService.php
TransactionsService.prepare
public function prepare($transactionId, $type, $object = null) { if (!in_array( $type, [ self::TYPE_AUTO, self::TYPE_DIRECT_DEBIT, self::TYPE_CREDIT_CARD, self::TYPE_INVOICE, self::TYPE_PAYPAL, ] )) { throw new \InvalidArgumentException('Wrong transaction type'); } return $this->execute($transactionId, 'prepare', $type, $object, Transaction::class); }
php
public function prepare($transactionId, $type, $object = null) { if (!in_array( $type, [ self::TYPE_AUTO, self::TYPE_DIRECT_DEBIT, self::TYPE_CREDIT_CARD, self::TYPE_INVOICE, self::TYPE_PAYPAL, ] )) { throw new \InvalidArgumentException('Wrong transaction type'); } return $this->execute($transactionId, 'prepare', $type, $object, Transaction::class); }
[ "public", "function", "prepare", "(", "$", "transactionId", ",", "$", "type", ",", "$", "object", "=", "null", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "[", "self", "::", "TYPE_AUTO", ",", "self", "::", "TYPE_DIRECT_DEBIT", ",", "...
Preparing a transaction. @param string $transactionId The transaction id. @param string $type The transaction type like "auto" or "cash". @param null $object @return Transaction The prepared transaction. @throws GuzzleException @throws ApiError @throws AuthError @throws ClientError
[ "Preparing", "a", "transaction", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Product/Smart/TransactionsService.php#L60-L76
train
ventoviro/windwalker-core
src/Core/Mailer/MailAttachment.php
MailAttachment.getBody
public function getBody() { if ($this->body instanceof \Closure) { $method = $this->body; $this->body = $method(); } return $this->body; }
php
public function getBody() { if ($this->body instanceof \Closure) { $method = $this->body; $this->body = $method(); } return $this->body; }
[ "public", "function", "getBody", "(", ")", "{", "if", "(", "$", "this", "->", "body", "instanceof", "\\", "Closure", ")", "{", "$", "method", "=", "$", "this", "->", "body", ";", "$", "this", "->", "body", "=", "$", "method", "(", ")", ";", "}", ...
Method to get property Body @return string
[ "Method", "to", "get", "property", "Body" ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Mailer/MailAttachment.php#L133-L142
train
ventoviro/windwalker-core
src/Core/Schedule/Schedule.php
Schedule.getEvents
public function getEvents(array $tags = []): array { if ($tags === []) { return $this->events; } return array_filter($this->events, function (ScheduleEvent $event) use ($tags) { return array_intersect($event->getTags(), $tags) === $tags; }); }
php
public function getEvents(array $tags = []): array { if ($tags === []) { return $this->events; } return array_filter($this->events, function (ScheduleEvent $event) use ($tags) { return array_intersect($event->getTags(), $tags) === $tags; }); }
[ "public", "function", "getEvents", "(", "array", "$", "tags", "=", "[", "]", ")", ":", "array", "{", "if", "(", "$", "tags", "===", "[", "]", ")", "{", "return", "$", "this", "->", "events", ";", "}", "return", "array_filter", "(", "$", "this", "...
Method to get property Events @param array $tags @return ScheduleEvent[] @since 3.5.3
[ "Method", "to", "get", "property", "Events" ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Schedule/Schedule.php#L279-L288
train
ventoviro/windwalker-core
src/Core/View/Traits/LayoutRenderableTrait.php
LayoutRenderableTrait.setRenderer
public function setRenderer($renderer) { $this->renderer = $renderer instanceof AbstractRenderer ?: $this->getRendererManager()->getRenderer((string) $renderer); return $this; }
php
public function setRenderer($renderer) { $this->renderer = $renderer instanceof AbstractRenderer ?: $this->getRendererManager()->getRenderer((string) $renderer); return $this; }
[ "public", "function", "setRenderer", "(", "$", "renderer", ")", "{", "$", "this", "->", "renderer", "=", "$", "renderer", "instanceof", "AbstractRenderer", "?", ":", "$", "this", "->", "getRendererManager", "(", ")", "->", "getRenderer", "(", "(", "string", ...
Method to set property renderer @param AbstractRenderer|string $renderer @return static Return self to support chaining.
[ "Method", "to", "set", "property", "renderer" ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/View/Traits/LayoutRenderableTrait.php#L89-L94
train
ventoviro/windwalker-core
src/Core/View/Traits/LayoutRenderableTrait.php
LayoutRenderableTrait.getRendererManager
public function getRendererManager() { if (!$this->rendererManager) { $this->rendererManager = $this->getPackage()->getContainer()->get('renderer.manager'); } return $this->rendererManager; }
php
public function getRendererManager() { if (!$this->rendererManager) { $this->rendererManager = $this->getPackage()->getContainer()->get('renderer.manager'); } return $this->rendererManager; }
[ "public", "function", "getRendererManager", "(", ")", "{", "if", "(", "!", "$", "this", "->", "rendererManager", ")", "{", "$", "this", "->", "rendererManager", "=", "$", "this", "->", "getPackage", "(", ")", "->", "getContainer", "(", ")", "->", "get", ...
Method to get property RendererManager @return RendererManager
[ "Method", "to", "get", "property", "RendererManager" ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/View/Traits/LayoutRenderableTrait.php#L248-L255
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/FedoraCache.php
FedoraCache.deleteByUri
public function deleteByUri(string $uri) { if (!isset($this->cache[$uri])) { throw new NotInCache(); } foreach ($this->uri2id[$uri] as $id) { unset($this->id2uri[$id]); } unset($this->uri2id[$uri]); unset($this->cache[$uri]); }
php
public function deleteByUri(string $uri) { if (!isset($this->cache[$uri])) { throw new NotInCache(); } foreach ($this->uri2id[$uri] as $id) { unset($this->id2uri[$id]); } unset($this->uri2id[$uri]); unset($this->cache[$uri]); }
[ "public", "function", "deleteByUri", "(", "string", "$", "uri", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "$", "uri", "]", ")", ")", "{", "throw", "new", "NotInCache", "(", ")", ";", "}", "foreach", "(", "$", "this"...
Removes given resource from cache. @param string $uri resource URI
[ "Removes", "given", "resource", "from", "cache", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/FedoraCache.php#L77-L86
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/FedoraCache.php
FedoraCache.deleteById
public function deleteById(string $id) { if (!isset($this->id2uri[$id])) { throw new NotInCache(); } $this->deleteByUri($this->id2uri[$id]); }
php
public function deleteById(string $id) { if (!isset($this->id2uri[$id])) { throw new NotInCache(); } $this->deleteByUri($this->id2uri[$id]); }
[ "public", "function", "deleteById", "(", "string", "$", "id", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "id2uri", "[", "$", "id", "]", ")", ")", "{", "throw", "new", "NotInCache", "(", ")", ";", "}", "$", "this", "->", "deleteByU...
Removes resource with a given internal id from cache. @param string $id resource repo internal id @throws NotInCache
[ "Removes", "resource", "with", "a", "given", "internal", "id", "from", "cache", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/FedoraCache.php#L93-L98
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/FedoraCache.php
FedoraCache.reload
public function reload(FedoraResource $res) { if (isset($this->cache[$res->getUri(true)])) { $this->delete($res); } $this->add($res); }
php
public function reload(FedoraResource $res) { if (isset($this->cache[$res->getUri(true)])) { $this->delete($res); } $this->add($res); }
[ "public", "function", "reload", "(", "FedoraResource", "$", "res", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "cache", "[", "$", "res", "->", "getUri", "(", "true", ")", "]", ")", ")", "{", "$", "this", "->", "delete", "(", "$", "res",...
Refreshes given resource in cache. @param FedoraResource $res resource object
[ "Refreshes", "given", "resource", "in", "cache", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/FedoraCache.php#L112-L117
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/FedoraCache.php
FedoraCache.add
public function add(FedoraResource $res) { $uri = $res->getUri(true); if (isset($this->cache[$uri])) { if (get_class($res) === get_class($this->cache[$uri])) { throw new AlreadyInCache(); } else { $this->deleteByUri($uri); } } try { $ids = $res->getIds(); $this->cache[$uri] = $res; $this->uri2id[$uri] = array(); foreach ($ids as $id) { $this->uri2id[$uri][] = $id; $this->id2uri[$id] = $uri; } } catch (ClientException $e) { switch ($e->getCode()) { case 404: throw new NotFound(); case 410: throw new Deleted(); default: throw $e; } } }
php
public function add(FedoraResource $res) { $uri = $res->getUri(true); if (isset($this->cache[$uri])) { if (get_class($res) === get_class($this->cache[$uri])) { throw new AlreadyInCache(); } else { $this->deleteByUri($uri); } } try { $ids = $res->getIds(); $this->cache[$uri] = $res; $this->uri2id[$uri] = array(); foreach ($ids as $id) { $this->uri2id[$uri][] = $id; $this->id2uri[$id] = $uri; } } catch (ClientException $e) { switch ($e->getCode()) { case 404: throw new NotFound(); case 410: throw new Deleted(); default: throw $e; } } }
[ "public", "function", "add", "(", "FedoraResource", "$", "res", ")", "{", "$", "uri", "=", "$", "res", "->", "getUri", "(", "true", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "cache", "[", "$", "uri", "]", ")", ")", "{", "if", "(", ...
Adds given object to the cache. @param FedoraResource $res resource object @throws AlreadyInCache @throws NotFound @throws Deleted @throws ClientException
[ "Adds", "given", "object", "to", "the", "cache", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/FedoraCache.php#L127-L154
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/FedoraCache.php
FedoraCache.getById
public function getById(string $id): FedoraResource { if (!isset($this->id2uri[$id])) { throw new NotInCache(); } return $this->cache[$this->id2uri[$id]]; }
php
public function getById(string $id): FedoraResource { if (!isset($this->id2uri[$id])) { throw new NotInCache(); } return $this->cache[$this->id2uri[$id]]; }
[ "public", "function", "getById", "(", "string", "$", "id", ")", ":", "FedoraResource", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "id2uri", "[", "$", "id", "]", ")", ")", "{", "throw", "new", "NotInCache", "(", ")", ";", "}", "return", ...
Gets a resource from cache by its repo internal id. @param string $id resource's repo internal id @return FedoraResource @throws NotInCache
[ "Gets", "a", "resource", "from", "cache", "by", "its", "repo", "internal", "id", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/FedoraCache.php#L162-L167
train
acdh-oeaw/repo-php-util
src/acdhOeaw/fedora/FedoraCache.php
FedoraCache.getByUri
public function getByUri(string $uri): FedoraResource { if (!isset($this->cache[$uri])) { throw new NotInCache(); } return $this->cache[$uri]; }
php
public function getByUri(string $uri): FedoraResource { if (!isset($this->cache[$uri])) { throw new NotInCache(); } return $this->cache[$uri]; }
[ "public", "function", "getByUri", "(", "string", "$", "uri", ")", ":", "FedoraResource", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "$", "uri", "]", ")", ")", "{", "throw", "new", "NotInCache", "(", ")", ";", "}", "return",...
Gets a resource from cache by its URI. @param string $uri resource URI @return FedoraResource @throws NotInCache
[ "Gets", "a", "resource", "from", "cache", "by", "its", "URI", "." ]
e22c7cd2613f3c8daf0deee879896d9cd7f61b41
https://github.com/acdh-oeaw/repo-php-util/blob/e22c7cd2613f3c8daf0deee879896d9cd7f61b41/src/acdhOeaw/fedora/FedoraCache.php#L175-L180
train