Subnet Calculator in 9 Lines of PHP

I’ve been spending a lot of time studying for my Microsoft 70-642 exam, an important part of which is subnetting.As an intellectual exercise I wrote a subnet calculator. Enjoy:

1
2
3
4
5
6
7
8
9
 function subnet($hosts)
 {
	$bits       = decbin($hosts) + 2; // Add 2 for Network ID and Broadcast
	$hostBits   = strlen($bits); // find how many bits it takes to represent it
	$cidr       = 32 - $hostBits; // Find slash-notation
	$binaryMask = str_repeat('1', $cidr) . str_repeat('0', $hostBits); // Subnet in binary
	$subnet     = implode('.', array_map('bindec', str_split($binaryMask, 8))); // Subnet in dotted-decimal
	return array('hosts' => $hosts, 'hostBits' => $hostBits, 'cidr' => '/' . $cidr, 'binaryMask' => $binaryMask, 'subnet' => $subnet);
 }

How I Got Banned From Reddit

Important: I’m not posting this to complain about how I got banned from Reddit. In retrospect I can, albeit somewhat begrudgingly, admit that I probably had it coming.  But just as I always do I’m using my blog as a forum to help people solve IT problems. Only this time around, the problem happened to be one of my own.

Background

Lately I spend a lot of time on /r/techsupport posting solutions to IT problems asked by other users.  Sometimes I post my own problems, and when I think others will find them useful I’ve submitted links to posts on this blog.  Several days ago I got involved with an /r/techsupport question about editing PDF documents.  This is a problem that I’ve helped numerous people solve at work, so I did what I always do: I blogged about it so the next time the problem comes up I can point the user to the link.

The problem arose when I posted the link back to /r/techsupport.  It was immediately down-voted to oblivion, and soon after a few individuals wrote comments accusing me of posting blog spam.  Another individual posted that I had been banned from Reddit. The fact that my profile page is now a 404 error confirms this.

Why I Was Banned

If you’ve read my blog in the past then you know it’s far from blogspam in the commonly understood sense. I almost exclusively post original content and, on the few occasions when I do post links to another author’s information, it’s because I have something to add to it and I always attribute the original sources. Unfortunately for me, that’s completely irrelevant in this situation.

I was accused of blog spamming and subsequently banned from Reddit because I posted a link to my personal blog in /r/techsupport. This is against their rules, but the only way I would have known is by lurking long enough to infer this rule from the actions of other community members. I spent plenty of time as a reader in /r/techsupport.  But what I found out was that I wasn’t really listening.

By the definition of some redditors I am, indeed, a blog spammer.  Do I agree with their definition?  Not entirely; but if I want to play in their sandbox, I’m going to have to learn to play by their rules.

Advice for Surviving Reddit

I love Reddit and in some way I felt a little betrayed when it lashed out at me for reasons I couldn’t quite comprehend. So learn my mistakes, prospective redditors, and consider my suggestions for surviving and thriving on Reddit.

 

Read and Understand Reddiquette

I (sort of) broke one of these rules by posting links in the subreddit that I did, in the manner that I did. Specifically,”Feel free to post links to your own content (within reason). If that’s all you ever post, and it always seems to get voted down instantly, take a good hard look in the mirror — you just might be a spammer.”

Learn by Lurking.

This advice stems from back in the days of Usenet Newsgroups but still holds true today. Take the time to get familiar with the subreddit you plan to post to.  Get to know what sort of posts are acceptable to it’s users and the format in which they expect to see them. If you post something that’s off-topic or otherwise considered inappropriate to the venue, expect to be down-voted, ridiculed, verbally assaulted, or even banned.

Learn your Subreddit’s Code of Conduct

Just like the real world, many Reddit communities have completely different sets of social mores. Some reddits are obvious and even have pages dedicated to what and how to post. Others are not so obvious, so it’s important to follow the previous advice until you get to know the written as well as unwritten rules of your Reddit community.

I found this out the hard way.  Self-congratulatory and self-promoting links are completely acceptable in certain Reddit communities such as /r/diy provided they serve some function other than stroking one’s own ego, and even those are accepted under the right circumstances.  /r/techsupport frowns upon them in a big way. However a moderator told me it’s completely acceptable to post a link to one’s own content, provided it’s a relevant part of a longer post that either asks or answers a question, like this. Get to know these sorts of rules before you post and if you’re unsure, you may consider asking a moderator.

Don’t Take Yourself Too Seriously

Do not post to Reddit hoping for a future filled with pats on the back and “atta boys.”  If you post to Reddit (or just about anywhere else on the Internet), you’re begging for criticism.

I recently saw an individual cross-post a home-brew garden watering system between /r/diy and /r/gardening.  On /r/diy the post was met with mostly respectful criticism and advice on how to correct a couple of beginner mistakes. On /r/gardening, however, the post and author were violently ripped apart. As far as I can tell, it was because /r/gardening expects a higher-than-amateur quality in the gardening content that’s posted there.There also were clearly some community bullies there, just waiting for someone to berate. The user user who posted it handle the criticism with a grace that was not afforded him by his critics.

The point is, Reddit is as nuanced as the people who use it. Most users are courteous individuals, but there is a rotten banana in every bunch, and they are waiting to rip your post apart.  Don’t take it too seriously. Take the high ground in dealing with these people, and don’t be afraid to use the “report” button when they go too far.

 

Summary

I love Reddit and I love blogging.  Right now I’m still trying to strike a balance between these two fascinations and understanding how they can compliment each other.  I’m far from having it figured out, but this experience has taught me a lot.  Are you a Redditor with a personal experience or some advice to share?  I’d love to hear what you have to say on the subject.

JavaScript Errors in Internet Explorer? It’s Probably a Comma’s Fault

