Monday, February 29, 2016

Rustic way to import your AngularJS configuration from an external JS file

Many times we want to store our constants/config details into a different file to simplify the deployment process or simply to organise the code.

Here you can see a very basic way to save your app's config file into a different location.

https://jsfiddle.net/sergioloppe/bvajr7bw/

The code is self-explanatory.

Hope helps





Friday, February 12, 2016

How to avoid errors using the function eval in php (under any framework)

Sometimes when you have to evaluate some mathematical expressions with eval it is difficult to control the errors even using try-catch. Here you have a trick to solve that problem:


$calculation = '1/0';

$result = @eval($calculation . "; return true;");
if($result) {
$rule2_val = doubleval(@eval($calculation));
}
else {
return 'Impossible to perform the calculation';
}

Hope helps!


Sunday, January 24, 2016

Using Illuminate/Html in Laravel 5.2


As you know, long time ago, Illuminate/Html was remove from laravel because it is not a core feature. Today I need to use Form for one of my projects and I am going to show how to include in Laravel 5.2. (I prefer not to use Form but you never know).

1) Add to composer.json

"illuminate/html": "5.*"

2) Update your project

composer update

3) Edit the file config/app.php and add to providers

Illuminate\Html\HtmlServiceProvider::class,

4) Edit config/app.php and add to aliases

        'Html'      => Illuminate\Html\HtmlFacade::class,
        'Form'      => Illuminate\Html\FormFacade::class,

5) Check it for example using the code:

{!! Form::open() !!}

{!! Form::text('name', @$name) !!}

{!! Form::password('password') !!}

{!! Form::submit('Send') !!}

{!! Form::close() !!}


If you receive the error:

[Symfony\Component\Debug\Exception\FatalErrorException]                   

  Call to undefined method Illuminate\Foundation\Application::bindShared() 

that means you need an additional step. Laravel 5.2 use singleton instead bindShared which is deprecated. You have to change that in your vendor HtmlServiceProvider as:

/**
* Register the HTML builder instance.
*
* @return void
*/
protected function registerHtmlBuilder()
{
$this->app->singleton('html', function($app)
{
return new HtmlBuilder($app['url']);
});
}

/**
* Register the form builder instance.
*
* @return void
*/
protected function registerFormBuilder()
{
$this->app->singleton('form', function($app)
{
$form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken());

return $form->setSessionStore($app['session.store']);
});
}


Hope it helps





Wednesday, January 13, 2016

Github Two-Factor Authentication on the command line


Today is the day to deploy things and... also the day to set up the Github's two-factor authentication on the command line. In order to be able to work with your repositories once you set up your w-factor authentication follow the next steps:
  1. Log into your Github account and go to Settings
  2. Select the "Personal Access Tokens" tab on the left-hand navigation
  3. Click on "Generate new" personal access token and enter a proper description
  4. Copy the 40 characters long token and use it as your password on the command line
That's all. 

Hope help!

Sunday, January 3, 2016

Installing Ruby on Rails in a Ubuntu/trusty64 Vagrant Box under OS El Capitan

To install Ruby on Rails in a Ubuntu Vagrant Box in a Mac follow the steps below:

1) Download and install vagrant and virtualbox
  - http://www.vagrantup.com/downloads
  - https://www.virtualbox.org/wiki/Downloads

2) Install the Ubuntu box
# vagrant init ubuntu/trusty64

4) Set up the forwarding

# vi Vagrantfile

Add the line in the forwarded port mapping

config.vm.network "forwarded_port", guest: 3000, host: 3030, protocol: 'tcp', auto_correct: true

5) Runing Ubuntu

# vagrant up --provider virtualbox
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'ubuntu/trusty64' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 3000 (guest) => 3030 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default: 
    default: Guest Additions Version: 4.3.34
    default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
    default: /vagrant => /Users/sergio/vagrant_boxes
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: flag to force provisioning. Provisioners marked to run always will still run.


6) Access the virtual machine
# vagrant ssh

Now it's time to install Ruby on Rails. Follow the next steps_
1) Installing dependencies

# cd
# sudo apt-get update
# sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

