Currency Exchange Rate in PHP

We might sometime need to deal with multiple type of currencies when developing e-commerce website. Multiple type of currencies mean we have to take care and get updated currency exchange rate to correctly fix the price of any product. In PHP, we can easily make use of Yahoo Finance to generate currency exchange rate.

<?php

// $from => Currency to convert from
// $to   => Currency to convert to
function get_exchange_rate ($from, $to){
    $currency = [ "from" => $from, "to" => $to ];
    $ticker = $currency["from"] . $currency["to"] . "=X";

    // Retrieve data from Yahoo Finance
    $open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$ticker&f=sl1d1t1c1ohgv&e=.csv", "r");
    $exchange_rate = fread($open, 2000);
    fclose($open);
    $exchange_rate = str_replace("\"", "", $exchange_rate);
    $exchange_rate = explode(",", $exchange_rate);

    // return exchange rate
    return $exchange_rate;
}

$rate_USD_SGD = get_exchange_rate("USD", "SGD");
?>

 

JQuery Parse JSON

JQuery Parse JSON

So, through AJAX, you sent a request to another PHP page that process and return some JSON format response like the following:

{
    "filename":"my_uploaded_file.png",
    "url":"QWwYjb7e8dem2Jh9jBnwKKUMoNud1eUHOYyCYtkDUqkalD1tJvJasCnJT6ucuHlcnLNldw0hTDpFJS7nyAdYKHy5CwUVyK6Ufms2",
    "status":"New file uploaded."
}

So, how are we suppose to parse this JSON in jQuery? Normally, a typical jQuery AJAX request will be as followed:

$.ajax({
    url: "test.html",
}).done(function(json){
    // some function here
});

So, we will want to make sure that the JSON is parsed in done function. To parse the JSON from PHP, we need to get the data from the json variable and after that we can access it just like an array.

var obj = jQuery.parseJSON(json["responseText"]);
// access the filename value from JSON
alert(obj["filename"]);

Fresh Tomcat takes too long to start up?

Fresh Tomcat takes too long to start up?

So you have been working on Ubuntu or Cent OS and installed the Tomcat server just to host some application, but the server just doesn’t seems to startup or freezing. However there is no ERROR message found in the log and you have been wondering what is going on. But sooner after sometime, maybe few minutes up to 10 minutes, the server finally started up. You checked on the log file catalina.out and found out the following line:

INFO: Server startup in 58506 ms

You can speed up the start up of the tomcat server by installing haveged package in both Ubuntu and Cent OS using the following command:

Ubuntu:

sudo apt-get install haveged

Cent OS

yum install haveged

Now, enjoy the faster start up time!

Laravel 5.2 Localization Without Using Prefix

Laravel 5.2 Localization Without Using Prefix

During a process to build a web application, it can sometime unavoidable to deal with localization of the application. Having multiple localizations can be beneficial to your web application as users can surf in their preferred language.

If you are using Laravel framework to build the web application, you might be wondering on how to properly set up multiple localization on your web application. There are multiple ways of doing it, but we will focus here on changing locale without using prefix in the URI segment.

You will need to use session in conjunction with a middleware. All you need is a controller and a middleware. Make sure you have appropriate locale file in resources\lang\ directory.

App\Http\Controllers\LangController.php Method

class LangController extends Controller
{
    public function setLang($locale)
    {
        // 1. store selected locale
        Session::put('my_project.locale', $locale);

        return back();
    }
}

App\Http\Middleware\Language.php Method

class LocaleMiddleware
{
    public function handle($request, Closure $next)
    {
        $default = config('app.locale');

        // 2. retrieve selected locale if exist (otherwise return the default)
        $locale = Session::get('my_project.locale', $default);

        // 3. set the locale
        App::setLocale($locale);

        return $next($request);
    }
}

Next, you will need to register the middleware in the kernel, under route middleware.

App\Kernel.php

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'lang' =&amp;amp;amp;gt; \App\Http\Middleware\Language::class,
    'auth' =&amp;amp;amp;gt; \App\Http\Middleware\Authenticate::class,
    'auth.basic' =&amp;amp;amp;gt; \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' =&amp;amp;amp;gt; \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' =&amp;amp;amp;gt; \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Lastly, remember to register the middleware on the controller where you want localization to happen.

Create a triangle using CSS

Create a triangle using CSS

Do you know that you can easily create a triangle without using any image? You can use CSS styling to create triangle with up, down, left and right directions easily. Here is how you do so:

First of all, we will need a div element which will be styled into a triangle later.

<div class="triangle"></div>

The idea is a box with zero width and height. The actual width and height of the arrow is determined by the width of the border. In an up arrow, for example, the bottom border is colored while the up, left and right are transparent, which forms the triangle. The CSS which form the triangle is as followed:

