phpPgAdmin On Linux On Windows With Vagrant

This tutorial is a continuation of Rails On Linux On Windows With Vagrant.

What we want to achieve at the end of this tutorial is to able to modify our PostgresSQL database from a convenient web interface (phpPgAdmin) directly from the web browser in our host machine. Observe:

2015-09-18 21_19_47-phpPgAdmin

Let’s roll:

Port Forwarding

For this to work, we need to forward the port 80 in our guest machine to port 8080 in our host.

If you are in SSH mode, exit it by entering

exit

Then halt it:

vagrant halt

In the Vagrantfile in your project directory, uncomment the following line:

config.vm.network "forwarded_port", guest: 80, host: 8080

Though not apparent in the Vagrantfile here, the virtual machine we used forwards port 3000 in the guest machine to port 3000 in the host machine. That is how we are able to access our Rails application from the host machine. You can find it here:

C:\Users\YOURUSERNAME\.vagrant.d\boxes\fiercepunchstudios-VAGRANTSLASH-vagabond\0.1.1\virtualbox\include

In “_Vagrantfile” (the only file in that directory), you can peek in its contents:

Vagrant.configure(2) do |config|
 config.vm.network "forwarded_port", guest: 3000, host: 3000
end

Install phpPgAdmin

After you have ran vagrant up and vagrant ssh, in git bash enter:

sudo apt-get update
sudo apt-get install phppgadmin

Congratulations! You have installed phpPgAdmin, but when you go to its URL – http://localhost:8080/phppgadmin/ (make sure its all in lower case), you get a page not found error:

2015-09-18 20_46_29-404 Not Found

It’s not all bad. At least we know Apache Server is running.

Setup phpPgAdmin

So now we need to configure Apache server to tell it where to find phppgadmin. Edit /etc/apache2/apache2.conf

sudo nano /etc/apache2/apache2.conf

and add the following line to it:

Include /etc/apache2/conf.d/phppgadmin

If you’re not familiar with nano, just press the down key till you reach the end of the document. Copy paste the line above and press Ctrl-O (save), Enter (confirm overwrite), followed by Ctrl-X (exit).

When you have done this, restart apache:

sudo service apache2 reload

