Words from Alejandro U. Alvarez
Programming
All about server and client side back-end programming, php, javascript, mysql…
C++? Quick help for begginers
Mar 9th
Alright I've seen many people who are struggling to understand C++, students, developers... and many more. I will publish here an amazing a decent guide to get you started. I'm assuming you have "some" knowledge of programming (i.e. what is a variable, an integer... )
The basics:
If you know a little about C++, you can probably skip this short introduction. Basically C++ is a multi-purpose programming language. It is used for all sorts of applications, from simple command-line ones, to large statistical programs or videogames.
For know, you should know that you code in C++ using any editor you like, and then you must run a compiler to generate machine code (a .exe file) which is called an executable. But don't worry about that yet.
Starting up: "Hello world!"
Enough of the boring stuff, let's get started doing some real stuff. For now I recommend you download a source code editor, like Dev-C++.
First steps in Dev C++:
- Install and open the program
- Close the Tips that will open up
- Go to File > New > Source code (Or click Ctrl+N)
You will now see an empty page where we will write our code
Base structure:
Our C++ programs will always have the same base structure for now: First we will include necessary files (I will explain later on what they are), then we will declare our functions, and then will go the main code.
So first things first, we will include the necessary files. In order to display on the screen "Hello World!" we are not going to set up an interface, that's more advanced stuff. We will be using the system console (Yes, that black thing with white text on it). The file that will allow us to do that is iostream. So our first line will be:
#include <iostream>
Now that we hace access to the input and output functions, we will tell the compiler that all functions we use are from there, we do that by declaring a namespace:
#include <iostream> using namespace std;
And that is all we need in the header. We can now move on to the main code. In C++ the program executes always the code found inside a function called main. Whether you are on Linux, Windows, Mac, or other OS, it will be of one type or another. For Windows users it will be int
So let's set up an empty main for now:
#include <iostream>
using namespace std;
int main(){
return 0;
}
And finally the Hello world code, we want to display it on the screen, and the function for that is cout (If you are a programmer in other languages, equivlents would be echo or printf)
We must remember to add a "pause" after we display the message, to leave the console open. If we develop in a Windows environment, we can use the command system("pause"); but I recommend using a more global solution like cin.get();
So the final program would be:
#include <iostream>
using namespace std;
int main(){
cout << "Hello world!";
cin.get();
return 0;
}
And this finishes lesson 1
In our next tutorial I will teach you the use of variables and a more advanced look at the iostream functions cout and cin
Perfect jQuery UI rotating tabs
Oct 20th
Tabs are nice. They create a very elegant interface, and jQuery UI does this marvelously, here we have a little preview of this:

jQuery UI Tabs
How to do that?
Include the files
With jQuery and jQuery UI it is dead simple. First, load the JS libraries, I recommend using the hosted files at Google for jQuery:
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="path/to/jquery UI" type="text/javascript"></script>
Remember to include also the CSS files for the UI Theme! Otherwise the tabs won't seem to work!
The HTML for the tabs:
We need a little HTML for our tabs to work:
A wrapper, a few divs with the content, and an unordered list with the tabs:
<div id="tabs-rotate"> <ul> <li><a href="#tab1"><span>Tab 1</span></a></li> <li><a href="#tab2"><span>Tab 2</span></a></li> <li><a href="#tab3"><span>Tab 3</span></a></li> </ul> <div id="tab1">Tab 1 content</div> <div id="tab2">Tab 2 content</div> <div id="tab3">Tab 3 content</div> </div>
The JavaScript:
Now comes the cool part, basically we want to have tabs. But although tabs are nice, people may not realize there is more content, or they might be just too lazy to browse through it, so, why not rotate through the tabs?
jQuery UI does that by itself with a very simple commant, but it is not perfect! So we need to program our tabs to rotate, unless the mouse is over them. This way when a user is looking for a link, the tab will wait!
So here is how this is achieved:
$(document).ready(function(){ $("#tabs-rotate").tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 3000); $('#tabs-rotate').hover(function(){ $(this).tabs('rotate', 0, false); },function(){ $(this).tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 3000); } ); });
First we instruct jQuery UI to set up tabs in that div, and to rotate them. Then we use a hover event to control the rotation. On hover no rotation, and on out resume rotation.
See it in action
You can see it working on the DJs Music homepage
As with the best stuff, it's terribly simple
Hope you enjoy,
Alex
Parse links in user comments
Sep 13th
When you allow users to comment and post stuff to your website, it is interesting and useful allowing them to post links and other stuff. But how can we do so easily?
Surely there is BBCode, phpBB, allowing only some HTML tags... etc but how easy is this approach for the end user? Of course some users will be familiar with BB code, or with HTML; others will be curious enough to learn how to use it, but most won't. And we want our users to be able to do so.
The solution: URL Parsing
How about this: They simply post the URL of whatever they want to include (A link, a picture, a YouTube video... ) and we detect that, and take the corresponding action.
First of all we need something that detects links, I have written a simple regexp to do so:
function parse($text){ return preg_replace_callback('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', 'parseUrl', $text); }
This is valid for almost all URLs, as long as http is the beggining. This function calls a callback function whenever a URL is found, called parseURL, which will then take care of the URL.
parseURL
Now that the URL is found, we need to take care of it: The url is stored in a parameter returned from the function preg_replace_callback. It is contained in the first element of the returned array.
function parseURL($url){ $link = $url[0]; }
We will parse the full url with a built-in function called parse_url(), which will return the following data:
- scheme - e.g. http
- host
- port
- user
- pass
- path
- query - after the question mark ?
- fragment - after the hashmark #
To get the file format we will check the extension:
$ext = substr(strrchr($url['path']),'.'),1);
Image formats:
$imgs = array('jpg','jpeg','gif','png','tif'); // You can write more if you want, this is only an example
Now let's check if it is or not an image:
if(in_array($ext,$imgs)){ return '<img src="'.$link.'" alt="This is a picture" class="insertedPic" />'; }
This way if a user inserts a link to a picture, the picture is displayed. You can now add a link, or change in any way the result of this.
If it is a YouTube video it would also be good to embed it, so we will first check if it is:
if(eregi('^(www\.)*(youtube\.).{2,3}$',$url['host'])){ // Check for youtube video return youtubeEmbed($url['query']); }
As you can see, if the link comes from youtube, we will embed it using our custom function youtubeEmbed:
youtubeEmbed()
function youtubeEmbed($params){ parse_str($params); if(substr($v , strlen($v)-3 ,3) == '<br '){ $v = substr($v , 0 ,strlen($v)-3); } if($v){ return ' <div class="addedLink"/><object width="200px" height="150px" style="display:block; z-index:1"><param name="movie" value="http://www.youtube.com/v/'.$v.'"></param><param name="allowFullScreen" value="true"></param><param name="wmode" value="transparent"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$v.'&rel=1&color1=0xFFFFFF&color2=0x666666&border=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="200" height="150" wmode="transparent"></embed></object><br '; }else{ return false; } } </pre/> I won't go into too much detail here, it is quite simple, we take the parameter $v, which is the video ID, and then we proceed to the video embed... You can do the same with Metacafe, Vimeo, College Humor, Google Video... etc and the process would be basically the same for all. <h2>Further uses</h2> I use this class to detect internal links in some of my websites. If the link points to a page with a picture for example, I show a small version of it, if it points to a user profile I show the user's name and some data... etc The options are endless, and once you have everything parsed it is very easy to add new stuff. It really makes it simple for users to share pictures and videos, and it is the safest way of doing so, as well as the best way if you ever want to change the behavior, since in the database all you store is the raw URL.
Calculate age in PHP from timestamp
Sep 8th
If you ever wanted to calculate someone's age in PHP from a birth timestamp, you must take into account that the age is more than the number of years, since days and months are also important, so I wrote a simple function that will return the exact age for a given timestamp:
function getAge($birth){ $t = time(); $age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth; return floor($age/31536000); }
Basically we first get the current time and store it in a variable (To avoid having to call the function time more than once)
Then we get the age in milliseconds (Taking into account that before 1969 timestamps are negative, thus the ternary operator)
Now we have the date in milliseconds, we divide it by the number of milliseconds in a year (60*60*24*365)
And that is basically it