div.triangle {
    width: 0;
    height: 0;
    border-top: 15px solid transparent;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-bottom: 15px solid black;
}

Now we will have an up arrow triangle like this:

You can change the color of the triangle by adjusting the border color of the div element. You can also change the size of the triangle by adjusting the border width.

NetSpeedMonitor – Know your bandwidth usage

These days, even the most powerful PC is not of much use without a solid Internet connection. Even if your Internet connection is superior, do you even know what is happening on your network connection? Can you identify which applications on your computer are connecting to the Internet, where they’re connecting to?

NetSpeedMonitor is a small, simple, unobtrusive donationware network monitoring utility that could answer all of the questions above. Unlike other network monitoring utility, NetSpeedMonitor doesn’t use a window, it just sit silently in the system tray.

net-speed-monitor

To display connection speeds, NetSpeedMonitor creates a new toolbar for the Windows Taskbar. It sits right next to the system tray (where you can find your clock and tiny tray icons), and displays download and upload speeds. Whenever you hover the cursor over the toolbar, NetSpeedMonitor shows a custom pop-up with the current upload and download bitrates (which you can see on the toolbar as well), as well as montly, daily and session transfer tallies, so you know how many bytes you uploaded and downloaded over those time spans.

net config

NetSpeedMonitor’s toolbar can be customized so it takes up minimal horizontal space, and works well with vertical taskbars. The configurations window can be accessed by right clicking on the NetSpeedMonitor’s toolbar.

net connection

Apart from that, NetSpeedMonitor can also show which processes on your system use TCP and UDP connections, and where those connections lead. This is the most technical of all three dialogs, and it shows a list of running processes which have established, listening, or closed TCP and UDP connection endpoints. Basically, it shows you a list of applications who are trying to go online, as well as where these applications are trying to connect. The list is a bit tricky to use, because some of the processes are marked as Unknown; NetSpeedMonitor can’t find their name. It does, however, report their PID (process ID), and you can then run Process Explorer or Task Manager and find what process that PID belongs to.

While the Connections dialog is mainly useful for developers and/or very technical users, the rest of NetSpeedMonitor is easy, fast, and friendly.

NetSpeedMonitor can be downloaded from this link.

ThrottleStop – No More CPU Overheating!

There is always heat problem when we come to heavy computing or gaming with our computer. This happens even more frequently when your computer is not properly vented. Overheating not only causes uncomfortable temperature for user when using the computer, it also affect the performance of the computer, a.k.a. throttling, or computer components will break down eventually.

There is a tool called ThrottleStop which is developed by TechPowerUp, which is the famous developer for GPU-Z, EVEREST benchmarking software and also Real Temp.

SIfnCwY

ThrottleStop is a small application designed to monitor for and correct the three main types of CPU throttling that are being used on many laptop computers.

The left side of ThrottleStop contains a variety of options which can be used to bypass CPU throttling and on the right side is a Monitoring panel that shows you the current state of each thread on your CPU.

Some laptops are using clock modulation and multiplier reductions to lower the performance and power consumption of your computer. This is done deliberately to either allow your computer to run cooler or to allow your laptop to operate with a power adapter that is not sufficient to fully power your laptop and recharge its battery at the same time.

When using ThrottleStop, it is strongly recommended to monitor power consumption at the wall with a Kill-a-Watt meter or similar device and make sure that you don’t exceed the power capabilities of your power adapter. Use of ThrottleStop to bypass these throttling schemes is at your own risk and can result in permanent damage to your power adapter or computer or both which may not be covered by your warranty.

How to use ThrottleStop to stop CPU from overheating?

A lot of heat is generated when CPU is under heavy load. This is due to the Turbo Boost feature offered on the CPU chipset, which allow the CPU to run faster than the default frequency. For example, a CPU with 2.4GHz may be boosted up to 3.2GHz during heavy load which introduce a lot of heats. With ThrottleStop, we may set the CPU multiplier to a lower value to prevent the clock from exceeding the value.

If you set the multiplier value below a certain value where the Turbo Boost will not happen, which in our case 24 compared to Turbo Boosted 32T, overheating will happen less, and you will notice your CPU temperature will drop to a lower maximum limit. However, you may experience slightly slower CPU performance, which is due to the fact that your CPU performance is limited to 24/32 = 75% of the maximum CPU performance, which mean 25% less heat generated! This will help a lot if you suffer CPU throttling during gaming due to CPU overheating and Intel safe measure to prevent CPU from overheating (which is to slow down the CPU clock based on the CPU temperature).

If you are interested with the program, you can download ThrottleStop from here.