Paul S. Tuon
`~The engine of your inginuity is limited only to your imagination!!!~`
UX Engineer
Minneapolis, MN (US)
Attended: University of
Minnesota (Twin Cities)
Majored: Economics/Computer
Science
Expertise:
Programming:
I am a Software
Engineer/Economist--
specializing in all kinds of
software applications
development.
My field of expertise: Java,
Delphi, C#, Python, PHP,
Node.js, JavaScript, jQuery,
Ajax, MySQL, PDO, and,
of course, CSS.
I enjoy programming and
it feels like a hobby to me. It
probably falls in both categories
of programming and hobbies!!!
Hobbies:
Social media: Love going
online and interacting with
total strangers on social
medias! It's fun!!
And it's so 21st century and
beyond!!! Hardly a bane on
my existence!
Sports: Enjoy watching/playing
soccer, Karate, and the
World Cup. And I am a
season-ticket holder of
the Minnesota United
Prefessional Soccer Team.
A Lifelong Dream:
Going as far back as I could
remember (even being just a
child), I have always
dreamed of owning my own
company and taking it to the
public. It is a lifelong dream
that is still with me today!
I can dream, too; can't I?
I can say this:
My will, determination, and
resolve are unshaken!!!
Never have been and
never will be!!!
search .....
Article Date: August 9, 2014
By Paul S. Tuon
Strike | Symbol | Last | Chg % | Bid | Ask | Volume | Open Interest |
$15.00 | T100918C00015000 | 7.45 | 0.23 | 7.40 | 7.50 | 45 | 175 |
$25.00 | T100918C00025000 | 3.45 | 0.04 | 3.40 | 3.50 | 106 | 694 |
Call Options Quotes |
For AT & T, Inc (Symbol: T): 07-30-2010: $25.94 |
Expire at close on Friday September 17, 2010 |
Strike | Symbol | Last | Chg % | Bid | Ask | Volume | Open Interest |
$23.00 | T100918C00023000 | 2.94 | 0.23 | 3.00 | 3.05 | 45 | 175 |
$24.00 | T100918C00024000 | 2.15 | 0.04 | 2.10 | 2.13 | 106 | 694 |
$25.00 | T100918C00025000 | 1.31 | 0.05 | 1.27 | 1.28 | 138 | 2,924 |
$26.00 | T100918C00026000 | 0.63 | 0.00 | 0.60 | 0.61 | 322 | 11,331 |
$27.00 | T100918C00024000 | 0.21 | 0.02 | 0.19 | 0.21 | 466 | 3,637 |
$28.00 | T100918C00024000 | 0.06 | 0.01 | 0.04 | 0.06 | 120 | 808 |
$29.00 | T100918C00029000 | 0.02 | 0.00 | N/A | 0.02 | 10 | 20 |
$30.00 | T100918C00024000 | 2.15 | 0.04 | 2.10 | 2.13 | 106 | 694 |
Put Options Chain Quotes |
For AT & T, Inc (Symbol: T): 07-30-2010: Price $25.94 |
Expire at close on Friday September 17, 2010 |
Strike | Symbol | Last | Chg % | Bid | Ask | Volume | Open Interest |
$23.00 | T100918P00023000 | 0.05 | 0.00 | 0.09 | 0.11 | 6 | 1,651 |
$24.00 | T100918P00024000 | 0.15 | 0.01 | 0.16 | 0.18 | 131 | 1,025 |
$25.00 | T100918P00025000 | 0.31 | 0.00 | 0.32 | 0.34 | 76 | 3,194 |
$26.00 | T100918P00026000 | 0.63 | 0.03 | 0.65 | 0.67 | 283 | 1,634 |
$27.00 | T100918P00027000 | 1.24 | 0.02 | 1.24 | 1.27 | 273 | 1,774 |
$28.00 | T100918P00028000 | 2.05 | 0.03 | 2.09 | 2.11 | 78 | 439 |
$29.00 | T100918P00029000 | 3.15 | 0.15 | 3.05 | 3.10 | 89 | 18 |
$30.00 | T100918P00030000 | 4.15 | 0.15 | 3.95 | 4.10 | 124 | 1 |
<?php /** * file: neuralnetwork.php * * Simple MLP (Multi-layers Perceptron) Neural Network */ class NeuralNetwork { private $input = array(); // input information private $hidden_layer = array(); // layers in the network /** * Constructor setting up layers * A calling program needs to create an instance of this class and passing * input layer, hidden layers, and output layer. * * Usage: * * $net = new NeuralNetwork([3, 25, 25, 1 ]); * * After that, we need to call FeedForward() and BackPropagation(). * in this example, we pass the known value of XOR function as an array: * * $net.FeedForward([ 0, 0, 0 ]); * $net.BackPropagation([ 0 ]); * * we can train some more: * * $net.FeedForward([ 0, 0, 1 ]); * $net.BackPropagation([ 1 ]); * * $net.FeedForward([ 0, 1, 0 ]); * $net.BackPropagation([ 1 ]); * * $net.FeedForward([ 0, 1, 1 ]); * $net.BackPropagation([ 0 ]); * * $net.FeedForward([ 1, 0, 0 ]); * $net.BackPropagation([ 1 ]); * * $net.FeedForward([ 1, 0, 1 ]); * $net.BackPropagation([ 0 ]); * * $net.FeedForward([ 1, 1, 0 ]); * $net.BackPropagation([ 0 ]); * * $net.FeedForward([ 1, 1, 1 ]); * $net.BackPropagation([ 1 ]); * * @param $input Layers of this network */ // notice the type-hint which indicates $input is an array variable public __construct(array $input) { // initialize input layers that were passed in by the calling program for ($i = 0; $i < sizeof($input); $i++) { // $input argument contains: 3 inputs, 25 neurons in hidden layer 1, // 25 neurons in hidden layer 2, 1 output // store each argument in this class' array variable $input $this->input[$i] = $input[$i]; } /* the for() loop above result in the following initialization: $this->input[0] = 3; $this->input[1] = 25; $this->input[2] = 25; $this->input[3] = 1; */ // creates a bunch of neural network hidden layers, for ($i = 0; $i < count($input) - 1; $i++) { // for each argument in [count($input)], create a Layer object passing // this class' array variable $input // in other words, create one Layer object for the input layer (index 0), // one for the first hidden layer (index 1), // one for the 2nd hidden layer (index 2), // leaving the output (index 3) uneffected. // follow the for() loop iteration to make sense of all this: $this->hidden_layer[i] = new Layer($this->input[$i], $this->input[$i + 1]); } /* the for() loop above result in the following initialization: // input = 3, hidden layer = 25 => (3, 25) $this->hidden_layer[0] = new Layer($this->input[0], $this->input[0 + 1]); // hiddenl = 25, hiddenl = 25 => (25, 25) $this->hidden_layer[1] = new Layer($this->input[1], $this->input[1 + 1]); // hiddenl = 25, hidden layer = 25 => (25, 1) $this->hidden_layer[2] = new Layer($this->input[2], $this->input[2 + 1]); // so this last index is not iterated because of count($input) - 1, which is // when $i = 3. 3 < 3 is false, // so this last line is not executed at last iteration // hidden l = 25, hidden layer 2 = 25 => (1, null) // again, follow the for() loop iteration to make sense of all this: $this->hidden_layer[3] = new Layer($this->input[3], $this->input[3 + 1]); */ } /** * A feedforward for this network * this function is called by the training app to kickstart the process: * * // notice the argument is passed in as an array and the array * can contain limitless size. here we pass in five layers. * notice that we have two hidden layers 25 neurons each. * if we have more hidden layers we can pass in more arguments seperate each * argument with a comma, e.g.: 3 inputs, five hidden layers: 25, 25, 8, 4, 17 * one output: 1 * * for example: * new NeuralNetwork([3, 25, 25, 8, 4, 17, 1 ]) * * Usage: * * $net = new NeuralNetwork([3, 25, 25, 1 ]); * calling FeedForward() passing the known answer. in this example, we're * calling FeedForward() and passing the known value as an array. in this case, * we pass an XOR function values: 0, 0, 0 * $net.FeedForward([ 0, 0, 0 ]); * so all applications need to call this so called "train" function to start the process * some programmers like to name this function as "train()" but I like "FeedForward()" * @param $input inputs to be feed forward */ // this function acts as a train() function to train or jumpstart the process public FeedForward($input) { // feed forward. notice the call to FeedForward--it's not a recursive call, but // rather, it is actually calling Layer's FeedForward($input) because // $this->hidden_layer[0] refers to Layer's object $this->hidden_layer[0]->FeedForward($input); // so after the above call to FeedForward($input), // Layer's $output should contains a weighted sum of the input for ($i = 1; $i < count($this->hidden_layer); $i++) { // start with the 2nd Layer object instance (index 1) and call // Layer's FeedForward() passing the output of layer 0 $this->hidden_layer[$i]->FeedForward($this->hidden_layer[$i - 1]->output); } // return the output of the last layer return $this->hidden_layer[$i - 1]->output; // $i = 3 } /** * High level back propagation * Note: It is expected the one feed forward was done before this back prop. * @param $expected The expected output form the last feedforward */ // notice that $expected is the known answer passed in by calling code public BackPropagation($expected) { // run over all layers backwards. notice that the for() loop starts from // the total number of hidden layers and iterated downward to 0 for ($i = sizeof($this->hidden_layer) - 1; $i >= 0; $i--) { if ($i == sizeof($this->hidden_layer) - 1) { // doing a backward propagation output $this->hidden_layer[$i]->BackPropagationOutput($expected); } else { //back prop hidden $this->hidden_layer[$i]->BackPropagationHidden($this->hidden_layer[$i + 1]->gamma, $this->hidden_layer[$i + 1]->weight); } } //Update weights for ($i = 0; $i < sizeof($this->hidden_layer); $i++) { $this->hidden_layer[$i]->UpdateWeight(); } } // end BackProp($expected) } // end class NeuralNetwork /** * Each individual layer in the ML */ class Layer { public $numberOfInput; //# of neurons in the previous layer public $numberOfOuput; //# of neurons in the current layer public $output = array(); //outputs of this layer public $input_layer = array(); //inputs in into this layer public $weight[][]; //weights of this layer, a two-dimensional array public $weightDelta[][]; //deltas of this layer, a two-dimensional array public $gamma = array(); //gamma of this layer public $error = array(); //error of the output layer public static $random = new rand(); //Static random class variable /** * Constructor initilizes various data structures * * @param $numberOfInput Number of neurons in the previous layer * @param $numberOfOuput Number of neurons in the current layer * * note that $this->input refers to NeuralNetwork's member array variable $input * // input = 3, hidden layer = 25 => (3, 25) * $this->hidden_layer[0] = new Layer($this->input[0], $this->input[0 + 1]); * // hiddenl = 25, hiddenl = 25 => (25, 25) * $this->hidden_layer[1] = new Layer($this->input[1], $this->input[1 + 1]); * // hidden l = 25, hidden layer 2 = 25 => (25, 1) * $this->hidden_layer[2] = new Layer($this->input[2], $this->input[2 + 1]); * // so this last index is not iterated because of count($input) - 1, which is * // when $i = 3. 3 < 3 is false * // hiddenl = 25, hidden layer = 25 => (1, null) * $this->hidden_layer[3] = new Layer($this->input[3], $this->input[3 + 1]); */ public __construct($numberOfInput, $numberOfOuput) { $this.numberOfInput = $numberOfInput; // 3 $this.numberOfOuput = $numberOfOuput; // 25 //initialize data structures // these need to be refined and probably involve matrix manipulation // or we can use for loops to initialize the matrix: for ($i = 0; $i < $this->numberOfOuput; $i++) { for ($j = 0; $j < $this->numberOfInput; $j++) { // need to refine these $this->weight[$i][$j] = 0; $this->weightDelta[$i][$j] = 0; } } // all it does above is initializing the array elements to their default values. // all the array elements are initialized to zero. $this->InitilizeWeight(); //initilize weights } /** * Initilize weights between -0.5 and 0.5 */ public InitilizeWeight() { for ($i = 0; $i < $this->numberOfOuput; $i++) { for ($j = 0; $j < $this->numberOfInput; $j++) { // I need to refine this. It doesn't seem right! $this->weight[$i][$j] = rand(- 0.5, 0.5); } } } /** * Feedforward this layer with a given input * * @param $input The output values of the previous layer */ public FeedForward($input) { // initialize the layers which can be used for backward propagation $this->input_layer = $input; //feed forward for ($i = 0; $i < $this->numberOfOuput; $i++) { $this->output[$i] = 0; for ($j = 0; $j < $this->numberOfInput; $j++) { // this is the output sum of the activation function: sigmoid, tanH,... // this is where we can add a bias to the output sum // $this->input_layer[$j] * $this->weight[$i][$j] + $this->bias[$j] $this->output[$i] += $this->input_layer[$j] * $this->weight[$i][$j]; } // I need to refine and maybe use sigmoid() instead //$this->output[$i] = (float)Math.Tanh($this->output[$i]); $this->output[$i] = call_user_func_array(array('sigmoid', $this->output[$i]); } // in the calling code only returns output of the last layer is used even though // we return the full array of result return $this->output; } /** * Activation functions. * * You can use other activation functions as well: sigmoid(), ReLU(), softmax, etc. * * public function sigmoid($x) * { * return 1 / (1 + pow(M_E, -$x)); * } * * a derivative of sigmoid() * * public function dsigmoid($y) * { * // return sigmoid($x) * (1 - sigmoid($x)); * return $y * (1 - $y); * } * * ReLU * * public function relu($x) * { * //$x = $x > 0 ? 1 : 0; * return $x > 0 ? 1 : 0; * } * * TanH: * * public function getTanH($x) * { * // return the computed tanH() * return tanh($x); * } * * Or use it directly: * * echo tanh(M_PI_4); // output: 0.65579420263267 * echo tanh(0.50); // output: 0.46211715726001 * echo tanh(-0.50); // output: -0.46211715726001 * echo tanh(5); // output: 0.9999092042626 * echo tanh(-5); // output: -0.9999092042626 * echo tanh(10); // output: 0.99999999587769 * echo tanh(-10); // output: -0.99999999587769 */ /** * TanH derivative * * @param $value An already computed TanH value, for example: 0.65579420263267 * * Notice that to use this TanHDer() you first have to get the value of tanh() and * then call this function passing the computed value to it. See example above. */ public TanHDer($value) { return 1 - ($value * $value); } /** * Back propagation for the output layer * * @param $expected The expected output */ public BackPropagationOutput($expected) { //Error derivative of the cost function for ($i = 0; $i < $this->numberOfOuput; $i++) { $this->error[$i] = $this->output[$i] - $expected[$i]; } //Gamma calculation for ($i = 0; $i < $this->numberOfOuput; $i++) { $this->gamma[$i] = $this->error[$i] * $this->TanHDer($this->output[$i]); } //Caluclating delta weights for ($i = 0; $i < $this->numberOfOuput; $i++) { for ($j = 0; $j < $this->numberOfInput; $j++) { $this->weightDelta[$i, $j] = $this->gamma[$i] * $this->input_layer[$j]; } } } /** * Back propagation for the hidden layers * * @param $gammaForward the gamma value of the forward layer * @param $weightFoward the weights of the forward layer */ public BackPropagationHidden($gammaForward, $weightFoward[][]) { //Caluclate new gamma using gamma sums of the forward layer for ($i = 0; $i < $this->numberOfOuput; $i++) { $this->gamma[$i] = 0; for ($j = 0; $j < count($gammaForward); $j++) { $this->gamma[$i] += $gammaForward[$j] * $weightFoward[$j, $i]; } $this->gamma[$i] *= $this->TanHDer($this->output[$i]); } //Caluclating detla weights for ($i = 0; $i < $this->numberOfOuput; $i++) { for ($j = 0; $j < $this->numberOfInput; $j++) { $this->weightDelta[$i, $j] = $this->gamma[$i] * $this->input_layer[$j]; } } } /** * Updating weights */ public UpdateWeight() { for ($i = 0; $i < $this->numberOfOuput; $i++) { for ($j = 0; $j < $this->numberOfInput; $j++) { // learning rate is hardcoded to 0.033 $this->weight[$i, $j] -= $this->weightDelta[$i, $j] * 0.033f; } } } } // end class Layer ?>
Article Date: October 20, 2013
By Paul S. Tuon
File name incuding directory: Home/Database/connection.php <?php // arbitrarily name you give it when // you create during phpMyAdmin setup $databaseName = "db1.abc.10077"; //given to you by your hosting co. $hostingserver = "db1.abc10077.example.com"; // either given to you or you create it yourself $username = "yourUsername"; // either given to you or you create it yourself $password = "yourPassword"; ?>
<?php include('Home/Database/connection.php'); $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); ?>
<?php include('Home/Database/connection.php'); $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName; port=your_database_port_number;charset=utf8", $username, $password); ?>
<?php include('Home/Database/connection.php'); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } ?>
<?php include('Home/Database/connection.php'); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => true, PDO::ERRMODE_EXCEPTION => true)); } catch (PDOException $Exception) { echo 'Connection error: ' . $Exception->getMessage(); } ?>
<?php include('Home/Database/connection.php'); try { //initiate an instantiation $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); //after instantiation $conn->setAttribute(PDO::ATTR_PERSISTENT, PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)); } catch (PDOException $ex) { echo 'Connection error: ' . $ex->getMessage(); } ?>
<?php include('Home/Database/connection.php'); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); // use the connection here // .... } catch (PDOException $exception) { echo 'Cannot connect to the database. '.$exception->getMessage(); } // and now we're done; close it $conn = null; ?>
<?php //create a table named membership_table if it doesn't exist in the database name try { $conn->query("CREATE TABLE IF NOT EXISTS `membership_table` ( `id` int(10) NOT NULL auto_increment, //id is increment automatically `name` varchar(25) NOT NULL, `address` varchar(64), `email` varchar(64) NOT NULL, //just to have a variety for demonstrative purpose `price` float(10,2), //can be null,10 digits with 2 decimal `description` text(64), //also can be null `date_time` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, // the following definitions are advanced uses for key manipulations PRIMARY KEY (`id`), //used for referring to certain id UNIQUE KEY `id` (`id`), //for referring to a unique id // full text searching similar to Google search FULLTEXT (`name`, `address`, `email`, `description`) ) //MySQL 5.7 or higher: InnoDB is the default storage engine but //consumes more bytes. //So MyISAM is the preferred choice here/consuming less bytes and //runs faster. ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 "); } catch (PDOException $e) { echo "Error: Fail to create a table. " . $e->getMessage(); } ?>
<?php //Let's prepare to insert Joe's data into membership database $name = 'Joe Public1'; $email = 'abc@example.com'; $address = '123 Main St'; //hours in 24-hour military time //displays: 04-26-2016 20:01:04 $current_date_time = date("m-d-Y H:i:s"); //displays: 26-04-2016 20:01:04 $current_date_time = date("d-m-Y H:i:s"); //displays: 2016-04-26 20:01:04 $current_date_time = date("Y-m-d H:i:s"); try { # Prepare to insert Joe's data into club's membership database # using ?????? $stmt = $conn->prepare('INSERT INTO membership_table (name, address, email, price, description, created_time) VALUES(?, ?, ?, ?, ?, ?)'); $stmt->execute(array( 'name' => ' . $name . ', 'address' => ' . $address . ', 'email' => ' . $email . '. 'price' => ' . $price . '. 'description' => ' . $description . '. 'date_time' => ' . $current_date_time . ' )); # For debugging purpose? Affected rows? # output 1 row. # rowCount() is similar to mysql_num_rows() for the old PHP API echo "Data has been entered successfully: " . $stmt->rowCount(); } catch (PDOException $e) { echo 'Can't insert data into database. ' . $e->getMessage(); } ?>
<?php include('Home/Database/connection.php'); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'ERROR: Can't connect to the database. ' . $e->getMessage(); } try { // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO membership_table (name, address, email, price, description, created_time) VALUES (:name, :address, :email, :price, :description, :created_time)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':address', $address); $stmt->bindParam(':email', $email); $stmt->bindParam(':price', $price); $stmt->bindParam(':description', $description); $stmt->bindParam(':created_time', $created_time); // insert a row $name = "Joe Public"; $address = "123 main st"; $email = "joe@example.com"; $price = 10.00; $description = "this is a description"; $created_time = date("Y-m-d H:i:s"); $stmt->execute(); // insert another row $name = "Joe Public"; $address = "123 main st"; $email = "joe@example.com"; $price = 10.00; $description = "this is a description"; $created_time = date("Y-m-d H:i:s"); $stmt->execute(); // insert another row $name = "John Doe"; $address = "999 main st"; $email = "john@example.com"; $price = 30.00; $description = "this is another description"; $created_time = date("Y-m-d H:i:s"); $stmt->execute(); echo "New records created successfully"; } catch (PDOException $e) { echo "Cannot insert data into the database. " . $e->getMessage(); } ?>
<?php //include all database credential, e.g., $host, $database, $username, //$password include("Home/Database/Credential.php"); try { $conn = new PDO("mysql:host=$host;dbname=$database", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'ERROR: Cannot connect to the database. ' . $e->getMessage(); } //try to create a table if one doesn't exist try { $conn->query("CREATE TABLE IF NOT EXISTS `Products` ( ID int(6) NOT NULL auto_increment, ProductNum VARCHAR(8) NOT NULL, ProductName VARCHAR(35) NOT NULL, Price DOUBLE(8, 2) NOT NULL, Image VARCHAR(45), URL VARCHAR(45) NOT NULL, Description VARCHAR(64), PRIMARY KEY (ID), UNIQUE ID (ID), // full text searching similar to Google search FULLTEXT (ProductNum, ProductName, Description) ) //MySQL 5.7 or higher: InnoDB is the default storage engine but //consumes more bytes. //So MyISAM is the preferred choice here/consuming less bytes and //runs faster. ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 "); } catch (PDOException $e) { echo 'ERROR: Cannot create a table! ' . $e->getMessage(); } try { $result = $conn->prepare("INSERT INTO `Products` ( `ProductNum`, `ProductName`, `Price`, `Image`, `URL`, `Description` ) VALUES ( :ProductNum, :ProductName, :Price, :Image, :URL, :Description ) "); $result->bindParam(':ProductNum', $ProductNum, PDO::PARAM_STR); $result->bindParam(':ProductName', $ProductName, PDO::PARAM_STR); //No PDO::PARAM_DOUBLE OR PDO::PARAM_FLOAT, //so use PDO::PARAM_STR instead ////all float or decimal # treat as string, eg '12.30' $result->bindParam(':Price', $Price, PDO::PARAM_STR); $result->bindParam(':Image', $Image, PDO::PARAM_STR); $result->bindParam(':URL', $URL, PDO::PARAM_STR); $result->bindParam(':Description', $Description, PDO::PARAM_STR); $result->execute(); } catch (PDOException $e) { echo 'Can't insert data into database. ' . $e->getMessage(); } //Notice that you can place these values after the //execute() statement //and outside the try ... catch block as well and it still works. if (isset($_POST['num']) && ($_POST['num'] != '') ) { $ProductNum = $_POST['num']; } else { $Error = 'You forgot to type in the product number.'; $Flag = true; } if (isset($_POST['name']) && ($_POST['name'] != '') ) { $ProductName = $_POST['name']; } else { $Error = 'You forgot to type in the product name.'; $Flag = true; } if (isset($_POST['price']) && ($_POST['price'] != '') ) { $Price = $_POST['price']; } else { $Error = 'You forgot to type the product price.'; $Flag = true; } if (isset($_POST['image']) && ($_POST['image'] != '') ) { $Image = $_POST['image']; } else { $Error = 'You forgot to type the product image.'; $Flag = true; } if (isset($_POST['url']) && ($_POST['url'] != '') ) { $URL = $_POST['url']; } else { $Error = 'You forgot to type in the product url.'; $Flag = true; } if (isset($_POST['description']) && ($_POST['description'] != '')) { $Description = $_POST['description']; } else { $Error = 'You forgot to type in the product description.'; $Flag = true; } ?>
<?php include('Home/Database/connection.php'); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'ERROR: Cannot connect to the database. ' . $e->getMessage(); } try { // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO customer_table (firstname, lastname, email, address) VALUES (:firstname, :lastname, :email, :address)"); //for placeholders, do like this: //VALUES (?, ?, ?, ?)"); $stmt->bindValue(':firstname', $firstname, PDO::PARAM_STR); $stmt->bindValue(':lastname', $lastname, PDO::PARAM_STR); $stmt->bindValue(':email', $email, PDO::PARAM_STR); $stmt->bindValue(':address', $address, PDO::PARAM_STR); //for placeholders, do like this: //$stmt->bindValue(1, 'firstname', $firstname, PDO::PARAM_STR); //$stmt->bindValue(2, 'lastname', $lastname, PDO::PARAM_STR); //$stmt->bindValue(3, 'email', $email, PDO::PARAM_STR); //$stmt->bindValue(4, 'address', $address, PDO::PARAM_STR); // insert a row $firstname = "Joe"; $lastname = "Public"; $email = "joe@example.com"; $address = "123 Main St"; $stmt->execute(); // insert another row $firstname = "Jane"; $lastname = "Doe"; $email = "jane@example.com"; $address = "666 Main St"; $stmt->execute(); // insert another row $firstname = "Julie"; $lastname = "Johnson"; $email = "julie@example.com"; $address = "777 Main St"; $stmt->execute(); echo "New records created successfully"; } catch (PDOException $e) { echo "Error: Cannot insert data into the database. " . $e->getMessage(); } ?>
<?php include('Home/Database/connection.php'); $customer_name = 'Bill'; # user-supplied data try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { $data = $conn->query('SELECT * FROM customer_table WHERE customer_name = ' . $conn->quote($customer_name)); foreach($data as $row) { print_r($row); } } catch (PDOException $ex) { echo 'ERROR: Cannot select the data. ' . $ex->getMessage(); } ?>
<?php include('Home/Database/connection.php'); //get username and password from user input $user = $_GET['username']; //e.g.: myuser123 $pass = $_GET['password']; //e.g.: mypass123 try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { $stmt = $conn->prepare("SELECT * FROM membership_table WHERE username = :username AND password = :password"); $result = $stmt->execute(array($user, $pass)); //here if you want to know how many rows selected $rowcount = $result->rowCount(); if ($rowcount > 0) { echo($rowcount . ' rows'); // output # of rows selected } // set any fetch mode constants: OBJ, NUM, ASSOC, BOTH, // LAZY, CLASS, etc. Here I use OBJ $result->setFetchMode(PDO::FETCH_OBJ); while ($rows = $result->fetch()) { $username = $rows->username; $password = $rows->password; } } catch (PDOException $e) { echo 'ERROR: Cannot retrieve data. ' . $e->getMessage(); } ?>
<?php include('Home/Database/connection.php'); //get username and password from user input $user = $_GET['username']; //e.g.: myuser123 $pass = $_GET['password']; //e.g.: mypass123 try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { //a fancy way of programming but not easy to understand! $format = sprintf("SELECT * FROM %s WHERE username = :%s AND password = :%s", membership_table, username, password); $stmt = $conn->prepare("$format"); $result = $stmt->execute(array($user, $pass)); //here if you want to know how many rows selected $rowcount = $result->rowCount(); if ($rowcount > 0) { echo($rowcount . ' rows'); // output # of rows selected } // set any fetch mode constants: OBJ, NUM, ASSOC, BOTH, // LAZY, CLASS, etc. Here I use ASSOC $result->setFetchMode(PDO::FETCH_ASSOC); while ($rows = $result->fetch()) { $username = $rows['username']; $password = $rows['password']; } } catch (PDOException $e) { echo 'ERROR: Cannot retrieve data. ' . $e->getMessage(); } ?>
<?php include("Home/Database/Credential.php"); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { $result = $conn->prepare("SELECT * FROM Products"); $result->execute(); // set any fetch mode constants: OBJ, NUM, ASSOC, BOTH, // LAZY, CLASS, etc. Here I use BOTH $result->setFetchMode(PDO::FETCH_BOTH); echo '<table>'; while ($rows = $result->fetch()) { echo '<tr>'; echo '<td>' . $rows->ProductNum . </td>; echo '<td>' . $rows->ProductName . </td>; echo '<td>' . $rows->ProductPrice . </td>; echo '<td>' . $rows[3] . </td>; /* ProductImage */ echo '<td>' . $rows[4] . </td>; /* ProductURL */ echo '<td>' . $rows[5] . </td>; /* ProductDescr. */ echo '</tr>'; } echo '</table>'; } catch (PDOException $e) { echo 'ERROR: Cannot retrieve data. ' . $e->getMessage(); } ?>
<?php include('Home/Database/connection.php'); /* * The Prepared Statements Method * Best Practice */ $cutomer_id = xyz999; //obtained from a user input insecure form $order_number = 'abc123'; //user-supplied input from an insecure form try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { //Initiate the database handshake with mysql by passing the //query to it $stmt = "SELECT * FROM customer_table WHERE order_number like ? AND customer_id like ? "; # Prepare to retrieve customer's data from database # using ?????? $stmt = $conn->prepare($stmt); # Execute the retrieval and binds the palceholders using ?? to # customer's data (variables) $result = $stmt->execute(array( 'order_number' => ' . $order_number . ', 'customer_id' => ' . $cutomer_id . ' )); // Affected Rows? //Like if you want to know how many rows selected? // Use rowCount() and it is similar to mysql_num_rows() echo $stmt->rowCount(); // 1 row //Or grab values in selected row in resultset $result->setFetchMode(PDO::FETCH_BOTH); while ($rows = $result->fetch()) { $ProductNum = $rows->ProductNum; $ProductName = $rows->ProductName; $ProductPrice = $rows->ProductPrice; $ProductImage = $rows[3]; $ProductURL = $rows[4]; $Description = $rows[5]; } } catch (PDOException $e) { echo 'ERROR: Cannot retrieve the data. ' . $e->getMessage(); } ?>
<?php include("Home/Database/Credential.php"); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { $conn->query("UPDATE Customers_Table SET Price = 99.95 AND Description = "Men's Suits On Sale" WHERE ID = ($_POST['id'])"); } catch (PDOException $e) { echo 'ERROR: Cannot update the records. ' . $e->getMessage(); } ?>
<?php include("Home/Database/Credential.php"); try { $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Cannot connect to the database. ' . $e->getMessage(); } try { $stmt = $conn->prepare("UPDATE Customers_Table SET Price = ? AND Description = ? WHERE ID = ?) "); //And here we're supplying the actual values $id = 'abc123'; $price = 99.95; $description = "Men's Suits On Sale"; $stmt->execute(array($price, $description, $id)); $affected_rows = $stmt->rowCount(); } catch (PDOException $e) { echo 'ERROR: Cannot update the records. ' . $e->getMessage(); } ?>
<?php class Foo{ public test($x) { if ($x == 1){ // do something with $x }elseif ($x == 2){ // do something with $x again }elseif ($x == 3){ // do something with $x again }else{ // do nothing with $x } } private getFoo(){ for ($i = 1; $i < 10; ++i){ // do something with $i } } } ?>
<?php class Foo { private $arr; public function config() { return [ 'id' => 'app', 'basePath' => dirname(__DIR__), 'component' => [ 'request' => [ 'csrf' => 'csrf-app', ], 'user' => [ 'identity' => 'app\model\User', 'autoLogin' => true, 'cookie' => [ 'name' => 'id-app', 'httpOnly' => true ], 'error' => [ 'action' => 'site/error', ], ], ], ]; } // end config() public function example($arg1 = null, $arg2 = null) { if (!empty($arg1)) { // do something with $arg1 foreach ($arg1 as $item) { // do something with $item try { switch ($item) { case 1: // do something if ($something) { for ($i = 0; $i < $something; $i++) { $dosomething[$i] = getSomething(); } } elseif ($otherThing) { foreach ($otherThing) { try { $doOtherThing = getOtherthing(); } catch (Exception $e) { // doOtherThing with $e; } catch (OtherException $o) { // doOtherThing with $o } } // end foreach } // end elseif ($something) break; case 2: // do something break; case 3: // do something break; default: // do something break; } // end switch } // end try catch (Exception $e) { // Error! Do something with the error $e } } // end foreach } // end if $arg1 is not empty elseif ($arg2 != null) { // do ... while and for() loops $test = false; do { for ($i = 0; $i < count($arg2); ++$i) { if ($arg2[$i] == 1) { $test = true; break; } } // end for() } // end do while ($test == false); } // end elseif else { // do nothing return ''; } $connect = ''; $attempt = 3; while (!$connect AND $attempt > 0) { $authConn->connect(); $connect = $authConn->isConnect(); $attempt = $attempt - 1; } } // end example() } // end class Foo ?>
<?php class Foo { public addValue($x, $y) { // method body } // end addValue() private getFoo() { // method body } // end getFoo() } // end class Foo ?> Notice the comments: // end addValue(), // end getFoo(), // end class Foo
<?php class Foo { if ($expr1) { // lengthy multiple statements code block // lengthy multiple statements code block // lengthy multiple statements code block } // end if ($expr1) elseif ($expr2) { // lengthy multiple statements code block // lengthy multiple statements code block // lengthy multiple statements code block } // end elseif ($expr2) else { // lengthy multiple statements code block // lengthy multiple statements code block // lengthy multiple statements code block } // end else if ($expr2) try { // lengthy multiple statements code block // lengthy multiple statements code block // lengthy multiple statements code block // lengthy multiple statements code block } // end try block catch (Exception $e) { // lengthy multiple statements code block } // end Exception $e catch (OtherException $o) { // lengthy multiple statements code block } // end OtherException $o } // end class Foo ?> Notice the comments: // end if ($expr1), // end elseif ($expr2), // end else if ($expr2) // end try block, // end Exception $e, // end OtherException $o // end class Foo
[...elements...]
is used instead of the regular long form array(...elements...).
And (shorthand) arrays used in the configurations can optionally contain a comma (",") as well at the end of the array element list. As examples, the below configurations contain a comma following the last array element [particularly 'charset => utf8' for shorthand array] even though there isn't another array element following it.
As a matter of fact, both regular arrays and shorthand arrays can contain a comma (",") at the end of the array element list. This is legal (for both) and you can choose to put it there or take it out and it is perfectly fine. It's not a requirement to have a comma at the end of the last array element. So it's up to your personal preference.
However, this coding standard strongly recommends putting a comma after all array elements because it avoids bugs. The reason that it is legal to have a comma after the last array element is to speed up coding process and avoid bugs. So it is strongly suggested that you put a comma after the last array element to avoid bugs.
Here is a snippet of code using the regular array:
$requirement = array(
array(
'name' => 'PHP Some Extension',
'mandatory' => true,
'condition' => extension_loaded('some_extension'),
'by' => 'Some application feature',
'memo' => 'PHP extension "some_extension" required',
), // <== notice the the comma!
);
In the following, a configuration is used to create and initialize a database connection. Notice the comma following the array element 'charset => utf8' even though there isn't another array element following it:
$config = [
'class' => 'core\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8', // <== notice the the comma!
];
$db = core::createObject($config);
If you look at the example preview earlier [in the function config()], you'll see shorthand arrays are being used and all last elements of the arrays have a comma after each of the last element of the arrays. So it is definitely recommended that shorthand arrays and a comma on the last element of the array are being used--on your own programming chores--because it is much cleaner and easier to visualize, and most importantly, it speeds up your application development by eliminating bugs and unnecessary syntax corrections.
$a = $b + $c; // add b to c Do not do this: $a=$b+$c; //add b to c if ($b == $c) Do not do this: if($b==$c) Do not do this: for($i=0;$i<10;$i++) Do this instead: for ($i = 0; $i < 10; $i++)
class Example { }That looks very good, but on longer reserved/keywords like public, private, protected, static, etc., it looks awful. For examples:
public class Example { } private class Example { } protected class Example { } static class Example { } Or for conditional structures: if (condition) { } else { } elseif { } foreach { }As you can see, indenting four spaces for all code structures, [although very uniformed], is a bad idea, and it looks weird visually and logically. That's why I chose to indent the code according to the length of the reserved keyword.
class Example { private $myVar; public myMethod($x) { // ... code return $x; } // ... more class code here! }Nowaday, the trend is leaving the legacy style behind and more and more programmers are adopting new modern style of coding and my coding convention is a byproduct of the new trend. So do these instead:
<?php class Foo { /** * class body declaration. * notice the four spaces indentation of the class' opening "{" and * the five spaces indentation of the method declaration: public. * notice also that the opening/closing parentheses are aligned vertically at the * same level, and all respective code body are inside the parentheses. * it looks very clean and easy to follow the logic of the code flow. */ public $arr = array(); private $dbConnection; public addValue($x, $y) { // method body // notice that the indentation and placement of the opening "{" and // closing "}" directly leveled with the last letter of its keyword. } private getFoo() { // method body // notice that the indentation and placement of the opening "{" and // closing "}" directly leveled with the last letter of its keyword. } protected getBar() { // method body // notice that the indentation and placement of the opening "{" and // closing "}" directly leveled with the last letter of its keyword. } // this is ok, too, and is preferred, indent five spaces to align with // 'public' which is the most commonly use visibility clause protected setFoo($x) { // method body } public addFoo() { // method body } // this is ok abstract protected function zeroBar(); { // method body } // this is ok, too, indent five spaces to align with 'public' which is // the most commonly use visibility clause abstract arrayHelper() { // code body here for this abstract method } public static function bar() { // method body } // this is ok, too private static function bar() { // method body } // this is ok, too, indent five spaces private static function bar() { // method body } final public static function bar() { // method body } // same as above final private static function bar() { // method body } static function bar() { // method body } // this is ok, too function bar() { // method body } // this is ok, too, indent five spaces to align with 'public' function bar() { // method body } // this is ok, too, because it has at least five spaces indented for body code function bar() { // code body. // notice the placing of "{}" at the same level as the method declaration. // notice also the indented five spaces for coding statements // starting position // ..... } } // end class body ?> Notice that the parentheses are aligned vertically at the same level of indentation. This applies to all other code blocks/structures that contain parentheses, e.g., if/elseif/else, for() and foreach() loops. This makes it very easy to visualize the block of code, especially if the code is very lengthy. Note also that the examples showed multiple styles of indentation, but you need to decide which one is more suited to your style and stick with it consistently and do not use one variation for certain project and another for another project. Be consistent and choose one style and stick with it for the long haul. Traits: Traits are special form of class and they are similar to a normal class. trait ArrayHelper { // main body code of a trait } CSS: For CSS and other languages (such as Javascript, Java, C#, C/C++, etc.) do follow the guideline outlined in this coding standard and follow a five-space rule to align with 'public' visibility clause. For examples: <style> html, body { width: 100%; height: 100%; background-color: #e6e6ff; } #product-item { background-color: white; padding-left: 10px; padding-right: 10px; } div .some-selector { background-color: white; width: 400px; height: 200px; } .nav li > form > button.logout { padding: 15px; border: none; } a.asc:after, a.desc:after { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; padding-left: 5px; } a.asc:after { content: "\e151"; } a.desc:after { content: "\e152"; } </style> <script type="text/javascript"> $(document).ready(function() { public function example(arg) { // function code } // this is ok, too function example(arg) { // function code } // this ok, too, to align with 'public' function example(arg) { // function code } // this ok, too static public function example(arg) { // function code } }); </script> Notice the braces are aligned vertically and indented at the same amount of spaces (5).
<!DOCTYPE html> <html lang="en-US"> <head> <title>Untitled</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="language" content="en" > <link href="./asset/44ab1983/css/style.css" rel="stylesheet"> <script src="./asset/16eb9947/jquery.js"></script> <style> html, body { width: 100%; height: 100%; background-color: #e6e6ff; } #product-item { background-color: white; padding-left: 10px; padding-right: 10px; } </style> <script type="text/javascript"> $(document).ready(function() { public function example(arg) { // function code } }); </script> </head> <body> <div> content of the div </div> <div> <table> <tr> <td> td content </td> </tr> </table> </div> <div> content of the div <a href="#">link</a> </div> </body> </html>
<?php if ($expr1) { // single statement block. notice the use of braces even though it is not required! } elseif ($expr2) { // elseif code block. single statement block } elseif ($expr3) { // multiple statements code block // multiple statements code block // multiple statements code block } else { // else single statement block code block }
<?php switch ($expr) { case 0: echo 'First case, with a break'; break; case 1: echo 'Second case, which falls through'; // no break case 2: case 3: case 4: echo 'Third case, return instead of break'; return; default: echo 'Default case'; break; }
<?php while ($expr) { // structure of code block }
<?php do { // structure of code block; } while ($expr);
<?php do { // structure of code block; } while ($expr);
<?php for ($i = 0; $i < 10; $i++) { // for code block }
<?php foreach ($iterable as $key => $value) { // foreach code block }
<?php try { // try code block } catch (FirstExceptionType $e) { // catch code block } catch (OtherExceptionType $e) { // catch code block }
<?php $closureWithArg = function($arg1, $arg2) { // body };
<?php $longArg_noVar = function( $longArgument, $longerArgument, $muchLongerArgument ) { // code body }; $noArg_longVar = function() use( /* notice naming variables using enumerated variables, although $longVar1 is fine */ $longVar1, /* notice naming variables using enumerated variables, although $longVar2 is fine */ $longerVar2, /* notice naming variables using enumerated variables, although $longVar3 is fine */ $muchLongerVar3 ) { // code body }; $longArg_longVar = function( $longArgument, $longerArgument, $muchLongerArgument ) use( // readability: indents some spaces $longVar1, $longerVar2, $muchLongerVar3 ) { // code body }; // this is ok too $longArg_shortVar = function( $longArgument, $longerArgument, $muchLongerArgument ) use($var1) { // code body }; // this is ok, too $shortArg_longVar = function($arg) use( $longVar1, $longerVar2, $muchLongerVar3 ) { // code body };
<?php $foo->bar( $arg1, function($arg2) use($var1) { // code body }, $arg3 );
<?php // PHP 5.3 and later: namespace Vendor\Model; class Foo { // code block }
<?php // PHP 5.2.x and earlier: class Vendor_Model_Foo { // code block }
<?php namespace Vendor\Model; class Foo { const VERSION = '1.0'; const DATE_APPROVED = '2012-06-01'; }
<?php namespace Vendor\Package; use FooInterface; use BarClass as Bar; use OtherVendor\OtherPackage\BazClass; class Foo extends Bar implements FooInterface { public function sampleFunction($a, $b = null) { if ($a === $b) { bar(); } elseif ($a > $b) { $foo->bar($arg1); } else { BazClass::bar($arg2, $arg3); } } final public static function bar() { // method body } }
<?php /* * file: block.php * * a complete blockchain implementation will still need a P2P network * so we need to implement a P2P network. */ class Block { public __constructor($index, $timestamp, $transaction, $previousHash = '') { $this->index = $index; $this->previousHash = $previousHash; $this->timestamp = $timestamp; //$this->data = $data; $this->transaction = $transaction; $this->hash = $this->calculateHash(); $this->nonce = 0; } public function calculateHash() { // return hash('SHA256', strval($this->previousHash . // $this->timestamp . json_encode($this->transaction) . $this->nonce)); return hash('SHA256', $this->previousHash . $this->timestamp . ((string)$this->transaction) . $this->nonce); } // Implementing Proof-of-Work public function mineBlock($difficulty) { // takes the array elements, converts to string and concatenates 0 to it while (substr($this->hash, 0, $difficulty) !== str_repeat("0", $difficulty)) { $this->nonce++; $this->hash = $this->calculateHash(); } //echo("BLOCK MINED: " + $this->hash); } } // end class Block
<?php /* * file: blockchain.php * * a complete blockchain implementation will still need a P2P network * so we need to implement a P2P network. */ /** * usage: * * $coin = new Blockchain(); * $coin->createTransaction(new Transaction('address1', 'address2', 100)); * $coin->createTransaction(new Transaction('address2', 'address1', 50)); * * echo('\n Start mining...'); * $coin->minePendingTransaction('john-doe-address'); * * echo('\nBalance of John Doe is') . $coin->getBalanceOfAddress('john-doe-address'); * * echo('\n Start mining again...'); * $coin->minePendingTransaction('john-doe-address'); * * echo('\nBalance of John Doe is') . $coin->getBalanceOfAddress('john-doe-address'); */ class Blockchain { public $chain = array(); public __constructor() { // need to refine. // this chain should hold an array of object of genesis block // should be without the "[]" // $chain holds an array of Block objects ... lots of it. // this is where we hold blocks of transaction. $this->chain = [$this->createGenesisBlock()]; $this->difficulty = 2; // this array propery is assigned transactions by minePendingTransaction() below $this->pendingTransaction = array(); $this->miningReward = 100; } public function createGenesisBlock() { // the return statement just returns an instance of Block. // so the constructor that calls this function assigns an instance of Block and // that is it! //return new Block(0, strtotime("2017-01-01"), "Genesis Block"); return new Block(new DateTime('2000-01-01'), [], "0"); // [] short cut array } public function getLatestBlock() { // count the # of array elements in the chain by subtracting 1 to get the // last element in the array and therefore getting the last block. // array element starts at 0, 2nd element is 1, 3rd element is 2, etc. return $this->chain[count($this->chain) - 1]; } public function minePendingTransaction($miningRewardAddress) { // $this->getLatestBlock()->hash refers to the chain's property hash which // holds the block's hash strings $block = new Block(new DateTime(), $this->pendingTransaction, $this->getLatestBlock()->hash); $block->mineBlock($this->difficulty); echo ('Block successfully mined!'); // push the chain onto the block to be stored in the blockchain serial array_push($this->chain, $block); // storing the transactions in this class's // array property $this->pendingTransaction $this->pendingTransaction = [ new Transaction(null, $miningRewardAddress, $this->miningReward) ]; } // create a transaction passing an instance of the Transaction object containing // $fromAddress, $toAddress, $amount // and then push this transaction object onto the array list: pendingTransaction // createTransaction() receives a 'new Transaction("address1", "address2", 100)' // instance object as its argument public function createTransaction($transaction) { // storing the transactions in this class's // array property $this->pendingTransaction array_push($this->pendingTransaction, $transaction); } public function getBalanceOfAddress($address) { $balance = 0; foreach ($this->chain as $block) { foreach ($block->transaction as $trans) { if ($trans->fromAddress === $address) { $balance -= $trans->amount; } if ($trans->toAddress === $address) { $balance += $trans->amount; } } } return $balance; } public function isChainValid() { for ($i = 1; $i < count($this->chain) + 1; $i++) { $currentBlock = $this->chain[$i]; $previousBlock = $this->chain[$i - 1]; if ($currentBlock->hash !== $currentBlock->calculateHash()) { return false; } if ($currentBlock->previousHash !== $previousBlock->hash) { return false; } } return true; } } // end class Blockchain
<?php /* * file: transaction.php * * a complete blockchain implementation will still need a P2P network * so we need to implement a P2P network. */ class Transaction { public __constructor($fromAddress, $toAddress, $amount) { $this->fromAddress = $fromAddress; $this->toAddress = $toAddress; $this->amount = $amount; } } // end class Transaction
Goldman said it remains "Buy-rated on the stock as our view that Nvidia has access to one of the best growth opportunity sets in Semis and that it has a sustainable competitive lead within remains unchanged."
"The stock will likely not bounce back right away, given the severity of the miss," Morgan Stanley said.
Wells Fargo Analyst: Concerns (and now frustration) over a significant gaming channel inventory burn-off have materialized ... While we can appreciate that NVIDIA's weak F4Q19 outlook is impacted by a 1-2 quarter work-down of Pascal mid-range gaming card inventory in the channel ($600M; assuming no sell-in in F4Q19 as crypto-related dynamics flush through the channel), couple with a seasonal decline in game console builds, we think investors will be frustrated by NVIDIA's comments exiting F2Q19 that: "...we [NVIDIA] see inventory at the lower-ends of our stack...inventory is well positioned for back-to-school and building season that's coming up on F3Q19..." Bottom Line: Well, even if we model a strong double-digit growth in DCG next year, we think there is a high likelihood that NVIDIA will not grow next year. We are modeling for as such. The large shortfall in guidance due to a bloated channel due to crypto-currency is in sharp contrast to the comments around channel inventory from the company at the last earnings call. Our estimates and target price are going lower. We remain Market Perform rated. We are Buyers on weakness.
SunTrust Analyst: The surprisingly weak Q4 guide appears temporary. NVDA guided Q4 20% below consensus revs as the company halts 1/3 of gaming segment sales to flush channel inventory built during the crypto enthusiasm in 1H18. This badly damages near-term revenue and profits, but Datacenter, Pro-Viz, and Automotive results support our structural growth view. Gaming resets our 2019 & 2020 EPS to $7.33 & $8.70 (from $8.18 & $9.59). PT goes to $237 (from $316) based on 30x (17x discount to rapid-growth tech peers) our CY20 EPS, discounted back 1 year. Buy.
RBC Analyst: Going forward, we think the focus will now shift to Data Center as gaming expectations are now reset due to crypto currencies and a product transition (Turing) which will unlikely ramp until around the Jul-qtr time frame. Net Net: we lower our price target due to the lower than expected results (PT to $260 from $310). Positively, gaming and Pro Visualization will likely be up q/q in January helping gross margins and offsetting the material gaming weakness.
Payment Type | Declared Date | Payable Date | Amount |
Annual Regular Dividend | February 25, 2016 | March 16, 2016 | $.31 |
Annual Regular Dividend | February 21, 2017 | March 9, 2017 | $.35 |
One-time Special Dividend | February 21, 2017 | March 9, 2017 | $1.00 |
Annual Regular Dividend | February 21, 2018 | March 16, 2018 | $1.05 |
One-time Special Dividend | February 21, 2018 | March 16, 2018 | $3.00 |
Annual Regular Dividend | February 25, 2019 | March 15, 2019 | $1.75 |
One-time Special Dividend | February 25, 2019 | March 15, 2019 | $4.25 |
|
Autoloading of classes is a daily chore if you're a programmer. Every time you build an application (big or small) requires you to load your classes from the directories where classes are located. Most inexperienced programmers (or maybe all inexperienced programmers) typically load their classes at the class level rather than at the application level. Here is an example of loading of classes at a class level:
<?php
include '/home/package/someclass.php';
include_once '/home/package/someotherclass.php';
require '/home/package/somemoreclass.php';
require_once '/home/package/someothermoreclass.php';
/**
* An example of loading classes at a class level
*/
class MyClass extends OtherClass
{
// more code here
// .....
}
As you can see, this class loads four classes (someclass.php
, someotherclass.php
, somemoreclass.php
, someothermoreclass.php
) files at the top of the class file. This is called class level
loading. This is the most popular way of doing for most of us programmers, including experienced and inexperienced programmers.
There is absolutely nothing wrong with class level
loading and it can accomplish tasks (large or small) very well. However, pattern programming methodologies are becoming more and more popular and thus making use of application level
loading even more mainstream.
Pattern programming methodologies, such as the MVC pattern, loading of classes are taking place at the application level
-- and that is, we don't put the include
, include_once
, require
, or require_once
at the top of every class or at anywhere in the class. Rather it is autoloaded directly into the base class. The following description shows how SPL autoloads of classes.
SPL Autoloading
First, here is a simple version that uses an anonymous function to attempt to load the classes ExampleClass1 and ExampleClass2 from the files exampleclass1.php and exampleclass2.php, respectively. This is the simplest version you can use:
<?php
spl_autoload_register(function ($class_name)
{
// Of course, you need to specify a complete path to the
// class file
include $class_name . '.php';
}
);
?>
The code above registers
anonymous function (along with its argument variable $class_name) with PHP.
Now any time you create an instance of a class:
$obj1 = new ExampleClass1();
Or
$obj2 = new ExampleClass2();
PHP will attemp to create an instance of the class, but if PHP doesn't recorgnize that class it will tries to load and include that class name specified in variable $class_name--or classes ExampleClass1 and ExampleClass2 in this case.
In other words, if PHP doesn't recorgnize that class it will call the anonymous function() above passing a string--ExampleClass1 or ExampleClass1--to the anonymous function.
Suppose you want to incorporate an spl_autoload functionality in your base class called Example. Here is how you would do it:
<?php
/**
* Example is the base class serving common functionalities.
*/
class Example extends ParentClass
{
// Using anonymous function, you can put spl_autoload_register() statements anywhere in
// your main base class including inside the constructor
// In an MVC pattern, you can put spl_autoload_register() statements inside
// the starting script file as well
spl_autoload_register(function ($class_name)
{
// Of course, you need to specify a complete path to the
// class file
include $class_name . '.php';
}
);
}
?>
Here again, if PHP doesn't recorgnize the class that is being instantiated, it will call the anonymous function() inside class Example passing a string contains in the variable $class_name to the anonymous function. Remember that autoloading of classes is often being done in the base class or sometimes called base controller class.
Secondly, here is a more sophisticated version that uses a function name to autoload the classes. This is the preferred version if you're developing large-scale applications.
spl_autoload_register() allows you to register
multiple functions (or static methods ['myAutoloader' in this case] from your own autoload class) that PHP will put into a stack/queue and call sequentially when PHP sees an unknown class being referenced or instantiated.
In other words, PHP will call a function name that has been registered
in the spl_autoload_register() and tries to load and include that class name inside that function. For example:
<?php
spl_autoload_register('myAutoloader');
?>
That code above will register
a function named 'myAutoloader' which is illustrated below:
So if you defined an autoload function named 'myAutoloader' [as shown below] and registered
it in spl_autoload_register() [as shown above], PHP will call that function name whenever it sees an unknown class being referenced or instantiated. The two keywords that we're interested in are: referenced
and instantiated
. For example, when you reference
or create an instance
of a class, like so:
<?php
// here, we referenced
MyClass and if PHP doesn't recorgnize this class it will
// call 'myAutoloader'
MyClass::$some_static_property_variable = $this;
// here, we create an instance
of MyClass() and if PHP doesn't recorgnize this class it
// will call 'myAutoloader'
$myClass = new MyClass();
?>
If PHP does not recorgnize this class (i.e., "MyClass" hasn't been instantiated and included), PHP will call a function named myAutoloader() and tries to include that class file inside that function named myAutoloader():
<?php
// PHP calls this function passing a class name as a string like so: myAutoloader("MyClass")
function myAutoloader($className)
{
$path = '/path/to/class/';
// you must name your class file name the same as class name.
// this is the reason why my coding standard states that class file name should be
// the same as class name.
include $path.$className.'.php';
}
?>
In the example above, "MyClass" is the name of the class that you are trying to reference
or instantiate
, PHP passes this class name as a string to spl_autoload_register(), which allows you to pick up the variable ($className) and use it to "include" the appropriate class/file [as shown above].
As a result, you don't specifically need to include that class via an include/require statement. Just simply reference
or instantiate
the class you want to reference
/instantiate
like in the examples above, and since you registered a function (via spl_autoload_register()) of your own, PHP will call that function and it will figure out where all your classes are located.
Notice that this custom function is a function that you have to create and then register it in the spl() autoloader.
Remember that autoloading of classes is often being done in the application's base class, sometimes called controller base class in an MVC pattern talk.
To register your custom auto load function, you typically put spl_autoload_register() statements in your main base helper class and call that class from inside the starting script file. For example:
<?php
/**
* Application is the base helper class serving base class common functionalities.
*/
class Application extends Example
{
// PHP automatically registers the custom 'myAutoloader' function of the class 'Example'
spl_autoload_register(['Example', 'myAutoloader']);
}
?>
In the starting script file, typically in the index.php, you do it like the following:
<?php
/**
* The main index.php starting script file
*/
// loads the helper class
require __DIR__ . '/home/package/application.php';
?>
Assuming Example is an application's base class, here is how you would implement your own custom auto load function:
<?php
/**
* Example is the base class serving common functionalities.
*/
class Example extends ParentClass
{
// PHP automatically calls this function along with passing in a class name as a string
public function myAutoloader($class_name)
{
$path = '/path/to/class/';
// you must name your class file name the same as class name
include $path.$className.'.php';
}
}
?>
In the above base class Example, if somewhere in your application [most likely in the controller], you reference
or create an instance
of any class, like so:
<?php
// here, we referenced
MyClass and if PHP doesn't recorgnize this class it will
// call 'myAutoloader'
MyClass::$some_static_property_variable = $this;
// here, we create an instance
of MyClass() and if PHP doesn't recorgnize this class
// it will call 'myAutoloader'
$myClass = new MyClass();
?>
PHP will trigger a call to the function myAutoloader($class_name) above passing along the class name MyClass as a string to the function. As a result, that class gets included and instantiated.
The benefit of using spl_autoload_register() is that, unlike PHP's __autoload(), you don't need to implement an autoload function in every file that you create or use the include
, include_once
, require
, or require_once
at the top of every class or at anywhere in the class.
<?php
/**
* 'Autoloader', 'Helper', 'Database' are class names.
* Notice that you can place autoloaders in the same class as well:
* 'ClassLoader', 'LibraryLoader'
*/
class Example extends fromParentClass
{
// register classes and their functions
public function __construct()
{
// Load a class: 'Autoloader' is the class name,
// 'ClassLoader' is the name of a function
spl_autoload_register('Autoloader::ClassLoader');
// Load a library: 'LibraryLoader' is the name of a function
spl_autoload_register('Autoloader::LibraryLoader');
// Load a helper class: 'Helper' is the name of the class
spl_autoload_register('Helper::HelperLoader');
// Load a database: 'DatabaseLoader' <== name of a function
spl_autoload_register('Database::DatabaseLoader');
}
}
?>
Here is the implementation of the class Autoloader:
<?php
/**
* Autoloader is the class libraries.
*/
class Autoloader extends fromOtherParentClass
{
// PHP automatically calls this function along with passing in a class name as a string
public function ClassLoader($class_name)
{
$path = '/path/to/class/';
// you must name your class file name the same as class name
include $path.$className.'.php';
}
}
?>
The other classes are implemented in the same fashion. Self-explanatory.
For more see spl autoload.
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space
Sponsor Space