2) Installing Ruby dev packages

# sudo apt-get install ruby-all-dev
# sudu updatedb

3) Installing rbenv

# cd
# git clone git://github.com/sstephenson/rbenv.git .rbenv
# echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
# echo 'eval "$(rbenv init -)"' >> ~/.bashrc
# exec $SHELL

# git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
# echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
# exec $SHELL

# git clone https://github.com/sstephenson/rbenv-gem-rehash.git ~/.rbenv/plugins/rbenv-gem-rehash

# rbenv install 2.2.3
# rbenv global 2.2.3
# ruby -v

4) If you want to avoid installing the packages documentation execute the following commands

# echo "gem: --no-ri --no-rdoc" > ~/.gemrc
# gem install bundler

4) Installing NodeJS

# curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
# sudo apt-get install -y nodejs

5) Installing Rails

# gem install rails -v 4.2.4
# rails -v

6) Set up PostgreSQL

# sudo sh -c "echo 'deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main' > /etc/apt/sources.list.d/pgdg.list"

# wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add -

# sudo apt-get update
# sudo apt-get install postgresql-common
# sudo apt-get install postgresql-9.3 libpq-dev

7) Create a PostgrSQL user

# sudo -u postgres createuser INSERT_THE_USERNAME_HERE -s
# sudo -u postgres psql
postgres=# \password INSERT_THE_USERNAME_HERE

Now it is time to check the installation creating a rails application.

1) We will use sqlite in this case

# rails new myapp

If you want to use your PostgreSQL server use instead

# rails new myapp -d postgresql 

2) Go to the new app and create the database

# cd myapp
# rake db:create

3) Run the rails server

# rails s -b 0.0.0.0
=> Booting WEBrick
=> Rails 4.2.4 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2016-01-03 16:53:10] INFO  WEBrick 1.3.1
[2016-01-03 16:53:10] INFO  ruby 1.9.3 (2013-11-22) [x86_64-linux]
[2016-01-03 16:53:10] INFO  WEBrick::HTTPServer#start: pid=1956 port=3000


4) Check the server from your local machine at port 3030: http://127.0.0.1:3030

Hope help!



Friday, December 11, 2015

How to add a timestamp to your log files in your bash scripts in Linux


Today I show how to add a timestamp to your log files in your bash scripts. That is easy. In this solution we have to include the function

adddate() {
    while IFS= read -r line; do
        echo "$(date) $line"
    done
}

in your script file and add pipe the command to the function using the systax:

command | adddate

For example:

#!/bin/bash
adddate() {
    while IFS= read -r line; do
        echo "$(date) $line"
    done
}
echo -e "Doing something"
ls -la | adddate

Friday, August 21, 2015

Multiple DB Connections in Laravel 5. How to connect to a different Schema in Postgresql


What happens if you are using Laravel and PostgrSQL and you have to connect to multiple schemas. This post shows how to solve this problem easily in a few steps:



1) Create a new connection in the file app/config/database.php. For example the "test" connection linked to the "your_schema" schema.

...

'connections' => [

...

'test' => [
'driver'   => 'pgsql',
'host'     => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', 'secret'),
'charset'  => 'utf8',
'prefix'   => '',
'schema'   => 'your_schema',
],

...
],

...

2) Create a new Model using artisan. For example: OtherDB model.


use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\DB;

class OtherDB extends Model {

protected $connection = 'test'; // Connection name
protected $table = 'masterscale'; // table name

public $timestamps = false;

public static function loanSearch(){

$query = new OtherDB;

// Example 1: Using Eloquent
//dd($query::all());

// Example 2: Using a raw query
$masterscale = $query::where('risk_class','B1')->get();
foreach ($masterscale as $value) {
echo "
Risk class ". $value->risk_class . " has score " . $value->score;
}

//dd($masterscale);

return;
}

}


3) Create a controller with artisan or use an existing one. For example: otherDBController


use App\OtherDB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class otherDBController extends Controller {

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$loans = OtherDB::loanSearch();
dd($loans);
}

}

4) Create the route to the controller is it does not exist

Route::resource('test', 'otherDBController');

5) Test it :)