Now when you try to access phppgadmin (http://localhost:8080/phppgadmin/). The error message changes:

2015-09-18 20_54_01-403 Forbidden

Basically its trying to say that phppgadmin is there, it’s just that you don’t have permission to access it. So let’s change that now. Enter:

sudo nano /etc/apache2/conf.d/phppgadmin

Comment out (add # at beginning of line) “allow from 127.0.0.0/255.0.0.0 ::1/128” and remove # from the line below it, “allow from all”. Your file should look like this:

order deny,allow
deny from all
# allow from 127.0.0.0/255.0.0.0 ::1/128
allow from all

Save it out and restart apache again, now try to access phppgadmin again. You should be able to see the site now. Though it’s not apparent what you should be doing (contradictory to a more user-friendly web client, phpMyAdmin), click “PostgreSQL”:

2015-09-18 21_01_07-phpPgAdmin

…and it prompt for your login. What’s the username and password? Default username is postgres, but you need to set a password. Let’s do that now. Enter:

sudo -u postgres psql postgres

That should take you to psql:

2015-09-18 21_09_35-MINGW64__d_HashiCorp_Boxes_vagabond

To set a password enter:

\password postgres

It will prompt you for the password, which you will not be able to see it as you type. This will be the password you will use to login to phppgadmin.

To quit psql, enter:

\quit

If you try to login now, it will block you with the message:

Login disallowed for security reasons.

Well, we’re not so bothered about security reasons at the moment, so in git bash enter:

sudo nano /etc/phppgadmin/config.inc.php

and change

$conf['extra_login_security'] = true;

to

$conf['extra_login_security'] = false;

and try to login to phppgadmin again (again, username is postgres). It should work now.

Troubleshooting PostgreSQL

You might encounter this FATAL: role “vagrant” does not exist error:

FATAL role vagrant does not exist Action Controller_ Exception caught

To fix the vagrant role problem, enter this code in ssh mode (make sure you shut down your rails server first):

sudo -u postgres createuser -s -d -r -e vagrant

That should resolve that issue. Note that you need to execute all postgres commands the same way (prefix “sudo -u postgres“). For example:

sudo -u postgres createdb TimeTabler_development

You may also realize that you also can’t access the psql for the exact same error. To work around this, access psql like this:

sudo -u postgres psql postgres

You exit the terminal as such:

\quit

Conclusion

Once you’re done playing around, you can halt the virtual machine by first exiting SSH, then halt the virtual machine:

exit
vagrant halt

 

Advertisements

Rails On Linux On Windows With Vagrant

Rails not running properly on Windows? In this quick tutorial I’ll guide you how to get Ruby on Rails running in Ubuntu in Windows via Vagrant and Virtualbox; it’s the fastest way of getting up with Rails I’ve found to date.

Let’s begin:

Install

You will need to restart your computer after installation for vagrant commands to work.

Setup Vagrant

Create a new folder for your Rails project.

Now inside that folder, right click on on a blank area. If you have git installed properly, you should be able to right click and see a context menu option called “git bash”:

2015-09-18 14_07_41-vagabond

This will open a git bash terminal. From here you will execute all vagrant commands:

2015-09-18 14_09_16-vagabond

Enter:

vagrant init fiercepunchstudios/vagabond

You will see a “Vagrantfile” added to the folder. Now Enter:

vagrant up

This will download a virtual machine (pretty big file, about 700Mb) from atlas.hashicorp.com and save it to:

C:/Users/USERNAME/.vagrant.d/boxes

There you will find a folder for each virtual machine you downloaded.

NOTE: If the download gets interrupted, vagrant will not be able to resume. You’ll have to delete the incomplete box file in

C:/Users/USERNAME/.vagrant.d/tmp

Create Rails Project and Start Running

Once all that is completed, the vagrant up command also launches your virtual machine, though you can’t see it. Enter in git bash:

vagrant ssh

Note you can only do this after you have run vagrant up. This will place you inside the Ubuntu virtual machine (we call this the guest machine, the environment you are currently using will then be the host machine):

2015-09-18 14_16_39-Edit Post ‹ Bruceoutdoors Blog of Blots — WordPress

It should place you inside a “vagrant” folder (notice the vagrant@vagabond:/vagrant), which is the project folder you have created in your host machine. It is here we create a new rails project. So now enter (Don’t forget that full-stop):

rails new .

This also requires an internet connection. After this runs you should see your project folder populated with a fresh new Rails project. So now you can use your favourite IDE, editor (Ahem, Geany) and git client (Ahem, SourceTree) right in Windows! How cool is that?

To run a Rails server, enter in your git bash:

rails server -b 0.0.0.0

Now open up your favourite web browser and go to http://localhost:3000 – you should see this:

2015-09-18 14_25_47-Ruby on Rails_ Welcome aboard

TIP: you can copy paste code by right clicking git bash as such:

2015-09-18 14_27_46-MINGW32__D_HashiCorp_Boxes_vagabond

Any changes you make in your Rails project in your host machine is immediately picked up by the Rails server running in your guest Ubuntu machine.

When you’re done developing on Rails, press Ctrl-C to close the server.

Virtual Machine Management

After you have SSHed into the virtual machine via vagrant ssh, to exit it enter

exit

While you’re in SSH to get out of the virtual machine. Once you are out, run:

vagrant halt

to shutdown the virtual machine, and

vagrant up

to boot it again.

Finally, to completely wipe the virtual machine from the disk destroying all its contents:

vagrant destroy

In git 2.5.2, the above command in git bash causes the error:

Vagrant is attempting to interface with the UI in a way that requires
a TTY. Most actions in Vagrant that require a TTY have configuration
switches to disable this requirement. Please do that or run Vagrant
with TTY.

You either run vagrant destroy in the normal command prompt, or use

vagrant destroy --force

Doing the above will not prompt for any confirmation.

Troubleshooting

Virtualization Technology Problem

You know you got this issue when you have vagrant and VirtualBox installed (or reinstalled a dozen times) and restarted (a dozen times) and yet when you do vagrant up, it states otherwise:

The guest machine entered an invalid state while waiting for it
to boot. Valid states are ‘starting, running’. The machine is in the
‘poweroff’ state. Please verify everything is configured
properly and try again.

If the provider you’re using has a GUI that comes with it,
it is often helpful to open that and watch the machine, since the
GUI often has more helpful error messages than Vagrant can retrieve.
For example, if you’re using VirtualBox, run `vagrant up` while the
VirtualBox GUI is open.

The primary issue for this error is that the provider you’re using
is not properly configured. This is very rarely a Vagrant issue.

Also, when you run VirtualBox and try to start one of the machines there, you have this error:

Failed to open a session for the virtual machine mmutimetabler_default_1448517896835_14736.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED).

VT-x is disabled in the BIOS for both all CPU modes

This issue appears a few times during the course of setting up a couple of different laptops. There are 2 possible cases:

  1. Your CPU does not support Virtualization Technology (VT-x).
  2. Your CPU supports it, but it is disabled.

For the first case, you must be running some really ancient hardware (i.e. Pentium C), and this rails setup is not going to be possible for you until you buy new hardware. This is the case if you boot up to the advanced options in your BIOS and you find that there is no Virtualization Technology option. For the second case, you just need to boot to your BIOS and enable it.

Check out

for further information to resolve your issue.

PostgreSQL

If you are using PostgreSQL, you might encounter this FATAL: role “vagrant” does not exist error:

FATAL role vagrant does not exist Action Controller_ Exception caught

To fix the vagrant role problem, enter this code in ssh mode (make sure you shut down your rails server first):

sudo -u postgres createuser -s -d -r -e vagrant

That should resolve that issue. Note that you need to execute all postgres commands the same way (prefix “sudo -u postgres“). For example:

sudo -u postgres createdb TimeTabler_development

You may also realize that you also can’t access the psql for the exact same error. To work around this, access psql like this:

sudo -u postgres psql postgres

You exit the terminal as such:

\quit

Conclusion

In brief, you just run your Rails application in a Ubuntu machine in your Windows machine. Stay tune for more!

UPDATE: A continuation of this post is up: phpPgAdmin On Linux On Windows With Vagrant.

Using std::unique_ptr as a class member (C++11)

Abstract

For this post I’m going to go through some of the gotchas most people might face when using unique_ptr as a class member (most examples out there only show unique_ptr as a local variable), all accompanied by examples. I will also compare it with shared_ptr.

Assumptions

I’m assuming you know your way round classic/naked pointers, basic memory management and object construction and destruction.

Intro

Unique pointers is type of smart pointer in the C++11 standard that uses the concept of ownership, which meant that only 1 pointer can point to 1 resource (ergo ‘owns’ the resource). In other words only a single pointer is responsible for the destruction of its resource, hence the term ‘unique’.

Theories aside, let’s see some code! To see the source code of the files in this post, just click the link – it will point to a github gist (For example, click Point.hpp below).

Getting Started

In this scenario we’ll be managing a class Point (Point.hpp) from a manager class PointMan. Then add shared_and_unique.cpp to the same directory get started.

So we start with our unique pointer q:

Point::UPtr q;

UPtr here refers to a typedef std::unique_ptr<Point>, you can actually use these interchangeably. Why do Point::UPtr? Because other people do this. And it looks more concise. In fact, if you ever intend to use smart pointers to manage a class, you should add a typedef there.

Now, notice that the unique_ptr p is initialized at the constructor:

PointMan() : q(new Point("q")) {
    q->set(6, 12);
    // ...

well, what if you don’t want to initialize at the constructor? You do this:

r = Point::UPtr(new Point("r"));
r->set(r_x, r_y);

Here is the output of unique_and_shared.cpp:

Image

Ownership Transfering

Moving on to the next example: unique_container.cpp

How does one transfers a unique pointer to another unique pointer? An example is when you have created a point:

Point::UPtr temp(new Point("element-" + ss.str()));
temp->set(i, i*2);

And now you want to transfer this temp Point to a container of unique pointers. Why? Currently the unique pointer is being initialized in a for loop. Exiting or restarting the loop will destroy the resource. That is why the life management of the object needs to be passed to a variable in the class scope. However, doing this:

container[i] = temp;

will result in a compile time error:

unique_container.cpp:16:17: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Point; _Dp = std::default_delete<Point>]’

what does it mean? You can’t use assignment operator from one unique pointer to another unique pointer. Why is this so? Because unique pointers are designed in such a way such that only one pointer can own one resource. However, ownership can be transfered. The following is valid:

container[i] = std::move(temp);

What happens now is that the job of managing the life time of the object is now passed down to the container. So now temp pointer doesn’t point to anything:

assert(temp == nullptr);

Of course, if you don’t want to create temporary variables and move them, you could simply initialize the array element directly:

container[i] = Point::UPtr(new Point("element-" + ss.str()));
container[i]->set(i, i*2);

Non-owning Pointers

Now comes a tricky problem: say there is an element my container of points that I want to designate as the location of the current player on a game board. I need a convenient means to access this particular point in the container. I can’t store this Point as a unique pointer as only one unique pointer can point to one resource. How can I go about doing so?

Well, what you can do is save the index of that container and use it accordingly:

container[player_idx]->set(45, 12);

but it’s rather tedious, messy, and not very expressive. And what about data structures that are not indexed? This creates an overhead simply to get to the resource. What we can do is use a non-owning pointer. Non-owning pointers are classic pointers that do what you would expect normal pointers would do, except they should not manage the life time of the object.

Point *mainPoint;

You assign a raw pointer the resource by using the get() method:

mainPoint = container[1].get();

Now here’s where you need to be careful: do not delete this pointer!

delete mainPoint; // don't do this! no no no!

Your compiler won’t stop you from doing so, but you can cause some really insidious bugs to your program. mainPoint should only serve as a pointer where you can pass around to access the object in the heap. By no reason should you try to manipulate the life time of the resource via this pointer.

But anyhow, I was curious what would happen:

Image

Data corruption! Wohoo! 😀

VS Shared Pointers

So to conclude, here’s the same Pointer manager class, but now using shared pointers: shared_container.cpp

So it’s really a lot easier to read, and more consistent. In fact, Objective C only uses reference counting to handle heap memory. SFGUI, a GUI toolkit built for SFML, forces you to use shared pointers to create GUI components. Seems like shared pointers is one size fits all right? I would think so.

But of course, people would debate that unique pointers perform better than shared pointers, and that shared pointers should be only used as a last resort.

Personally? Shared pointers for the win, man.

So leave a comment if you feel this article could elaborate on certain things or whatever. Bye for now! 😀

Auto-formatting source code using AStyle

Today I talk about how to get AStyle 2.04 the awesome code beautifier working with Qt Creator 3.1, and towards the end share my configuration settings (C++).

Background

I have a particularly strange habit to code: I can’t stand it if it doesn’t look pretty. I make a fuss about formatting, on whether code is readable and properly formatted by consistent and standard code conventions. In short, messy code is disgusting to me.

I doubt I’m the only one like this (:

For awhile now I’ve been manually formatting the code, little seemingly insignificant stuff point of adding spaces between operators and removing spaces around parenthesis, until I realize how it was actually kinda unproductive.

Enter AStyle

I setup Qt Creator via this link. Apparently Qt Creator 3.1 already has beautifier just setting around, but disabled for some reason. You then need to download AStyle and set the exe accordingly.

Then… after that I started wandering around the web wondering where to get a predefined set of formatting options for it. It was actually quite hard to find what I was looking for, truth be told. In the end I just look up the documentation and make it work for me. It wasn’t too bad; was actually kinda fun seeing the code just fixed up itself.

So here is my self-defined style (C++):

style=kr 
attach-namespaces
indent=tab
pad-oper 
unpad-paren 
pad-header 
align-pointer=name
keep-one-line-blocks

My only gripe was that the only way to format the code I have to go through the menu:

Tools > Beautifier > Artistic Style > Format Current File.

I mean, I wanted to format a dozen files at once. Couldn’t there be a faster way? I can’t assign a keyboard shortcut to this command.

…but I’m glad nonetheless 😀

Building GLUI with VS2013 and MinGW in Windows

Note: The dynamic library option doesn’t work. Only static binding is available as of this writing.
One of the example programs given that come with GLUI

One of the example programs given that come with GLUI

This is assuming you’ve already downloaded the GLUI  source code (As of this writing it is v2.35), and you have glut installed.

Visual Studio

  1. open the *.sln file, let it migrate the project file.
  2. Ignore all the errors.
  3. build only the “_glui library” project. Build both debug and release versions. When you build the example programs, choose debug and release build configurations according to what build the glui library uses.
  4. install the library:
    • Header file (glui.h): C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\gl
    • lib file (glui32.lib): C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\lib
  5. Building the example programs from the root project itself won’t work. Start a new empty 32-bit console visual studio project and copy paste the example code to the main.cpp
  6. build and run. You don’t need to link any libraries.
MinGW and Codeblocks
I’m assuming you have MinGW in your environment paths (typing gcc in your command prompt returns ‘no input files’)
  1. The makefile provided is for linux. Use this makefile instead.
  2. open command prompt window in the src directory and run
    mingw32-make -f makefile

    (notice that the example programs are built as well)

  3. install the library:
    • Header file (glui.h): C:\MinGW\include\GL
    • lib file (libglui.a): C:\MinGW\lib
  4. In codeblocks, right click the project and select ‘build options…’
  5. Add the following in linker settings:
    Image
    (the order is important! glui must come first!)
  6. Remember to do this for both debug and release configurations.
  7. build and run. As it is statically binded, no *.dll dependency here.
And there you have it! Now, let’s be honest: not everyone wants to go through the trouble of building the library (I myself had spent a formidable amount of time figuring this out, as silly as I may sound). So to save you the trouble, I’ve precompiled the the GLUI (v2.35) library for you (VC++ 2013, MinGW 4.8.1)!

Automatic Deployment Workflow with Bitbucket(git) in Hostgator

Hostgator has git and svn preinstalled. This enables us to automate deployment! The end result is when you push a commit to bitbucket, the changes are automatically deployed your site… automatically.

For this tutorial I will assume you have
  1. Bitbucket account
  2. Your git repo already uploaded to Bitbucket
  3. sourcetree git client managing your local git repo
  4. root access to your hostgator
  5. SSH access
My bitbucket account is bruceoutdoors, and I’ll be using a private git repo deploy-test.

Set up SSH in hostgator

After you have logged in to the cpanel, use your legacy file manager and set it to home directory and show hidden files.
Create a new .ssh folder if it has not existed.
Download PuTTy if haven’t got it. NOTE: To paste contents to PuTTy, right click on the terminal. Enter something like:
Hostname: gator1111.hostgator.com:1111
Port: 2222
Click “Open”. Login into hostgator with your username and password
run:
cd .ssh
ssh-keygen
We won’t be using any passphrase, so press enter until the SSH Key is generated. This should generate 2 files:
  • id_rsa – private key
  • id_rsa.pub – public key
Create a new file in your .ssh/ directory and name it authorized_keys.
Copy paste the contents of id_rsa.pub inside.
Configure your site’s repo to use SSH instead of HTTPS
Deploy your git repository to your server.
Edit your .git/config in your site directory, change
url = https://bruceoutdoors@bitbucket.org/bruceoutdoors/deploy-test.git
to
url = ssh://git@bitbucket.org/bruceoutdoors/deploy-test.git

Install the public key on your Bitbucket account

Open a browser and log into Bitbucket.
Choose avatar > Manage Account from the menu bar.
The system displays the Account settings page.
Click SSH keys.
The SSH Keys page displays. It shows a list of any existing keys. Then, below that, a dialog for labeling and entering a new key.
copy the contents of the public key file id_rsa.pub.
Back in your browser, enter a Label for your new key, for example, Default public key.
Paste the copied public key into the SSH Key field.
Click the Add key button.

The system adds the key to your account.
Return to PuTTy and verify your configuration by entering the following command:
ssh -T git@bitbucket.org
It should ask you

The authenticity of host ‘bitbucket.org (111.113.10.161)’ can’t be established.
RSA key fingerprint is 11:8p:5b:f2:6f:14:6q:1t:1r:ec:aa:11:11:14:7c:40.
Are you sure you want to continue connecting (yes/no)?

type yes and press enter:
Warning: Permanently added ‘bitbucket.org,111.113.10.161’ (RSA) to the list of known hosts.
logged in as bruceoutdoors.
You can use git or hg to connect to Bitbucket. Shell access is disabled.

This will add a “known_hosts” file in ~/.shh/ in hostgator

This is how your .ssh directory will look like now:
Image
PHP Auto Deploy Script
We will now create a php script that will execute the git pull command without us needing to log into hostgator.
Create a file “git-hook.php” in your site repository with the following contents
<?php
echo "<b>Attempting to pull from git repo...</b> <br>";
exec('git pull', $output);
foreach ($output as $o) {
    echo $o . '<br>';
}
If you go to the URL of your site, it should output something like:
Attempting to pull from git repo...
 Already up-to-date.
Now to set up hooks so that every time a commit is pushed, it’s changes are automatically reflected in our site.
POST Hooks
In Bitbucket, in your repository settings, Select Hooks. Add a POST hook and enter the URL of your git-hook.php script. It should look like this when you’re done:
Image
Now every time you push a commit to bitbucket’s repo, it will automatically deploy your changes.
Reference: