idx int64 0 60.3k | question stringlengths 101 6.21k | target stringlengths 7 803 |
|---|---|---|
13,500 | public static function weightedMean ( array $ values , array $ weights , ? int $ n = null ) : float { $ n = $ n ?? count ( $ values ) ; if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Mean is undefined for empty' . ' set.' ) ; } if ( count ( $ weights ) !== $ n ) { throw new InvalidArgumentException ( 'The number of weights must' . ' equal the number of values.' ) ; } $ total = array_sum ( $ weights ) ? : EPSILON ; $ temp = 0. ; foreach ( $ values as $ i => $ value ) { $ temp += $ value * ( $ weights [ $ i ] ? : EPSILON ) ; } return $ temp / $ total ; } | Compute the weighted mean of a set of values . |
13,501 | public static function mode ( array $ values ) : float { if ( empty ( $ values ) ) { throw new InvalidArgumentException ( 'Mode is undefined for empty' . ' set.' ) ; } $ counts = array_count_values ( array_map ( 'strval' , $ values ) ) ; return ( float ) argmax ( $ counts ) ; } | Find a mode of a set of values i . e a value that appears most often in the set . |
13,502 | public static function variance ( array $ values , ? float $ mean = null , ? int $ n = null ) : float { $ n = $ n ?? count ( $ values ) ; if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Variance is undefined for an' . ' empty set.' ) ; } $ mean = $ mean ?? self :: mean ( $ values ) ; $ ssd = 0. ; foreach ( $ values as $ value ) { $ ssd += ( $ value - $ mean ) ** 2 ; } return $ ssd / $ n ; } | Compute the variance of a set of values given a mean and n degrees of freedom . |
13,503 | public static function median ( array $ values ) : float { $ n = count ( $ values ) ; if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Median is undefined for empty' . ' set.' ) ; } $ mid = intdiv ( $ n , 2 ) ; sort ( $ values ) ; if ( $ n % 2 === 1 ) { $ median = $ values [ $ mid ] ; } else { $ median = self :: mean ( [ $ values [ $ mid - 1 ] , $ values [ $ mid ] ] ) ; } return $ median ; } | Calculate the median of a set of values . |
13,504 | public static function percentile ( array $ values , float $ p ) : float { if ( empty ( $ values ) ) { throw new InvalidArgumentException ( 'Percentile is not defined for' . ' an empty set.' ) ; } if ( $ p < 0. or $ p > 100. ) { throw new InvalidArgumentException ( 'P must be between 0 and 1,' . " $p given." ) ; } $ n = count ( $ values ) ; sort ( $ values ) ; $ x = ( $ p / 100 ) * ( $ n - 1 ) + 1 ; $ xHat = ( int ) $ x ; $ remainder = $ x - $ xHat ; $ a = $ values [ $ xHat - 1 ] ; $ b = $ values [ $ xHat ] ; return $ a + $ remainder * ( $ b - $ a ) ; } | Calculate the pth percentile of a given set of values . |
13,505 | public static function iqr ( array $ values ) : float { $ n = count ( $ values ) ; if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Interquartile range is not' . ' defined for empty set.' ) ; } $ mid = intdiv ( $ n , 2 ) ; sort ( $ values ) ; if ( $ n % 2 === 0 ) { $ lower = array_slice ( $ values , 0 , $ mid ) ; $ upper = array_slice ( $ values , $ mid ) ; } else { $ lower = array_slice ( $ values , 0 , $ mid ) ; $ upper = array_slice ( $ values , $ mid + 1 ) ; } return self :: median ( $ upper ) - self :: median ( $ lower ) ; } | Compute the interquartile range of a set of values . |
13,506 | public static function mad ( array $ values , ? float $ median = null ) : float { $ median = $ median ?? self :: median ( $ values ) ; $ deviations = [ ] ; foreach ( $ values as $ value ) { $ deviations [ ] = abs ( $ value - $ median ) ; } return self :: median ( $ deviations ) ; } | Calculate the median absolute deviation of a set of values given a median . |
13,507 | public static function centralMoment ( array $ values , int $ moment , ? float $ mean = null , ? int $ n = null ) : float { $ n = $ n ?? count ( $ values ) ; if ( $ n < 1 ) { throw new InvalidArgumentException ( 'Central moment is undefined for' . ' empty set.' ) ; } $ mean = $ mean ?? self :: mean ( $ values , $ n ) ; $ sigma = 0. ; foreach ( $ values as $ value ) { $ sigma += ( $ value - $ mean ) ** $ moment ; } return $ sigma / $ n ; } | Compute the n - th central moment of a set of values . |
13,508 | public static function skewness ( array $ values , ? float $ mean = null , ? int $ n = null ) : float { $ n = $ n ?? count ( $ values ) ; if ( $ n === 0 ) { throw new InvalidArgumentException ( 'Skewness is undefined for' . ' empty set.' ) ; } $ mean = $ mean ?? self :: mean ( $ values , $ n ) ; $ numerator = self :: centralMoment ( $ values , 3 , $ mean ) ; $ denominator = self :: centralMoment ( $ values , 2 , $ mean ) ** 1.5 ; return $ numerator / ( $ denominator ? : EPSILON ) ; } | Compute the skewness of a set of values given a mean and n degrees of freedom . |
13,509 | public static function range ( array $ values ) : float { if ( empty ( $ values ) ) { throw new InvalidArgumentException ( 'Range is undefined for empty' . ' set.' ) ; } return ( float ) ( max ( $ values ) - min ( $ values ) ) ; } | Return the statistical range given by the maximum minus the minimum of a set of values . |
13,510 | public static function meanVar ( array $ values ) : array { $ mean = self :: mean ( $ values ) ; return [ $ mean , self :: variance ( $ values , $ mean ) ] ; } | Compute the population mean and variance and return them in a 2 - tuple . |
13,511 | public static function medMad ( array $ values ) : array { $ median = self :: median ( $ values ) ; return [ $ median , self :: mad ( $ values , $ median ) ] ; } | Compute the population median and median absolute deviation and return them in a 2 - tuple . |
13,512 | public function compute ( Tensor $ expected , Tensor $ output ) : float { return $ expected -> negate ( ) -> multiply ( $ output -> log ( ) ) -> sum ( ) -> mean ( ) ; } | Compute the matrix . |
13,513 | public function search ( array $ sample ) : ? BinaryNode { $ current = $ this -> root ; while ( $ current ) { if ( $ current instanceof Decision ) { $ value = $ current -> value ( ) ; if ( is_string ( $ value ) ) { if ( $ sample [ $ current -> column ( ) ] === $ value ) { $ current = $ current -> left ( ) ; } else { $ current = $ current -> right ( ) ; } } else { if ( $ sample [ $ current -> column ( ) ] < $ value ) { $ current = $ current -> left ( ) ; } else { $ current = $ current -> right ( ) ; } } continue 1 ; } if ( $ current instanceof Leaf ) { break 1 ; } } return $ current ; } | Search the tree for a leaf node . |
13,514 | public function featureImportances ( ) : array { if ( ! $ this -> root ) { return [ ] ; } $ importances = array_fill ( 0 , $ this -> featureCount , 0. ) ; foreach ( $ this -> dump ( ) as $ node ) { if ( $ node instanceof Decision ) { $ index = $ node -> column ( ) ; $ importances [ $ index ] += $ node -> purityIncrease ( ) ; } } $ total = array_sum ( $ importances ) ? : self :: BETA ; foreach ( $ importances as & $ importance ) { $ importance /= $ total ; } arsort ( $ importances ) ; return $ importances ; } | Return an array indexed by feature column that contains the normalized importance score of that feature . |
13,515 | public function dump ( ) : Generator { $ nodes = [ ] ; $ stack = [ $ this -> root ] ; while ( $ stack ) { $ current = array_pop ( $ stack ) ; if ( $ current instanceof BinaryNode ) { foreach ( $ current -> children ( ) as $ child ) { $ stack [ ] = $ child ; } } yield $ current ; } } | Return a generator for all the nodes in the tree starting at the root . |
13,516 | protected static function c ( int $ n ) : float { if ( $ n <= 1 ) { return 1. ; } return 2. * ( log ( $ n - 1 ) + M_EULER ) - 2. * ( $ n - 1 ) / $ n ; } | Calculate the average path length of an unsuccessful search for n nodes . |
13,517 | public function update ( Tensor $ step ) : void { $ this -> w = $ this -> w ( ) -> subtract ( $ step ) ; } | Update the parameter . |
13,518 | public function train ( Dataset $ dataset ) : void { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This estimator requires a' . ' labeled training set.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; $ k = $ dataset -> numColumns ( ) ; $ this -> columns = range ( 0 , $ dataset -> numColumns ( ) - 1 ) ; $ this -> maxFeatures = $ this -> maxFeatures ?? ( int ) round ( sqrt ( $ k ) ) ; $ this -> grow ( $ dataset ) ; $ this -> columns = [ ] ; } | Train the regression tree by learning the optimal splits in the training set . |
13,519 | public function predict ( Dataset $ dataset ) : array { if ( $ this -> bare ( ) ) { throw new RuntimeException ( 'Estimator has not been trained.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; $ predictions = [ ] ; foreach ( $ dataset as $ sample ) { $ node = $ this -> search ( $ sample ) ; $ predictions [ ] = $ node instanceof Average ? $ node -> outcome ( ) : null ; } return $ predictions ; } | Make a prediction based on the value of a terminal node in the tree . |
13,520 | protected function split ( Labeled $ dataset ) : Decision { $ bestVariance = INF ; $ bestColumn = $ bestValue = null ; $ bestGroups = [ ] ; shuffle ( $ this -> columns ) ; foreach ( array_slice ( $ this -> columns , 0 , $ this -> maxFeatures ) as $ column ) { $ values = array_unique ( $ dataset -> column ( $ column ) ) ; foreach ( $ values as $ value ) { $ groups = $ dataset -> partition ( $ column , $ value ) ; $ variance = $ this -> splitImpurity ( $ groups ) ; if ( $ variance < $ bestVariance ) { $ bestColumn = $ column ; $ bestValue = $ value ; $ bestGroups = $ groups ; $ bestVariance = $ variance ; } if ( $ variance <= $ this -> tolerance ) { break 2 ; } } } return new Decision ( $ bestColumn , $ bestValue , $ bestGroups , $ bestVariance ) ; } | Greedy algorithm to chose the best split for a given dataset as determined by the variance of the split . |
13,521 | protected function terminate ( Labeled $ dataset ) : BinaryNode { [ $ mean , $ variance ] = Stats :: meanVar ( $ dataset -> labels ( ) ) ; return new Average ( $ mean , $ variance , $ dataset -> numRows ( ) ) ; } | Terminate the branch with the most likely outcome . |
13,522 | protected function splitImpurity ( array $ groups ) : float { $ n = array_sum ( array_map ( 'count' , $ groups ) ) ; $ impurity = 0. ; foreach ( $ groups as $ dataset ) { $ k = $ dataset -> numRows ( ) ; if ( $ k < 2 ) { continue 1 ; } $ variance = Stats :: variance ( $ dataset -> labels ( ) ) ; $ impurity += ( $ k / $ n ) * $ variance ; } return $ impurity ; } | Calculate the weighted variance for the split . |
13,523 | public function featureImportances ( ) : array { if ( ! $ this -> forest or ! $ this -> featureCount ) { return [ ] ; } $ importances = array_fill ( 0 , $ this -> featureCount , 0. ) ; foreach ( $ this -> forest as $ tree ) { foreach ( $ tree -> featureImportances ( ) as $ column => $ value ) { $ importances [ $ column ] += $ value ; } } $ k = count ( $ this -> forest ) ; foreach ( $ importances as & $ importance ) { $ importance /= $ k ; } return $ importances ; } | Return the feature importances calculated during training keyed by feature column . |
13,524 | public static function gaussian ( ) : float { $ r1 = rand ( 0 , PHP_INT_MAX ) / PHP_INT_MAX ; $ r2 = rand ( 0 , PHP_INT_MAX ) / PHP_INT_MAX ; return sqrt ( - 2. * log ( $ r1 ) ) * cos ( TWO_PI * $ r2 ) ; } | Generate a random number from a Gaussian distribution with 0 mean and standard deviation of 1 . |
13,525 | public function warm ( Parameter $ param ) : void { $ velocity = get_class ( $ param -> w ( ) ) :: zeros ( ... $ param -> w ( ) -> shape ( ) ) ; $ g2 = clone $ velocity ; $ this -> cache [ $ param -> id ( ) ] = [ $ velocity , $ g2 ] ; } | Warm the cache with a parameter . |
13,526 | public function step ( Parameter $ param , Tensor $ gradient ) : void { [ $ velocity , $ g2 ] = $ this -> cache [ $ param -> id ( ) ] ; $ velocity = $ velocity -> multiply ( $ this -> momentumDecay ) -> add ( $ gradient -> multiply ( 1. - $ this -> momentumDecay ) ) ; $ g2 = $ g2 -> multiply ( $ this -> rmsDecay ) -> add ( $ gradient -> square ( ) -> multiply ( 1. - $ this -> rmsDecay ) ) ; $ this -> cache [ $ param -> id ( ) ] = [ $ velocity , $ g2 ] ; if ( $ this -> t < self :: WARM_UP_STEPS ) { $ this -> t ++ ; $ velocity = $ velocity -> divide ( 1. - $ this -> momentumDecay ** $ this -> t ) ; $ g2 = $ g2 -> divide ( 1. - $ this -> rmsDecay ** $ this -> t ) ; } $ step = $ velocity -> multiply ( $ this -> rate ) -> divide ( $ g2 -> sqrt ( ) -> clipLower ( EPSILON ) ) ; $ param -> update ( $ step ) ; } | Calculate a gradient descent step for a given parameter . |
13,527 | public function compute ( Matrix $ z ) : Matrix { $ zHat = $ z -> transpose ( ) -> exp ( ) ; $ total = $ zHat -> sum ( ) ; return $ zHat -> divide ( $ total ) -> transpose ( ) ; } | Compute the output value . |
13,528 | public static function precision ( int $ tp , int $ fp ) : float { return $ tp / ( ( $ tp + $ fp ) ? : EPSILON ) ; } | Compute the class precision . |
13,529 | public static function recall ( int $ tp , int $ fn ) : float { return $ tp / ( ( $ tp + $ fn ) ? : EPSILON ) ; } | Compute the class recall . |
13,530 | public function save ( Persistable $ persistable ) : void { if ( $ this -> history and is_file ( $ this -> path ) ) { $ filename = $ this -> path . '.' . ( string ) time ( ) . self :: HISTORY_EXT ; if ( ! rename ( $ this -> path , $ filename ) ) { throw new RuntimeException ( 'Failed to rename history,' . ' file, check path and permissions.' ) ; } } if ( is_file ( $ this -> path ) and ! is_writable ( $ this -> path ) ) { throw new RuntimeException ( "File $this->path is not writable." ) ; } $ data = $ this -> serializer -> serialize ( $ persistable ) ; if ( ! file_put_contents ( $ this -> path , $ data , LOCK_EX ) ) { throw new RuntimeException ( 'Failed to save persistable to' . ' filesystem, check path and permissions.' ) ; } } | Save the persitable model . |
13,531 | public function search ( array $ sample ) : ? Cell { $ current = $ this -> root ; while ( $ current ) { if ( $ current instanceof Isolator ) { $ value = $ current -> value ( ) ; if ( is_string ( $ value ) ) { if ( $ sample [ $ current -> column ( ) ] === $ value ) { $ current = $ current -> left ( ) ; } else { $ current = $ current -> right ( ) ; } } else { if ( $ sample [ $ current -> column ( ) ] < $ value ) { $ current = $ current -> left ( ) ; } else { $ current = $ current -> right ( ) ; } } continue 1 ; } if ( $ current instanceof Cell ) { return $ current ; } } return null ; } | Search the tree for a terminal node . |
13,532 | public function purityIncrease ( ) : float { $ impurity = $ this -> impurity ; if ( $ this -> left instanceof Purity ) { $ impurity -= $ this -> left -> impurity ( ) * ( $ this -> left -> n ( ) / $ this -> n ) ; } if ( $ this -> right instanceof Purity ) { $ impurity -= $ this -> right -> impurity ( ) * ( $ this -> right -> n ( ) / $ this -> n ) ; } return $ impurity ; } | Return the decrease in impurity this decision node introduces . |
13,533 | public function priors ( ) : array { $ priors = [ ] ; if ( is_array ( $ this -> priors ) ) { $ max = logsumexp ( $ this -> priors ) ; foreach ( $ this -> priors as $ class => $ probability ) { $ priors [ $ class ] = exp ( $ probability - $ max ) ; } } return $ priors ; } | Return the class prior probabilities . |
13,534 | public function partial ( Dataset $ dataset ) : void { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This Estimator requires a' . ' Labeled training set.' ) ; } if ( ! $ dataset -> homogeneous ( ) or $ dataset -> columnType ( 0 ) !== DataType :: CATEGORICAL ) { throw new InvalidArgumentException ( 'This estimator only works' . ' with categorical features.' ) ; } if ( empty ( $ this -> weights ) or empty ( $ this -> counts ) or empty ( $ this -> probs ) ) { $ this -> train ( $ dataset ) ; return ; } foreach ( $ dataset -> stratify ( ) as $ class => $ stratum ) { $ classCounts = $ this -> counts [ $ class ] ; $ classProbs = $ this -> probs [ $ class ] ; foreach ( $ stratum -> columns ( ) as $ column => $ values ) { $ columnCounts = $ classCounts [ $ column ] ; $ counts = array_count_values ( $ values ) ; foreach ( $ counts as $ category => $ count ) { if ( isset ( $ columnCounts [ $ category ] ) ) { $ columnCounts [ $ category ] += $ count ; } else { $ columnCounts [ $ category ] = $ count ; } } $ total = ( array_sum ( $ columnCounts ) + ( count ( $ columnCounts ) * $ this -> alpha ) ) ? : EPSILON ; $ probs = [ ] ; foreach ( $ columnCounts as $ category => $ count ) { $ probs [ $ category ] = log ( ( $ count + $ this -> alpha ) / $ total ) ; } $ classCounts [ $ column ] = $ columnCounts ; $ classProbs [ $ column ] = $ probs ; } $ this -> counts [ $ class ] = $ classCounts ; $ this -> probs [ $ class ] = $ classProbs ; $ this -> weights [ $ class ] += $ stratum -> numRows ( ) ; } if ( $ this -> fitPriors ) { $ total = ( array_sum ( $ this -> weights ) + ( count ( $ this -> weights ) * $ this -> alpha ) ) ? : EPSILON ; foreach ( $ this -> weights as $ class => $ weight ) { $ this -> priors [ $ class ] = log ( ( $ weight + $ this -> alpha ) / $ total ) ; } } } | Compute the rolling counts and conditional probabilities . |
13,535 | protected function score ( Dataset $ dataset ) : array { $ scores = array_fill ( 0 , $ dataset -> numRows ( ) , array_fill_keys ( $ this -> classes , 0. ) ) ; foreach ( $ this -> ensemble as $ i => $ estimator ) { $ influence = $ this -> influences [ $ i ] ; foreach ( $ estimator -> predict ( $ dataset ) as $ j => $ prediction ) { $ scores [ $ j ] [ $ prediction ] += $ influence ; } } return $ scores ; } | Return the influence scores for each sample in the dataset . |
13,536 | public function partial ( Dataset $ dataset ) : void { if ( ! $ dataset instanceof Labeled ) { throw new InvalidArgumentException ( 'This estimator requires a' . ' labeled training set.' ) ; } DatasetIsCompatibleWithEstimator :: check ( $ dataset , $ this ) ; $ this -> classes = array_unique ( array_merge ( $ this -> classes , $ dataset -> possibleOutcomes ( ) ) ) ; $ this -> samples = array_merge ( $ this -> samples , $ dataset -> samples ( ) ) ; $ this -> labels = array_merge ( $ this -> labels , $ dataset -> labels ( ) ) ; } | Store the sample and outcome arrays . No other work to be done as this is a lazy learning algorithm . |
13,537 | public function layers ( ) : Generator { yield $ this -> input ; foreach ( $ this -> hidden as $ hidden ) { yield $ hidden ; } yield $ this -> output ; } | Return all the layers in the network . |
13,538 | public function parametric ( ) : Generator { foreach ( $ this -> hidden as $ layer ) { if ( $ layer instanceof Parametric ) { yield $ layer ; } } if ( $ this -> output instanceof Parametric ) { yield $ this -> output ; } } | The parametric layers of the network . i . e . the layers that have weights . |
13,539 | public function roundtrip ( Labeled $ batch ) : float { $ input = Matrix :: quick ( $ batch -> samples ( ) ) -> transpose ( ) ; $ this -> feed ( $ input ) ; return $ this -> backpropagate ( $ batch -> labels ( ) ) ; } | Do a forward and backward pass of the network in one call . Returns the loss from the backward pass . |
13,540 | public function feed ( Matrix $ input ) : Matrix { $ input = $ this -> input -> forward ( $ input ) ; foreach ( $ this -> hidden as $ hidden ) { $ input = $ hidden -> forward ( $ input ) ; } return $ this -> output -> forward ( $ input ) ; } | Feed a batch through the network and return a matrix of activations . |
13,541 | public function infer ( Matrix $ input ) : Tensor { $ input = $ this -> input -> infer ( $ input ) ; foreach ( $ this -> hidden as $ hidden ) { $ input = $ hidden -> infer ( $ input ) ; } return $ this -> output -> infer ( $ input ) ; } | Run an inference pass and return the activations at the output layer . |
13,542 | public function backpropagate ( array $ labels ) : float { [ $ gradient , $ loss ] = $ this -> output -> back ( $ labels , $ this -> optimizer ) ; foreach ( $ this -> backPass as $ layer ) { $ gradient = $ layer -> back ( $ gradient , $ this -> optimizer ) ; } return $ loss ; } | Backpropagate the gradient produced by the cost function and return the loss calculated by the output layer s cost function . |
13,543 | public function restore ( Snapshot $ snapshot ) : void { foreach ( $ snapshot as [ $ layer , $ params ] ) { if ( $ layer instanceof Parametric ) { $ layer -> restore ( $ params ) ; } } } | Restore the network parameters from a snapshot . |
13,544 | public function search ( array $ sample ) : ? Neighborhood { $ current = $ this -> root ; while ( $ current ) { if ( $ current instanceof Coordinate ) { if ( $ sample [ $ current -> column ( ) ] < $ current -> value ( ) ) { $ current = $ current -> left ( ) ; } else { $ current = $ current -> right ( ) ; } continue 1 ; } if ( $ current instanceof Neighborhood ) { return $ current ; } } return null ; } | Search the tree for a neighborhood and return an array of samples and labels . |
13,545 | public function nearest ( array $ sample , int $ k = 1 ) : array { if ( $ k < 1 ) { throw new InvalidArgumentException ( 'The number of nearest' . " neighbors must be greater than 0, $k given." ) ; } $ neighborhood = $ this -> search ( $ sample ) ; if ( ! $ neighborhood ) { return [ [ ] , [ ] ] ; } $ distances = $ labels = [ ] ; $ visited = new SplObjectStorage ( ) ; $ stack = [ $ neighborhood ] ; while ( $ stack ) { $ current = array_pop ( $ stack ) ; if ( $ visited -> contains ( $ current ) ) { continue 1 ; } $ visited -> attach ( $ current ) ; $ parent = $ current -> parent ( ) ; if ( $ parent ) { $ stack [ ] = $ parent ; } if ( $ current instanceof Neighborhood ) { foreach ( $ current -> samples ( ) as $ neighbor ) { $ distances [ ] = $ this -> kernel -> compute ( $ sample , $ neighbor ) ; } $ labels = array_merge ( $ labels , $ current -> labels ( ) ) ; array_multisort ( $ distances , $ labels ) ; continue 1 ; } $ target = $ distances [ $ k - 1 ] ?? INF ; foreach ( $ current -> children ( ) as $ child ) { if ( $ visited -> contains ( $ child ) ) { continue 1 ; } if ( $ child instanceof Box ) { foreach ( $ child -> sides ( ) as $ side ) { $ distance = $ this -> kernel -> compute ( $ sample , $ side ) ; if ( $ distance < $ target ) { $ stack [ ] = $ child ; continue 2 ; } } } $ visited -> attach ( $ child ) ; } } $ distances = array_slice ( $ distances , 0 , $ k ) ; $ labels = array_slice ( $ labels , 0 , $ k ) ; return [ $ labels , $ distances ] ; } | Run a k nearest neighbors search of every neighborhood and return the labels and distances in a 2 - tuple . |
13,546 | public function range ( array $ sample , float $ radius ) : array { if ( $ radius <= 0. ) { throw new InvalidArgumentException ( 'Radius must be' . " greater than 0, $radius given." ) ; } $ samples = $ labels = $ distances = [ ] ; $ stack = [ $ this -> root ] ; while ( $ stack ) { $ current = array_pop ( $ stack ) ; if ( ! $ current instanceof BinaryNode ) { continue 1 ; } if ( $ current instanceof Cluster ) { foreach ( $ current -> samples ( ) as $ i => $ neighbor ) { $ distance = $ this -> kernel -> compute ( $ sample , $ neighbor ) ; if ( $ distance <= $ radius ) { $ samples [ ] = $ neighbor ; $ labels [ ] = $ current -> label ( $ i ) ; $ distances [ ] = $ distance ; } } continue 1 ; } foreach ( $ current -> children ( ) as $ child ) { if ( $ child instanceof Ball ) { $ distance = $ this -> kernel -> compute ( $ sample , $ child -> center ( ) ) ; if ( $ distance <= ( $ child -> radius ( ) + $ radius ) ) { $ stack [ ] = $ child ; } } } } return [ $ samples , $ labels , $ distances ] ; } | Run a range search over every cluster within radius and return the labels and distances in a 2 - tuple . |
13,547 | public static function determine ( $ data ) : int { switch ( gettype ( $ data ) ) { case 'string' : return self :: CATEGORICAL ; case 'double' : return self :: CONTINUOUS ; case 'integer' : return self :: CONTINUOUS ; case 'resource' : return self :: RESOURCE ; default : return self :: OTHER ; } } | Return the integer encoded data type . |
13,548 | public static function split ( Labeled $ dataset ) : self { $ columns = $ dataset -> columns ( ) ; $ variances = array_map ( [ Stats :: class , 'variance' ] , $ columns ) ; $ column = argmax ( $ variances ) ; $ value = Stats :: median ( $ columns [ $ column ] ) ; $ groups = $ dataset -> partition ( $ column , $ value ) ; $ min = $ max = [ ] ; foreach ( $ columns as $ values ) { $ min [ ] = min ( $ values ) ; $ max [ ] = max ( $ values ) ; } return new self ( $ column , $ value , $ groups , $ min , $ max ) ; } | Factory method to build a coordinate node from a labeled dataset using the column with the highest variance as the column for the split . |
13,549 | public static function array_replace_recursive ( $ array1 , $ array2 ) { if ( function_exists ( 'array_replace_recursive' ) ) { return array_replace_recursive ( $ array1 , $ array2 ) ; } foreach ( $ array2 as $ key => $ value ) { if ( is_array ( $ value ) ) { $ array1 [ $ key ] = self :: array_replace_recursive ( $ array1 [ $ key ] , $ value ) ; } else { $ array1 [ $ key ] = $ value ; } } return $ array1 ; } | Custom array_replace_recursive to be used if PHP < 5 . 3 Replaces elements from passed arrays into the first array recursively . |
13,550 | public function getTableLimit ( $ tableName ) { if ( empty ( $ this -> tableLimits [ $ tableName ] ) ) { return false ; } $ limit = $ this -> tableLimits [ $ tableName ] ; if ( ! is_numeric ( $ limit ) ) { return false ; } return $ limit ; } | Returns the LIMIT for the table . Must be numeric to be returned . |
13,551 | private function connect ( ) { try { switch ( $ this -> dbType ) { case 'sqlite' : $ this -> dbHandler = @ new PDO ( "sqlite:" . $ this -> dbName , null , null , $ this -> pdoSettings ) ; break ; case 'mysql' : case 'pgsql' : case 'dblib' : $ this -> dbHandler = @ new PDO ( $ this -> dsn , $ this -> user , $ this -> pass , $ this -> pdoSettings ) ; foreach ( $ this -> dumpSettings [ 'init_commands' ] as $ stmt ) { $ this -> dbHandler -> exec ( $ stmt ) ; } $ this -> version = $ this -> dbHandler -> getAttribute ( PDO :: ATTR_SERVER_VERSION ) ; break ; default : throw new Exception ( "Unsupported database type (" . $ this -> dbType . ")" ) ; } } catch ( PDOException $ e ) { throw new Exception ( "Connection to " . $ this -> dbType . " failed with message: " . $ e -> getMessage ( ) ) ; } if ( is_null ( $ this -> dbHandler ) ) { throw new Exception ( "Connection to " . $ this -> dbType . "failed" ) ; } $ this -> dbHandler -> setAttribute ( PDO :: ATTR_ORACLE_NULLS , PDO :: NULL_NATURAL ) ; $ this -> typeAdapter = TypeAdapterFactory :: create ( $ this -> dbType , $ this -> dbHandler , $ this -> dumpSettings ) ; } | Connect with PDO . |
13,552 | public function start ( $ filename = '' ) { if ( ! empty ( $ filename ) ) { $ this -> fileName = $ filename ; } $ this -> connect ( ) ; $ this -> compressManager -> open ( $ this -> fileName ) ; $ this -> compressManager -> write ( $ this -> getDumpFileHeader ( ) ) ; $ this -> compressManager -> write ( $ this -> typeAdapter -> backup_parameters ( ) ) ; if ( $ this -> dumpSettings [ 'databases' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> getDatabaseHeader ( $ this -> dbName ) ) ; if ( $ this -> dumpSettings [ 'add-drop-database' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> add_drop_database ( $ this -> dbName ) ) ; } } $ this -> getDatabaseStructureTables ( ) ; $ this -> getDatabaseStructureViews ( ) ; $ this -> getDatabaseStructureTriggers ( ) ; $ this -> getDatabaseStructureProcedures ( ) ; $ this -> getDatabaseStructureEvents ( ) ; if ( $ this -> dumpSettings [ 'databases' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> databases ( $ this -> dbName ) ) ; } if ( 0 < count ( $ this -> dumpSettings [ 'include-tables' ] ) ) { $ name = implode ( "," , $ this -> dumpSettings [ 'include-tables' ] ) ; throw new Exception ( "Table (" . $ name . ") not found in database" ) ; } $ this -> exportTables ( ) ; $ this -> exportTriggers ( ) ; $ this -> exportViews ( ) ; $ this -> exportProcedures ( ) ; $ this -> exportEvents ( ) ; $ this -> compressManager -> write ( $ this -> typeAdapter -> restore_parameters ( ) ) ; $ this -> compressManager -> write ( $ this -> getDumpFileFooter ( ) ) ; $ this -> compressManager -> close ( ) ; return ; } | Primary function triggers dumping . |
13,553 | private function getDumpFileHeader ( ) { $ header = '' ; if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ header = "-- mysqldump-php https://github.com/ifsnop/mysqldump-php" . PHP_EOL . "--" . PHP_EOL . "-- Host: {$this->host}\tDatabase: {$this->dbName}" . PHP_EOL . "-- ------------------------------------------------------" . PHP_EOL ; if ( ! empty ( $ this -> version ) ) { $ header .= "-- Server version \t" . $ this -> version . PHP_EOL ; } if ( ! $ this -> dumpSettings [ 'skip-dump-date' ] ) { $ header .= "-- Date: " . date ( 'r' ) . PHP_EOL . PHP_EOL ; } } return $ header ; } | Returns header for dump file . |
13,554 | private function getDumpFileFooter ( ) { $ footer = '' ; if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ footer .= '-- Dump completed' ; if ( ! $ this -> dumpSettings [ 'skip-dump-date' ] ) { $ footer .= ' on: ' . date ( 'r' ) ; } $ footer .= PHP_EOL ; } return $ footer ; } | Returns footer for dump file . |
13,555 | private function exportTables ( ) { foreach ( $ this -> tables as $ table ) { if ( $ this -> matches ( $ table , $ this -> dumpSettings [ 'exclude-tables' ] ) ) { continue ; } $ this -> getTableStructure ( $ table ) ; if ( false === $ this -> dumpSettings [ 'no-data' ] ) { $ this -> listValues ( $ table ) ; } elseif ( true === $ this -> dumpSettings [ 'no-data' ] || $ this -> matches ( $ table , $ this -> dumpSettings [ 'no-data' ] ) ) { continue ; } else { $ this -> listValues ( $ table ) ; } } } | Exports all the tables selected from database |
13,556 | private function exportViews ( ) { if ( false === $ this -> dumpSettings [ 'no-create-info' ] ) { foreach ( $ this -> views as $ view ) { if ( $ this -> matches ( $ view , $ this -> dumpSettings [ 'exclude-tables' ] ) ) { continue ; } $ this -> tableColumnTypes [ $ view ] = $ this -> getTableColumnTypes ( $ view ) ; $ this -> getViewStructureTable ( $ view ) ; } foreach ( $ this -> views as $ view ) { if ( $ this -> matches ( $ view , $ this -> dumpSettings [ 'exclude-tables' ] ) ) { continue ; } $ this -> getViewStructureView ( $ view ) ; } } } | Exports all the views found in database |
13,557 | private function getTableStructure ( $ tableName ) { if ( ! $ this -> dumpSettings [ 'no-create-info' ] ) { $ ret = '' ; if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ ret = "--" . PHP_EOL . "-- Table structure for table `$tableName`" . PHP_EOL . "--" . PHP_EOL . PHP_EOL ; } $ stmt = $ this -> typeAdapter -> show_create_table ( $ tableName ) ; foreach ( $ this -> dbHandler -> query ( $ stmt ) as $ r ) { $ this -> compressManager -> write ( $ ret ) ; if ( $ this -> dumpSettings [ 'add-drop-table' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> drop_table ( $ tableName ) ) ; } $ this -> compressManager -> write ( $ this -> typeAdapter -> create_table ( $ r ) ) ; break ; } } $ this -> tableColumnTypes [ $ tableName ] = $ this -> getTableColumnTypes ( $ tableName ) ; return ; } | Table structure extractor |
13,558 | private function getTableColumnTypes ( $ tableName ) { $ columnTypes = array ( ) ; $ columns = $ this -> dbHandler -> query ( $ this -> typeAdapter -> show_columns ( $ tableName ) ) ; $ columns -> setFetchMode ( PDO :: FETCH_ASSOC ) ; foreach ( $ columns as $ key => $ col ) { $ types = $ this -> typeAdapter -> parseColumnType ( $ col ) ; $ columnTypes [ $ col [ 'Field' ] ] = array ( 'is_numeric' => $ types [ 'is_numeric' ] , 'is_blob' => $ types [ 'is_blob' ] , 'type' => $ types [ 'type' ] , 'type_sql' => $ col [ 'Type' ] , 'is_virtual' => $ types [ 'is_virtual' ] ) ; } return $ columnTypes ; } | Store column types to create data dumps and for Stand - In tables |
13,559 | public function createStandInTable ( $ viewName ) { $ ret = array ( ) ; foreach ( $ this -> tableColumnTypes [ $ viewName ] as $ k => $ v ) { $ ret [ ] = "`${k}` ${v['type_sql']}" ; } $ ret = implode ( PHP_EOL . "," , $ ret ) ; $ ret = "CREATE TABLE IF NOT EXISTS `$viewName` (" . PHP_EOL . $ ret . PHP_EOL . ");" . PHP_EOL ; return $ ret ; } | Write a create table statement for the table Stand - In show create table would return a create algorithm when used on a view |
13,560 | private function getViewStructureView ( $ viewName ) { if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ ret = "--" . PHP_EOL . "-- View structure for view `${viewName}`" . PHP_EOL . "--" . PHP_EOL . PHP_EOL ; $ this -> compressManager -> write ( $ ret ) ; } $ stmt = $ this -> typeAdapter -> show_create_view ( $ viewName ) ; foreach ( $ this -> dbHandler -> query ( $ stmt ) as $ r ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> drop_view ( $ viewName ) ) ; $ this -> compressManager -> write ( $ this -> typeAdapter -> create_view ( $ r ) ) ; break ; } } | View structure extractor create view |
13,561 | private function getTriggerStructure ( $ triggerName ) { $ stmt = $ this -> typeAdapter -> show_create_trigger ( $ triggerName ) ; foreach ( $ this -> dbHandler -> query ( $ stmt ) as $ r ) { if ( $ this -> dumpSettings [ 'add-drop-trigger' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> add_drop_trigger ( $ triggerName ) ) ; } $ this -> compressManager -> write ( $ this -> typeAdapter -> create_trigger ( $ r ) ) ; return ; } } | Trigger structure extractor |
13,562 | private function getProcedureStructure ( $ procedureName ) { if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ ret = "--" . PHP_EOL . "-- Dumping routines for database '" . $ this -> dbName . "'" . PHP_EOL . "--" . PHP_EOL . PHP_EOL ; $ this -> compressManager -> write ( $ ret ) ; } $ stmt = $ this -> typeAdapter -> show_create_procedure ( $ procedureName ) ; foreach ( $ this -> dbHandler -> query ( $ stmt ) as $ r ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> create_procedure ( $ r ) ) ; return ; } } | Procedure structure extractor |
13,563 | private function getEventStructure ( $ eventName ) { if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ ret = "--" . PHP_EOL . "-- Dumping events for database '" . $ this -> dbName . "'" . PHP_EOL . "--" . PHP_EOL . PHP_EOL ; $ this -> compressManager -> write ( $ ret ) ; } $ stmt = $ this -> typeAdapter -> show_create_event ( $ eventName ) ; foreach ( $ this -> dbHandler -> query ( $ stmt ) as $ r ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> create_event ( $ r ) ) ; return ; } } | Event structure extractor |
13,564 | private function prepareColumnValues ( $ tableName , $ row ) { $ ret = array ( ) ; $ columnTypes = $ this -> tableColumnTypes [ $ tableName ] ; foreach ( $ row as $ colName => $ colValue ) { $ colValue = $ this -> hookTransformColumnValue ( $ tableName , $ colName , $ colValue , $ row ) ; $ ret [ ] = $ this -> escape ( $ colValue , $ columnTypes [ $ colName ] ) ; } return $ ret ; } | Prepare values for output |
13,565 | private function escape ( $ colValue , $ colType ) { if ( is_null ( $ colValue ) ) { return "NULL" ; } elseif ( $ this -> dumpSettings [ 'hex-blob' ] && $ colType [ 'is_blob' ] ) { if ( $ colType [ 'type' ] == 'bit' || ! empty ( $ colValue ) ) { return "0x${colValue}" ; } else { return "''" ; } } elseif ( $ colType [ 'is_numeric' ] ) { return $ colValue ; } return $ this -> dbHandler -> quote ( $ colValue ) ; } | Escape values with quotes when needed |
13,566 | protected function hookTransformColumnValue ( $ tableName , $ colName , $ colValue , $ row ) { if ( ! $ this -> transformColumnValueCallable ) { return $ colValue ; } return call_user_func_array ( $ this -> transformColumnValueCallable , array ( $ tableName , $ colName , $ colValue , $ row ) ) ; } | Give extending classes an opportunity to transform column values |
13,567 | private function listValues ( $ tableName ) { $ this -> prepareListValues ( $ tableName ) ; $ onlyOnce = true ; $ lineSize = 0 ; $ colStmt = $ this -> getColumnStmt ( $ tableName ) ; if ( $ this -> dumpSettings [ 'complete-insert' ] ) { $ colNames = $ this -> getColumnNames ( $ tableName ) ; } $ stmt = "SELECT " . implode ( "," , $ colStmt ) . " FROM `$tableName`" ; $ condition = $ this -> getTableWhere ( $ tableName ) ; if ( $ condition ) { $ stmt .= " WHERE {$condition}" ; } $ limit = $ this -> getTableLimit ( $ tableName ) ; if ( $ limit ) { $ stmt .= " LIMIT {$limit}" ; } $ resultSet = $ this -> dbHandler -> query ( $ stmt ) ; $ resultSet -> setFetchMode ( PDO :: FETCH_ASSOC ) ; $ ignore = $ this -> dumpSettings [ 'insert-ignore' ] ? ' IGNORE' : '' ; $ count = 0 ; foreach ( $ resultSet as $ row ) { $ count ++ ; $ vals = $ this -> prepareColumnValues ( $ tableName , $ row ) ; if ( $ onlyOnce || ! $ this -> dumpSettings [ 'extended-insert' ] ) { if ( $ this -> dumpSettings [ 'complete-insert' ] ) { $ lineSize += $ this -> compressManager -> write ( "INSERT$ignore INTO `$tableName` (" . implode ( ", " , $ colNames ) . ") VALUES (" . implode ( "," , $ vals ) . ")" ) ; } else { $ lineSize += $ this -> compressManager -> write ( "INSERT$ignore INTO `$tableName` VALUES (" . implode ( "," , $ vals ) . ")" ) ; } $ onlyOnce = false ; } else { $ lineSize += $ this -> compressManager -> write ( ",(" . implode ( "," , $ vals ) . ")" ) ; } if ( ( $ lineSize > $ this -> dumpSettings [ 'net_buffer_length' ] ) || ! $ this -> dumpSettings [ 'extended-insert' ] ) { $ onlyOnce = true ; $ lineSize = $ this -> compressManager -> write ( ";" . PHP_EOL ) ; } } $ resultSet -> closeCursor ( ) ; if ( ! $ onlyOnce ) { $ this -> compressManager -> write ( ";" . PHP_EOL ) ; } $ this -> endListValues ( $ tableName , $ count ) ; } | Table rows extractor |
13,568 | public function prepareListValues ( $ tableName ) { if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ this -> compressManager -> write ( "--" . PHP_EOL . "-- Dumping data for table `$tableName`" . PHP_EOL . "--" . PHP_EOL . PHP_EOL ) ; } if ( $ this -> dumpSettings [ 'single-transaction' ] ) { $ this -> dbHandler -> exec ( $ this -> typeAdapter -> setup_transaction ( ) ) ; $ this -> dbHandler -> exec ( $ this -> typeAdapter -> start_transaction ( ) ) ; } if ( $ this -> dumpSettings [ 'lock-tables' ] ) { $ this -> typeAdapter -> lock_table ( $ tableName ) ; } if ( $ this -> dumpSettings [ 'add-locks' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> start_add_lock_table ( $ tableName ) ) ; } if ( $ this -> dumpSettings [ 'disable-keys' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> start_add_disable_keys ( $ tableName ) ) ; } if ( $ this -> dumpSettings [ 'no-autocommit' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> start_disable_autocommit ( ) ) ; } return ; } | Table rows extractor append information prior to dump |
13,569 | public function endListValues ( $ tableName , $ count = 0 ) { if ( $ this -> dumpSettings [ 'disable-keys' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> end_add_disable_keys ( $ tableName ) ) ; } if ( $ this -> dumpSettings [ 'add-locks' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> end_add_lock_table ( $ tableName ) ) ; } if ( $ this -> dumpSettings [ 'single-transaction' ] ) { $ this -> dbHandler -> exec ( $ this -> typeAdapter -> commit_transaction ( ) ) ; } if ( $ this -> dumpSettings [ 'lock-tables' ] ) { $ this -> typeAdapter -> unlock_table ( $ tableName ) ; } if ( $ this -> dumpSettings [ 'no-autocommit' ] ) { $ this -> compressManager -> write ( $ this -> typeAdapter -> end_disable_autocommit ( ) ) ; } $ this -> compressManager -> write ( PHP_EOL ) ; if ( ! $ this -> dumpSettings [ 'skip-comments' ] ) { $ this -> compressManager -> write ( "-- Dumped table `" . $ tableName . "` with $count row(s)" . PHP_EOL . '--' . PHP_EOL . PHP_EOL ) ; } return ; } | Table rows extractor close locks and commits after dump |
13,570 | public function getColumnStmt ( $ tableName ) { $ colStmt = array ( ) ; foreach ( $ this -> tableColumnTypes [ $ tableName ] as $ colName => $ colType ) { if ( $ colType [ 'type' ] == 'bit' && $ this -> dumpSettings [ 'hex-blob' ] ) { $ colStmt [ ] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`" ; } elseif ( $ colType [ 'is_blob' ] && $ this -> dumpSettings [ 'hex-blob' ] ) { $ colStmt [ ] = "HEX(`${colName}`) AS `${colName}`" ; } elseif ( $ colType [ 'is_virtual' ] ) { $ this -> dumpSettings [ 'complete-insert' ] = true ; continue ; } else { $ colStmt [ ] = "`${colName}`" ; } } return $ colStmt ; } | Build SQL List of all columns on current table which will be used for selecting |
13,571 | public function getColumnNames ( $ tableName ) { $ colNames = array ( ) ; foreach ( $ this -> tableColumnTypes [ $ tableName ] as $ colName => $ colType ) { if ( $ colType [ 'is_virtual' ] ) { $ this -> dumpSettings [ 'complete-insert' ] = true ; continue ; } else { $ colNames [ ] = "`${colName}`" ; } } return $ colNames ; } | Build SQL List of all columns on current table which will be used for inserting |
13,572 | public function parseColumnType ( $ colType ) { $ colInfo = array ( ) ; $ colParts = explode ( " " , $ colType [ 'Type' ] ) ; if ( $ fparen = strpos ( $ colParts [ 0 ] , "(" ) ) { $ colInfo [ 'type' ] = substr ( $ colParts [ 0 ] , 0 , $ fparen ) ; $ colInfo [ 'length' ] = str_replace ( ")" , "" , substr ( $ colParts [ 0 ] , $ fparen + 1 ) ) ; $ colInfo [ 'attributes' ] = isset ( $ colParts [ 1 ] ) ? $ colParts [ 1 ] : null ; } else { $ colInfo [ 'type' ] = $ colParts [ 0 ] ; } $ colInfo [ 'is_numeric' ] = in_array ( $ colInfo [ 'type' ] , $ this -> mysqlTypes [ 'numerical' ] ) ; $ colInfo [ 'is_blob' ] = in_array ( $ colInfo [ 'type' ] , $ this -> mysqlTypes [ 'blob' ] ) ; $ colInfo [ 'is_virtual' ] = strpos ( $ colType [ 'Extra' ] , "VIRTUAL GENERATED" ) !== false || strpos ( $ colType [ 'Extra' ] , "STORED GENERATED" ) !== false ; return $ colInfo ; } | Decode column metadata and fill info structure . type is_numeric and is_blob will always be available . |
13,573 | protected function setTrustedProxyIpAddresses ( Request $ request ) { $ trustedIps = $ this -> proxies ? : $ this -> config -> get ( 'trustedproxy.proxies' ) ; if ( $ trustedIps === '*' || $ trustedIps === '**' ) { return $ this -> setTrustedProxyIpAddressesToTheCallingIp ( $ request ) ; } $ trustedIps = is_string ( $ trustedIps ) ? array_map ( 'trim' , explode ( ',' , $ trustedIps ) ) : $ trustedIps ; if ( is_array ( $ trustedIps ) ) { return $ this -> setTrustedProxyIpAddressesToSpecificIps ( $ request , $ trustedIps ) ; } } | Sets the trusted proxies on the request to the value of trustedproxy . proxies |
13,574 | private function setTrustedProxyIpAddressesToTheCallingIp ( Request $ request ) { $ request -> setTrustedProxies ( [ $ request -> server -> get ( 'REMOTE_ADDR' ) ] , $ this -> getTrustedHeaderNames ( ) ) ; } | Set the trusted proxy to be the IP address calling this servers |
13,575 | public function setSchema ( $ schema ) { $ this -> schema = $ schema ; $ sessionVars = [ 'CURRENT_SCHEMA' => $ schema , ] ; return $ this -> setSessionVars ( $ sessionVars ) ; } | Set current schema . |
13,576 | public function setSessionVars ( array $ sessionVars ) { $ vars = [ ] ; foreach ( $ sessionVars as $ option => $ value ) { if ( strtoupper ( $ option ) == 'CURRENT_SCHEMA' || strtoupper ( $ option ) == 'EDITION' ) { $ vars [ ] = "$option = $value" ; } else { $ vars [ ] = "$option = '$value'" ; } } if ( $ vars ) { $ sql = 'ALTER SESSION SET ' . implode ( ' ' , $ vars ) ; $ this -> statement ( $ sql ) ; } return $ this ; } | Update oracle session variables . |
13,577 | public function getDoctrineConnection ( ) { if ( is_null ( $ this -> doctrineConnection ) ) { $ data = [ 'pdo' => $ this -> getPdo ( ) , 'user' => $ this -> getConfig ( 'username' ) ] ; $ this -> doctrineConnection = new DoctrineConnection ( $ data , $ this -> getDoctrineDriver ( ) ) ; } return $ this -> doctrineConnection ; } | Get doctrine connection . |
13,578 | public function createSqlFromProcedure ( $ procedureName , array $ bindings , $ cursor = false ) { $ paramsString = implode ( ',' , array_map ( function ( $ param ) { return ':' . $ param ; } , array_keys ( $ bindings ) ) ) ; $ prefix = count ( $ bindings ) ? ',' : '' ; $ cursor = $ cursor ? $ prefix . $ cursor : null ; return sprintf ( 'begin %s(%s%s); end;' , $ procedureName , $ paramsString , $ cursor ) ; } | Creates sql command to run a procedure with bindings . |
13,579 | public function createStatementFromProcedure ( $ procedureName , array $ bindings , $ cursorName = false ) { $ sql = $ this -> createSqlFromProcedure ( $ procedureName , $ bindings , $ cursorName ) ; return $ this -> getPdo ( ) -> prepare ( $ sql ) ; } | Creates statement from procedure . |
13,580 | public function createStatementFromFunction ( $ functionName , array $ bindings ) { $ bindings = $ bindings ? ':' . implode ( ', :' , array_keys ( $ bindings ) ) : '' ; $ sql = sprintf ( 'begin :result := %s(%s); end;' , $ functionName , $ bindings ) ; return $ this -> getPdo ( ) -> prepare ( $ sql ) ; } | Create statement from function . |
13,581 | public function addBindingsToStatement ( PDOStatement $ stmt , array $ bindings ) { foreach ( $ bindings as $ key => & $ binding ) { $ value = & $ binding ; $ type = PDO :: PARAM_STR ; $ length = - 1 ; if ( is_array ( $ binding ) ) { $ value = & $ binding [ 'value' ] ; $ type = array_key_exists ( 'type' , $ binding ) ? $ binding [ 'type' ] : PDO :: PARAM_STR ; $ length = array_key_exists ( 'length' , $ binding ) ? $ binding [ 'length' ] : - 1 ; } $ stmt -> bindParam ( ':' . $ key , $ value , $ type , $ length ) ; } return $ stmt ; } | Add bindings to statement . |
13,582 | protected function causedByLostConnection ( Throwable $ e ) { if ( parent :: causedByLostConnection ( $ e ) ) { return true ; } $ lostConnectionErrors = [ 'ORA-03113' , 'ORA-03114' , 'ORA-03135' , 'ORA-12170' , 'ORA-12537' , 'ORA-27146' , 'ORA-25408' , 'ORA-56600' , ] ; $ additionalErrors = null ; $ options = isset ( $ this -> config [ 'options' ] ) ? $ this -> config [ 'options' ] : [ ] ; if ( array_key_exists ( static :: RECONNECT_ERRORS , $ options ) ) { $ additionalErrors = $ this -> config [ 'options' ] [ static :: RECONNECT_ERRORS ] ; } if ( is_array ( $ additionalErrors ) ) { $ lostConnectionErrors = array_merge ( $ lostConnectionErrors , $ this -> config [ 'options' ] [ static :: RECONNECT_ERRORS ] ) ; } return Str :: contains ( $ e -> getMessage ( ) , $ lostConnectionErrors ) ; } | Determine if the given exception was caused by a lost connection . |
13,583 | protected function extractBinaries ( & $ attributes ) { $ binaries = [ ] ; if ( $ this -> checkBinary ( $ attributes ) && $ this -> getConnection ( ) instanceof Oci8Connection ) { foreach ( $ attributes as $ key => $ value ) { if ( in_array ( $ key , $ this -> binaries ) ) { $ binaries [ $ key ] = $ value ; unset ( $ attributes [ $ key ] ) ; } } } return $ this -> binaryFields = $ binaries ; } | Extract binary fields from given attributes . |
13,584 | protected function checkBinary ( array $ attributes ) { foreach ( $ attributes as $ key => $ value ) { if ( in_array ( $ key , $ this -> binaries ) ) { return true ; } } return false ; } | Check if attributes contains binary field . |
13,585 | public function create ( $ name , $ start = 1 , $ nocache = false , $ min = 1 , $ max = false , $ increment = 1 ) { if ( ! $ name ) { return false ; } if ( $ this -> connection -> getConfig ( 'prefix_schema' ) ) { $ name = $ this -> connection -> getConfig ( 'prefix_schema' ) . '.' . $ name ; } $ nocache = $ nocache ? 'nocache' : '' ; $ max = $ max ? " maxvalue {$max}" : '' ; $ sequence_stmt = "create sequence {$name} minvalue {$min} {$max} start with {$start} increment by {$increment} {$nocache}" ; return $ this -> connection -> statement ( $ sequence_stmt ) ; } | function to create oracle sequence . |
13,586 | public function drop ( $ name ) { if ( ! $ name || ! $ this -> exists ( $ name ) ) { return false ; } return $ this -> connection -> statement ( " declare e exception; pragma exception_init(e,-02289); begin execute immediate 'drop sequence {$name}'; exception when e then null; end;" ) ; } | function to safely drop sequence db object . |
13,587 | public function lastInsertId ( $ name ) { if ( ! $ name || ! $ this -> exists ( $ name ) ) { return 0 ; } return $ this -> connection -> selectOne ( "select {$name}.currval as id from dual" ) -> id ; } | function to get oracle sequence last inserted id . |
13,588 | public function table ( $ table , Closure $ callback ) { $ blueprint = $ this -> createBlueprint ( $ table ) ; $ callback ( $ blueprint ) ; foreach ( $ blueprint -> getCommands ( ) as $ command ) { if ( $ command -> get ( 'name' ) == 'drop' ) { $ this -> helper -> dropAutoIncrementObjects ( $ table ) ; } } $ this -> build ( $ blueprint ) ; $ this -> comment -> setComments ( $ blueprint ) ; } | Changes an existing table on the schema . |
13,589 | public function setComments ( OracleBlueprint $ blueprint ) { $ this -> commentTable ( $ blueprint ) ; $ this -> fluentComments ( $ blueprint ) ; $ this -> commentColumns ( $ blueprint ) ; } | Set table and column comments . |
13,590 | private function commentColumn ( $ table , $ column , $ comment ) { $ table = $ this -> wrapValue ( $ table ) ; $ table = $ this -> connection -> getTablePrefix ( ) . $ table ; $ column = $ this -> wrapValue ( $ column ) ; $ this -> connection -> statement ( "comment on column {$table}.{$column} is '{$comment}'" ) ; } | Run the comment on column statement . |
13,591 | public function updateLob ( array $ values , array $ binaries , $ sequence = 'id' ) { $ bindings = array_values ( array_merge ( $ values , $ this -> getBindings ( ) ) ) ; $ grammar = $ this -> grammar ; $ sql = $ grammar -> compileUpdateLob ( $ this , $ values , $ binaries , $ sequence ) ; $ values = $ this -> cleanBindings ( $ bindings ) ; $ binaries = $ this -> cleanBindings ( $ binaries ) ; $ processor = $ this -> processor ; return $ processor -> saveLob ( $ this , $ sql , $ values , $ binaries ) ; } | Update a new record with blob field . |
13,592 | public function whereIn ( $ column , $ values , $ boolean = 'and' , $ not = false ) { $ type = $ not ? 'NotIn' : 'In' ; if ( $ values instanceof Arrayable ) { $ values = $ values -> toArray ( ) ; } if ( is_array ( $ values ) && count ( $ values ) > 1000 ) { $ chunks = array_chunk ( $ values , 1000 ) ; return $ this -> where ( function ( $ query ) use ( $ column , $ chunks , $ type , $ not ) { foreach ( $ chunks as $ ch ) { $ sqlClause = $ not ? 'where' . $ type : 'orWhere' . $ type ; $ query -> { $ sqlClause } ( $ column , $ ch ) ; } } , null , null , $ boolean ) ; } return parent :: whereIn ( $ column , $ values , $ boolean , $ not ) ; } | Add a where in clause to the query . Split one WHERE IN clause into multiple clauses each with up to 1000 expressions to avoid ORA - 01795 . |
13,593 | public function compileInsertLob ( Builder $ query , $ values , $ binaries , $ sequence = 'id' ) { if ( empty ( $ sequence ) ) { $ sequence = 'id' ; } $ table = $ this -> wrapTable ( $ query -> from ) ; if ( ! is_array ( reset ( $ values ) ) ) { $ values = [ $ values ] ; } if ( ! is_array ( reset ( $ binaries ) ) ) { $ binaries = [ $ binaries ] ; } $ columns = $ this -> columnize ( array_keys ( reset ( $ values ) ) ) ; $ binaryColumns = $ this -> columnize ( array_keys ( reset ( $ binaries ) ) ) ; $ columns .= ( empty ( $ columns ) ? '' : ', ' ) . $ binaryColumns ; $ parameters = $ this -> parameterize ( reset ( $ values ) ) ; $ binaryParameters = $ this -> parameterize ( reset ( $ binaries ) ) ; $ value = array_fill ( 0 , count ( $ values ) , "$parameters" ) ; $ binaryValue = array_fill ( 0 , count ( $ binaries ) , str_replace ( '?' , 'EMPTY_BLOB()' , $ binaryParameters ) ) ; $ value = array_merge ( $ value , $ binaryValue ) ; $ parameters = implode ( ', ' , array_filter ( $ value ) ) ; return "insert into $table ($columns) values ($parameters) returning " . $ binaryColumns . ', ' . $ this -> wrap ( $ sequence ) . ' into ' . $ binaryParameters . ', ?' ; } | Compile an insert with blob field statement into SQL . |
13,594 | public function createAutoIncrementObjects ( Blueprint $ blueprint , $ table ) { $ column = $ this -> getQualifiedAutoIncrementColumn ( $ blueprint ) ; if ( is_null ( $ column ) ) { return ; } $ col = $ column -> name ; $ start = isset ( $ column -> start ) ? $ column -> start : 1 ; $ prefix = $ this -> connection -> getTablePrefix ( ) ; $ sequenceName = $ this -> createObjectName ( $ prefix , $ table , $ col , 'seq' ) ; $ this -> sequence -> create ( $ sequenceName , $ start , $ column -> nocache ) ; $ triggerName = $ this -> createObjectName ( $ prefix , $ table , $ col , 'trg' ) ; $ this -> trigger -> autoIncrement ( $ prefix . $ table , $ col , $ triggerName , $ sequenceName ) ; } | create sequence and trigger for autoIncrement support . |
13,595 | public function getQualifiedAutoIncrementColumn ( Blueprint $ blueprint ) { $ columns = $ blueprint -> getColumns ( ) ; foreach ( $ columns as $ column ) { if ( $ column -> autoIncrement ) { return $ column ; } } } | Get qualified autoincrement column . |
13,596 | private function createObjectName ( $ prefix , $ table , $ col , $ type ) { return substr ( $ prefix . $ table . '_' . $ col . '_' . $ type , 0 , 30 ) ; } | Create an object name that limits to 30 chars . |
13,597 | public function dropAutoIncrementObjects ( $ table ) { $ prefix = $ this -> connection -> getTablePrefix ( ) ; $ col = $ this -> getPrimaryKey ( $ prefix . $ table ) ; if ( isset ( $ col ) && ! empty ( $ col ) ) { $ sequenceName = $ this -> createObjectName ( $ prefix , $ table , $ col , 'seq' ) ; $ this -> sequence -> drop ( $ sequenceName ) ; $ triggerName = $ this -> createObjectName ( $ prefix , $ table , $ col , 'trg' ) ; $ this -> trigger -> drop ( $ triggerName ) ; } } | Drop sequence and triggers if exists autoincrement objects . |
13,598 | public function getPrimaryKey ( $ table ) { if ( ! $ table ) { return '' ; } $ sql = "SELECT cols.column_name FROM all_constraints cons, all_cons_columns cols WHERE upper(cols.table_name) = upper('{$table}') AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner AND cols.position = 1 AND cons.owner = (select user from dual) ORDER BY cols.table_name, cols.position" ; $ data = $ this -> connection -> selectOne ( $ sql ) ; if ( $ data ) { return $ data -> column_name ; } return '' ; } | Get table s primary key . |
13,599 | public function boot ( ) { $ this -> publishes ( [ __DIR__ . '/../config/oracle.php' => config_path ( 'oracle.php' ) , ] , 'oracle' ) ; Auth :: provider ( 'oracle' , function ( $ app , array $ config ) { return new OracleUserProvider ( $ app [ 'hash' ] , $ config [ 'model' ] ) ; } ) ; } | Boot Oci8 Provider . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.