Vi Cheatsheet

a -> Append cursor (After position)
i -> Insert cursor (At position)
esc -> Remove cursor if active
:wq -> Save and quit
:q -> Ask to save and quit
:q! -> Quit without saving
dd -> Cut the line
yy -> Copy the line
p -> Paste the line
:n -> Go to line n
/text -> Search for ‘text’
n -> Jump to next match when search is active
0 -> Go to the beginning of the line
$ -> Go to the end of the line
G -> Go to the end of the document
yn + arrow down -> Copy the current line with next n lines
yn + arrow up -> Copy the current line with previous n lines

Gamification: http://vim-adventures.com (Even though it’s for vi not vim there shouldn’t be any major differences as mentioned here.)

Post a comment

PDO Tutorials 1 – Inserting Single Row

A man's got 99 problems, used mysql_query(), now he has 100.When things are urgent, we all go with the spaghetti code. When they are not, well, some of us still do. Here comes the bad news: We shouldn’t.

If it’s about inserting records to database, most of the old tutorials go with the mysql extension functions such as mysql_connect() and/or mysql_query() which actually have been sitting at the center of the security issues, for example the most popular one: SQL injection.

Deprecated: mysql_connect()PHP’s got a lot more clear recently. As of PHP version 5.5.0, using good old mysql extension functions cause a warning that the methods are now deprecated and the one simple should use mysqli functions or PDO instead. It was a recommendation, now it became a must.

In this short tutorial series, I will try to explain how I use PDO in my OOP classes and also will share codes of a small example.

After the 5 tutorials, you’ll be able to:

  1. Insert single row
  2. Do rollback in failure cases
  3. Insert multiple rows
  4. Update multiple rows
  5. Select rows

All with PDO.

1. Inserting Single Row

There are some ways of executing SQL queries with PDO. If you have your SQL statement prepared with params bound to (not recommended), you can use PDO’s exec() function. If you want to use placeholders in your query (PDO uses either ? or :paramName) and then bind parameters (recommended), you can use PDO’s prepare(), bindParam() and execute() methods (in this order). I’ll go with the second.

Since we are going with OOP, it’s a good idea to keep the basic PDO connection code in a class like Connection.

Connection class contains a WOUF (write-once-use-forever) code so there's no need to memorise it. I know I didn't. (Btw, I just made up WOUF)
class Connection
{
    public function dbConnect()
    {
        try {
            $db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE. ";charset=utf8", USER, PASS);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        } catch (Exception $e) {
            die("Connection not found. Error Code (".$e->getMessage().")");
        }
        return $db;
    }
}

In our classes, we’ll store a private variable for database connections which is an instance of the Connection class. Line 7 and 8 contains some adjustments for PDO where you can find details here. I’d recommend keeping them like this but you can find discussions on Stack Overflow and make your own decision according to your case.

Now that our connection class is ready, we can write a record function to our custom object.

In this tutorial, I have an object named Object (TY, Captain Obvious) which has two attributes: id and name. They are stored in a database table named... "table". (I like to keep things simple.)
You can find the SQL query to create DB and table and other PHP codes in the repo that I'm going to share at the end of the tutorial.

First of all, we need to create a Connection instance object in our class. Best place to create this instance variable is our class’ __constructor method.

private $db;
public function __construct() {
    // create a new PDO connection instance
    $this->db = new Connection();
    $this->db = $this->db->dbConnect();
}

Now let’s create the recordObject method to use this $db variable to insert our object to database. Row id will be handled by the MySQL server and auto incremented.


// Record function for object with properties set
public function recordObject() {
    // create sql query
    $sql = "INSERT INTO `table` (`name`) VALUES (?) ";
    // prepare connection with the query
    $stmt = $this->db->prepare($sql);
    // bind parameters to query
    $stmt->bindParam(1, $this->name);
    // execute the statement
    if ($stmt->execute()) {
        // if statement has success, set self id to last insert id
        $this->id = $this->db->lastInsertId();
        return true;
    } else {
        return false;
    }
}

As you can see in line 4, our INSERT statement is pretty much the same with an SQL command but it has a placeholder. If I was adding two columns, I’d keep adding placeholders like (?,?). Each one is represented by index (starting from 1).

One of the coolest thing about the PDO is that it handles value types by itself. If we were to use SQL queries directly, we would need to surround our strings with quotation marks. With PDO, all we need to do is just bind the string directly and it will put those marks.

After creating the formatted SQL string, I create a variable to store the PDO statement, I also prepare it with prepare() function to bind parameters in the next step. (line 6)

