Coreutils Viewer  

I just found Coreutils Viewer, which gives you a progress meter for Linux coreutils. Specifically it can give status on cp, mv, dd, tar, gzip, and cat. It's great for doing a big dd to a flash drive or SD card.

I've used it with good success on Raspberry Pi SD card images.

Leave A Reply

PHP: is_ip() to test if a string is a valid IP address  

I needed to test if a string was a valid IP address or not. PHP has filter_var() which tests for a lot of common things (email addresses, urls, etc) but I can never remember the syntax. Here is a simple wrapper function to match IPv4 and IPv6 addresses.

function is_ip($str) {
    $ret = filter_var($str, FILTER_VALIDATE_IP);

    return $ret;
}

If you just want to match IPv4 addresses:

function is_ipv4($str) {
    $ret = filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);

    return $ret;
}
Leave A Reply

PHP: fakepath() to clean up a file path  

Needed a quick function to remove relative elements from a path. Similar to PHP's realpath() but doesn't require the file to exist on the local filesystem. This also works for URLs.

function fakepath($url) {
    $split = preg_split("|/|",$url);
    $first = substr($url,0,1);

    foreach ($split as $item) {
        if ($item === "." || $item === "") {
            // If it's a ./ then it's nothing (just that dir) so don't add/delete anything
        } elseif ($item === "..") {
            // Remove the last item added since .. negates it.
            $removed = array_pop($ret);
        } else {
            $ret[] = $item;
        }
    }

    // Rebuild the string
    $ret = join("/",$ret);

    // Remove dupe /
    $ret = preg_replace("!/+!","/",$ret);

    // Restore the double / after the HTTP:
    $ret = preg_replace("!(https?:/)!","$1/",$ret);

    if ($first === '/') {
        $ret = "/$ret";
    }

    return $ret;
}
Leave A Reply

CentOS 7 has been released  

CentOS 7.0 has been released and I gathered the versions of some core packages:

Package Version
Perl 5.16.3
PHP 5.4.16
Vim 7.4.160
Firefox 24.6.0
Apache 2.4.6
Leave A Reply

PHP: Assign a default value to a variable  

PHP E_ALL causes a warning to be thrown if you read an unitialized value from an array. For example if you did $debug = $_GET['debug']; but debug is not present in $_GET. This function will conditionally assign a value to a variable that will not cause a warning to be thrown. It also has the added benefit of having a default option that you can specify.

function var_set(&$value, $default = null) {
    if (isset($value)) {
        return $value;
    } else {
        return $default;
    }
}

This allows us to safely assign a variable from the superglobals.

# Default of null if not in array
$debug = var_set($_GET['debug']);

# Specific default of 99
$level = var_set($_GET['level'],99);
Leave A Reply

PHP: is_flat_array()  

PHP supports numeric and associative arrays. PHP's numeric arrays do not have to be sequential, and I wanted a test for that.

function is_flat_array($array) {
    if (!is_array($array)) { return false; }

    $current = 0;
    foreach (array_keys($array) as $key) {
        if ($key !== $current) { return false; }

        $current++;
    }

    return true;
}

I wrote up all the test cases I could think of:

var_dump(is_flat_array(array(1, 2, 3)));                // True
var_dump(is_flat_array(array()));                       // True
var_dump(is_flat_array(array('foo' => 'bar')));         // False
var_dump(is_flat_array(array(0 => 3, 'foo' => 'bar'))); // False
var_dump(is_flat_array(array(0 => 3, 1 => 3, 2 => 3))); // True
var_dump(is_flat_array(array(0 => 3, 2 => 3, 3 => 3))); // False
var_dump(is_flat_array("foo"));                         // False

See also: Test for numeric and associative arrays

Leave A Reply

NASA Radio - Third Rock Radio  

NASA has a cool online radio station called Third Rock Radio. They play an eclectic mix of music and space related tidbits.

Third Rock Radio ShoutCast Stream suitable for VLC.

Leave A Reply

FFMpeg: Encode a VP9 .webm video  

I needed to convert an .mp4 file to a VP9 .webm file. FFMpeg defaults to using VP8 for .webm files, but VP9 is broadly supported by both Firefox and Chrome now so I'd rather use that.

Uses the default, and makes a VP8 files:

ffmpeg -y -i input.mp4 /tmp/output.webm

Force the codec to be VP9:

ffmpeg -y -i input.mp4 -codec:video vp9 /tmp/output.webm
Leave A Reply

Perl: Using modules and @INC  

I was going to write an article about using modules in Perl but Perl Maven did a better job than I ever could have. The article explains all the places Perl looks to find a given module, and how you give it alternate locations. The only thing I would add is that if you print out %INC it will list all the modules that were loaded, and from where.

use Data::Dumper;

print Dumper(\%INC);

Outputs:

$VAR1 = {
          'strict.pm' => '/usr/share/perl5/strict.pm',
          'Data/Dumper.pm' => '/usr/lib64/perl5/vendor_perl/Data/Dumper.pm',
          'warnings/register.pm' => '/usr/share/perl5/warnings/register.pm',
          'vars.pm' => '/usr/share/perl5/vars.pm',
          'overloading.pm' => '/usr/share/perl5/overloading.pm',
          'Carp.pm' => '/usr/share/perl5/vendor_perl/Carp.pm',
          'overload.pm' => '/usr/share/perl5/overload.pm',
          'constant.pm' => '/usr/share/perl5/vendor_perl/constant.pm',
          'bytes.pm' => '/usr/share/perl5/bytes.pm',
          'warnings.pm' => '/usr/share/perl5/warnings.pm',
          'XSLoader.pm' => '/usr/share/perl5/XSLoader.pm',
          'Exporter.pm' => '/usr/share/perl5/vendor_perl/Exporter.pm'
        };

Looks like Data::Dumper has quite a few dependencies.

Leave A Reply

MySQL: Reset the auto increment counter  

In MySQL if you need to reset the AUTO_INCREMENT counter (i.e. After you did a bunch of deletes) you can run the following command:

ALTER TABLE MyTable AUTO_INCREMENT = 924;

This will cause 924 to be the next number given out for your AUTO_INCREMENT column.

Leave A Reply

Fonts: Comic Neue aka "good" Comic Sans  

Comic Sans has long been the whipping boy of bad fonts. There are many other good casual sans-serif fonts available, but Comic Neue is a great free alternative. If you must use a casual font, at least use a good one.

Leave A Reply

Javascript: Random element from array  

Function to get a random element from a Javascript array.

function rand_elem(items) {
    var item = items[Math.floor(Math.random() * items.length)];

    return item;
}
Leave A Reply

Perl: ANSI colors  

Perl's Term::ANSIColor is good but sometime it's overkill. I wrote a function to change colors before your print.

$color = color("13_on_5");
$reset = color("reset");

print $color . "Pink on purple" . $reset . "\n";
# String format: '115', '165bold', '10_on_140', 'reset', 'on_173'
sub color {
    my $str = shift();

    # No string sent in, so we just reset
    if (!$str || $str eq 'reset') {
        return "\e[0m";
    }

    # Get foreground and bold
    my ($fc,$bold) = $str =~ /^(\d+)(b|bold)?/g;
    # Get the background color (if present)
    my ($bc)       = $str =~ /on_?(\d+)$/g;

    my $ret = '';
    if ($bold) { $ret .= "\e[1m"; }
    if ($fc)   { $ret .= "\e[38;5;${fc}m"; }
    if ($bc)   { $ret .= "\e[48;5;${bc}m"; }

    return $ret;
}

The ANSI color numbers can be determined using term-colors.pl.

Leave A Reply

PHP: Get first and last elements of an array  

I often need to grab the first or last element of an array. This method works for either numeric or associative arrays.

$array = array('cats','dogs','fish','horses','squids');

$last  = end($array);   # 'squids'
$first = reset($array); # 'cats'
Leave A Reply

PHP: Test for numeric and associative arrays  

I wanted to test if a PHP array was associative or numeric. Here are two functions that will work for that.

function is_assoc_array($arr) {
    if (!is_array($arr)) { return false; }

    return array_keys($arr) !== range(0, count($arr) - 1);
}
function is_numeric_array($array) {
    if (!is_array($array)) { return false; }

    foreach ($array as $a=>$b) {
        if (!is_int($a)) {
            return false;
        }
    }
    return true;
}
Leave A Reply