This is a well known bug/feature in Internet Explorer but I’d like to share it again for the sake of beginners, as well as seasoned programmers who forget about it from time-to-time. If you’re testing JavaScript code that seems to work fine in Firefox, Chrome or Safari but chokes in Internet Explorer, a stray comma is probably to blame. Consider the following code:

(Click to Execute)

    arr = [1, 2, 3];
    for(i = 0, c = arr.length; i < c; i++) {
        alert(arr[i]);
    }

This code is dead simple. We create an array with three elements, iterate through that array with a for loop, and display each value. Nothing complicated, and it should run fine in any browser. Now consider a similar block of code:

(Click to Execute)

    arr = [1, 2, 3, ];
    for(i = 0, c = arr.length; i < c; i++) {
        alert(arr[i]);
    }

Notice the different: in the first block of code the array was defined as [1,2,3]. In the second block it is defined as [1,2,3,] with a trailing comma. Firefox, Chrome, and Safari will produce the same output. Internet Explorer, on the other hand, sees a fourth array member which with a value of undefined. Think about it in the context of a complicated JavaScript application. Accidently adding an extra comma to the end of an object or array can produce errors deep within your code or within the libraries they depend on, such as jQuery or ExtJS.

So remember, when troubleshooting JavaScript errors in Internet Explorer, always check for trailing commas, or use a utility like JSLint to find them for you.

Removing Keys from an Array in PHP

Removing one or more keys from an array in PHP seems like something that should be easy to do. Yet out of the 70+ array functions in PHP, there is no single function to do it. But here’s the easy way:

Use array_diff_key()

PHP has a function called array_diff_key($array1, $array2) that returns an array with all of the keys (and their values) from $array1 that don’t also occur in $array2. We can use this to quickly cobble together a solution:

<?php
 
function array_remove_keys($array, $keys) {
 
    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }
 
    return array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, array('address2'));
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/

Works great! But it’s not quite complete. There is absolutely no error checking, and passing an array as the second parameter isn’t the most convenient way to operate. Let’s give the caller the option of passing either an array, or a comma-separated list of keys to delete.

<?php
 
function array_remove_keys($array, $keys = array()) {
 
	// If array is empty or not an array at all, don't bother
	// doing anything else.
	if(empty($array) || (! is_array($array))) {
		return $array;
	}
 
	// If $keys is a comma-separated list, convert to an array.
	if(is_string($keys)) {
		$keys = explode(',', $keys);
	}
 
	// At this point if $keys is not an array, we can't do anything with it.
	if(! is_array($keys)) {
		return $array;
	}
 
    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }
 
    return array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, 'address2');
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/

What is HTML?

Most people have heard the term HTML and have a general idea that it has something to do with the web.  But as someone who wants to create the web you need to have a better understanding.  This article will explain what HTML is and why it’s important, and it just might do it without boring you into a coma.

What is HTML?

Defining HTML is by far the most boring part of understanding it, so lets keep this brief. HTML is the format in which documents on the web are written. HTML stands for HyperText Markup Language. Let’s break that down into something digestible:

  • HyperText – Text with interactive references to other text or content (or, Words on Ritalin). These so-called references are what you probably know as hyperlinks.  Hyperlinks are what allows the web to be a web in the first place: they link documents together. Without Hyperlinks the documents, videos, and images that make up the web would be likes islands with no trade routes between them. In other words, Hyperlinks are what allows us to surf the web, and are responsible for countless hours of lost productivity (well, hyperlinks and FarmVille).
  • Markup Language – HTML is technically a computer language, but don’t let that scare you: it’s really easy! HTML is a very specialized language called a Markup Language which is used for describing, annotating, and structuring text. HTML exists for the same reason we space and indent paragraphs, quotes, and other sections of a written document: it provides context to the content, and breaks up long sections of text into manageable chunks. HTML also allows us to insert interactive content into our documents like images and videos.  So while writing HTML may sound as fun as diagramming a sentence, the payoff for understanding it is way cooler.

But keep this in mind: with the exception of people like us who create the web, humans don’t read HTML; web browsers do! HTML is designed to help browsers (like Firefox, Chrome, Safari, or Internet Explorer) understand our content.

HTML is a Standard (That Everyone Interprets Differently)

HTML was created by a physicist names Tim Berners-Lee, but today is managed by a group called the World Wide Web Consortium, or W3. The W3 is a group of member organizations (still led by Berners-Lee) charged with creating and improving web standards.  The W3 publishes the HTML standards and leaves it up to the web browsers to interpret them.  The important thing to remember about HTML standards are:

  • HTML is still changing.  The language has gone through a number of versions over the years, the latest (and as of yet non-standard) version being HTML 5.
  • Not all web browsers interpret and display HTML the same way. This is one of the most difficult hurdles to pass in publishing on the Internet, and removing that room for interpretation is one of the reasons that HTML standards change.

As someone interested in creating HTML content and publishing it on the web, it’s important that you keep your finger on the pulse of the W3 and the web in general.  HTML and web browsers change rapidly, and you’ll have to learn to change with it.

Summary

HTML is a specialized computer language for describing and structuring text.  It’s a form of hypertext, which is a specialized type of document that provides references to other documents and content called hyperlinks.  HTML is a standard controlled by the World Wide Web Consortium, but it’s up to browser manufacturers to interpret that standard, so the way your HTML documents are rendered can differ from browser-to-browser.

Was that so difficult?  Let’s move on to something a little more interesting.

For More Information

[amazon_link id=”006251587X” target=”_blank” ]Weaving the Web: The Original Design and Ultimate Destiny of the World Wide Web[/amazon_link] [amazon_link id=”0596527322″ target=”_blank” ]HTML & XHTML: The Definitive Guide (6th Edition)[/amazon_link]