Now I’m ready to bind parameters to this PDO statement. Since the index of the “name” placeholder is 1, I will bind “name” value to param 1. (line 8)

That’s it. Now we can run this query with PDO’s execute() function which returns BOOLEAN and if it is true, set our object’s id to last insert ID.

Create an index.php file to put it all together and debug.

require_once __dir__."/Object.php";

$object = new Object();
$object->name = "Hello PDO";
if ($object->recordObject()) {
    echo "New record with ID: ".$object->id;
} else {
    echo "Could not record";
}

Run it and you the output should be: “New record with ID: ##”

That’s it for the first tutorial. Now you can insert rows one by one (yet) to database with PDO. You can find the code of this tutorial in the Github repo.

The next tutorial will be about rolling back changes which is ultimately important in such cases that the operation might be broken at some point and some of the records are inserted/updated, the rest are not. PDO can roll back the changes from a given point and it will.

Post a comment

Use Sublime Text to Bulk Rename Your Files

There are two cool plugins: One is dired, which allows you to use Sublime Text to manage your files and folders; and another is Text Pastry, which helps you to put increasing numbers to the multi-selected cursors (Of course, it is more than that, just not in this case).

Go ahead and combine this two. Yes, giving numbered names to contents of a folder. There were (in fact, probably still are) utilities existed that people buy for. Why pay, when you can do it with plugins?

First, install dired and Text Pastry plugins from Sublime Text Package Control. No need to restart, just get into it directly by pressing Cmd+Shift+P -> dired: Goto Anywhere -> Goto Directory and then hit enter. It doesn’t matter what directory you are getting into since you can now navigate between folders thanks to dired.

Now, you can see the contents of the directory you are currently inside of, and you can see the shortcuts for navigation. Goto a directory that you want to bulk rename contents of and then press R. Now you can rename the files by using great abilities of Sublime Text such as locating matches, inserting multiple cursors and all.

bulk-rename-files-using-sublime-text-dired-and-text-pastry

Assume that you have a set of images that were taken during one of your trips and you want to rename them like -> trip_1.jpg, trip_2.jpg and so. You opened the folder in Sublime, selected all the images (lines), set all of the names to trip_.jpg and placed your multi cursors after _ (before .). Now what? Just hit Cmd+Shift+P again and then select Text Pastry: From 1 To X. That’s it. Now all of your files have numbers increased by 1 at the end of their names. Hit Ctrl+Enter to save changes and you’re good to go.

Post a comment

Aligning SKPhysicsBody Correctly with SKShapeNode

When you want to create a circle in SpriteKit, SKShapeNode is the quickest and the simplest way for it. You don’t need to create images, you can manage the size, fill colour, stroke colours etc.

However, if you want this node to involve with collisions, you may get some trouble when creating an SKPhysicsBody for that node. The creating process is similar to SKSpriteNode but the alignment of it is different.

By default, SKShapeNode anchor points begin from (0, 0) and there isn’t any property to set it as we want. When we assign a SKPhysicsBody to this node, body’s anchor is its center point so the body doesn’t cover the node correctly.

Here’s how it looks when you want to implement for SKShapeNode as you do in SKSpriteNode:

skshapenode-skphysicsbody

There are plenty of people who were unable to solve this issue. Yet there is one answer on SO that helped me out with this.

To work around this situation, you can create an SKSpriteNode to implement the body and an SKShapeNode as the SKSpriteNode’s child to draw the shape.

First, create an SKSpriteNode and set the width and height same with the diameter of the circle

float radius = 30.0;
SKSpriteNode *aCircle = [SKSpriteNode spriteNodeWithColor:[UIColor clearColor] size:CGSizeMake(radius * 2, radius * 2)];
//

Then create a circular SKPhysicsBody for the SKSpriteNode (thankfully, this is possible)

SKPhysicsBody *circleBody = [SKPhysicsBody bodyWithCircleOfRadius:radius];
[circleBody setDynamic:NO];
[circleBody setUsesPreciseCollisionDetection:YES];
[aCircle circleBody];
//

Here is the key part. Create a CGPathRef as an ellipse in the rect with correct center values.

CGPathRef bodyPath = CGPathCreateWithEllipseInRect(CGRectMake(-[aCircle size].width / 2, -[aCircle size].height / 2, [aCircle size].width, [aCircle size].width), nil);
SKShapeNode *circleShape = [SKShapeNode node];
[circleShape setFillColor:[UIColor redColor]];
[circleShape setLineWidth:0];
[circleShape setPath:bodyPath];
[aCircle addChild:circleShape];
CGPathRelease(bodyPath);
//

Don’t forget to add the child to scene then you are done. As you can see below, the physics body now matches with the node frame correctly.

skspritenode-skshapenode-skphysicsbody.png

Source link of the answer:
SKPhysicsBody not as expected

Other questions about similar issues:
How to align SKPhysicsBody and SKShapeNode?
Align SKPhysicsBody with SKShapeNode
SKPhysicsBody does not work on SKShapeNode
SKshapenode is not responding to Physicsbody
how to make collisions with skshapenode circles
Keeping an SKShapeNode within the bounds of an SKSpriteNode

Post a comment

Sample Apple Push Notification PHP Script

This is an old script that I used to use for sending notifications. I don’t remember the source, on the other hand, it has been modified a couple of times already.

Even though I could manage to send notifications with this script, the Apple server was rejecting the connection after the amount reaches more than 50. It was usually getting cut off around 70. So it needs to get some management for not sending in a loop, like threading or whatever.

<?php

// set time limit to zero in order to avoid timeout
set_time_limit(0);

// charset header for output
header('content-type: text/html; charset: utf-8');

// this is the pass phrase you defined when creating the key
$passphrase = 'my_secret_pass';

// you can post a variable to this string or edit the message here
if (!isset($_POST['msg'])) {
$_POST['msg'] = "Notification message here!";
}

// tr_to_utf function needed to fix the Turkish characters
$message = tr_to_utf($_POST['msg']);

// load your device ids to an array
$deviceIds = array(
'lh142lk3h1o2141p2y412d3yp1234y1p4y1d3j4u12p43131p4y1d3j4u12p4313',
'y1p4y1d3j4u12p43131p4y1d3j4u12p4313lh142lk3h1o2141p2y412d3yp1234'
);

// this is where you can customize your notification
$payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}';

$result = 'Start' . '<br />';

////////////////////////////////////////////////////////////////////////////////
// start to create connection
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyAppGenerated.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

echo count($deviceIds) . ' devices will receive notifications.<br />';

foreach ($deviceIds as $item) {
	// wait for some time
	sleep(1);
	
	// Open a connection to the APNS server
	$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

	if (!$fp) {
		exit("Failed to connect: $err $errstr" . '<br />');
	} else {
		echo 'Apple service is online. ' . '<br />';
	}

	// Build the binary notification
	$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
	
	// Send it to the server
	$result = fwrite($fp, $msg, strlen($msg));
	
	if (!$result) {
		echo 'Undelivered message count: ' . $item . '<br />';
	} else {
		echo 'Delivered message count: ' . $item . '<br />';
	}

	if ($fp) {
		fclose($fp);
		echo 'The connection has been closed by the client' . '<br />';
	}
}

echo count($deviceIds) . ' devices have received notifications.<br />';

// function for fixing Turkish characters
function tr_to_utf($text) {
	$text = trim($text);
	$search = array('Ü', 'Þ', 'Ð', 'Ç', 'Ý', 'Ö', 'ü', 'þ', 'ð', 'ç', 'ý', 'ö');
	$replace = array('Ãœ', 'Åž', '&#286;ž', 'Ç', 'Ä°', 'Ö', 'ü', 'ÅŸ', 'ÄŸ', 'ç', 'ı', 'ö');
	$new_text = str_replace($search, $replace, $text);
	return $new_text;
}

// set time limit back to a normal value
set_time_limit(30);
?>
7 Comments

Node.js -3 | Reading user input from the command line

Readline module, which comes with the Node.js core reads user input so that you can use it as an interaction.

In this example, the user will tell how many glasses of water he/she drinks each day and we’ll say if it’s healthy enough or not.

In the script.js file, require the module like:

var rl = require("readline");

Create the prompts variable:

var prompts = rl.createInterface(process.stdin, process.stdout);

Request user input with a question:

prompts.question("How many glass of water do you drink each day?", function (glasses) {
	var message = "";
	if (glasses > 5) {
		message = "Great! Water is the key of a healthy life.";
	} else {
		message = "Are you drinking just " + glasses + " glass of water? You should drink at least " + (6 - glasses) + " more.";
	}
	console.log(message);
	process.exit();
});

Output will be like:

> node script.js
> How many glass of water do you drink each day?
> 5
> Are you drinking just 5 glass of water? You should drink at least 1 more.
> node script.js
> How many glass of water do you drink each day?
> 7
> Great! Water is the key of a healthy life.
Post a comment