TrueJournals

Tag: programming

If you’re writing C++, write C++!

by on May.06, 2014, under programming

Today, I came across some C++ that looked something like this:

std::string output = someFunctionCall();
if(strlen(output.c_str()) > OUTPUT_LIMIT) {
    // Trim output
}

Now… I get it. C++ is not an easy language.  C++ can be especially difficult if you’re coming from C and you’re not used to object-oriented programming, or if you already know how to do what you want in C.  But please, use the right tool for the job.

The code I came across wasn’t quite this simple (the string did not come from directly above the if statement, but the if statement is exactly the same, differing only in variable names).  I’m guessing that, at some point, this code was written in C before the project moved to C++.  However — someone, somewhere, at some point came across this if statement when refactoring, and decided that the right thing to do was to keep the “strlen” call and keep using C-style strings.

That means this person didn’t think “I wonder how I get the length of a string in C++”.  The person who refactored this line of code did not care what the intention was — they just cared to replicate EXACTLY what it was doing.

To make matters worse, someone decided that “output” should use NULL characters as a field delimiter of sorts.  I’m guessing that, in the original C code, these delimiters were properly removed.  However, this did not happen in the C++ refactor.  There was a NULL character about 20 characters into output, which meant that the call to strlen would always return 20.  It’s nice that C++ strings allow NULL characters — it’s bad when you then try to treat them as C strings.

Now, I won’t comment on the validity of using NULL characters as a field delimiter (it’s a bad idea… please, just don’t do it), but whoever decided that this line of code should not behave in the same way but instead execute the same calculation was just wrong.

Refactoring code is hard (especially if you didn’t write it yourself).  Programming is hard.  But, please, if you’re modifying someone else’s code, try to understand the intention of the code more than just the literal function calls.  The author of the original code clearly meant to execute the trimming code if the length of “output” was greater than the limit, and output.size() is the best way to check for that.

Leave a Comment :, , more...

Let the Language Work for You – Part 1: C++ Destructors

by on Oct.10, 2013, under programming

I recently came across a programming design pattern I hadn’t thought of, and that inspired me to write at least one blog post.  So, I introduce this post which may or may not start a series of posts, entitled “Letting the Language Work for You”.

The idea behind this series is this: programming languages have become very advanced, possibly more than most people realize.  There are many things you may be doing now in your programs that are simply extra work that you don’t really need to do.  Instead, you should let the language do the work for you.  These posts will (hopefully) help you take full advantage of your programming language to avoid extra work, and hopefully keep out some bugs.

For part 1, let’s look at destructors in C++.  Before we get started, I’ll note that this post is very much inspired by Boost’s ScopedLock pattern.  If you know where this is headed just by reading that, I’ll understand if you decide you don’t need to read what I have to say.  Otherwise, if you use an object oriented language, I’d encourage you to keep going.

(continue reading…)

Leave a Comment :, , more...

Google Drive Form Report Generation

by on Jan.22, 2013, under programming

Printing form responses in Google Drive is an awful experience.

That’s a strong statement, but it’s the truth.  Forms in Google Drive are used for so much more than simply numerical responses, with some being used for surveys, sign ups, and other data that just doesn’t fit properly in a spreadsheet.  Yet, that’s the only format Google presents this data in.  While spreadsheets are fantastic for numerical data analysis, they do little for analysis of open-ended survey responses.

And this statement even makes the assumption that you’re attempting to read the data off a computer screen.  Want to print out the data to keep a hard copy (or just to reduce eye strain from your computer’s back light)?  Forget it!  You can attempt to print the responses in landscape, but you’ll end up with an unorganized mess of papers which doesn’t really solve the original problem.

So, how can we get the data from the Form into a format that’s pleasant to read, and easy to print?  We use a script!

The Google Apps scripting engine is amazing.  I’ve previously used it to create rudimentary conditional formatting in Google Docs.  Now, I wanted to play around with it more and generate single page(-ish) reports of individual responses to a Google Drive Form.  I say “-ish”, because the script doesn’t guarantee a single page.  The end length is simply based on the response length and number of questions.

So, how do you use this script?  Just find it in the script gallery!  Searching for “Report Generator” should find the script and allow you to install it easily!  Once installed, a new menu — “Report Generation” will pop up on your spreadsheet.  Simply select the row you want to generate a report for, and choose “Generate Single Report” (or generate all at once!).  In a few moments, you’ll have a new folder in your document list, and a doc and/or PDF of the report.

The script has a few configurable options, which are for the most part self-explanatory.  I’m working on getting some documentation up at the script’s help page, but that may take me some time.  I also plan on adding more features to the script: the ability to change the folder name, change the resulting document names, change the formatting of the output, etc.  I’ve never published a script to the gallery before, but I’m hoping I’ll just be able to update the script when I have new features ready.

So, if you’re looking for a good solution to printing out responses to Google Drive Forms, check out “Report Generator” in the script gallery!

Leave a Comment :, , , , , more...

Building a Better WHD Notifier

by on Jun.29, 2012, under programming, technology

At my work, we use Web Help Desk to track support tickets.  It’s a very nice, very slick piece of software, and from my understanding, version 10.2 implements an API going forward.  Unfortunately, we use version 10.1.10.1, which doesn’t have the same API.

The problem I ran into was this: often, there are other tasks to be completed, so I’m not just staring at the WHD ticket queue the entire time I’m at work.  However, if a client logs a ticket, I have no way of being notified without going to the web help desk page and checking manually.  This results in one of two things happening: either I check the ticket queue every few minutes, breaking my workflow on other projects, or a ticket doesn’t get responded to for a while.

I wanted a way to be notified of new or updated tickets that pop up without having to continually go back to the WHD tab of my browser to actually check for new or updated tickets.  Unfortunately, without an API, I thought this was going to be difficult.  Until I found this: a WHD Notifier for Chrome.

However, this still didn’t quite achieve what I was looking for.  While this did provide me with a notification of the number of new or updated tickets within the browser, it didn’t notify me when this number changed. So, I still had to watch my web browser, and even then, continually check this small, inconspicuous number in the top-right corner of my screen.  Since Chrome extensions are simply Javascript, HTML and CSS, I decided to try my hand at modifying it to better suit my needs.

Here’s the list of things I needed:

  1. Pop-up notifications of a change in the number of new/updated tickets (like in Gmail).
  2. The ability to not save username and password.  The computers share a single profile between multiple users, so I don’t want individual passwords saved past the browser session.
  3. (Optional, if I could figure it out) Grabbing login info from the WHD web login, so you don’t have to go into the extension options every browser session.

After some coding, a lot of trial and error, and a lot of research, I was able to meet all three goals. If you’d find it useful, you can download WHD Notifier version 1.5.  Simply configure it with your WHD URL, choose what to display/be notified of, and you’re good to go.  If you login to web help desk, the notifier will grab that login information and start updating.

If you’re interested in seeing the source code for this extension, you can find a zip of the source here.  I’ll see if I can throw it up on GitHub later today or this weekend.  There’s some interesting things being done here — submitting the login form in WHD sends a call to forms.submit() instead of going through the normal submit procedure — this means that I couldn’t simply add an onsubmit handler to capture the login information.

Instead, I inject another piece of JavaScript into the page which overrides the submit() method for all forms.  This calls chrome.extension.sendMessage to message the background page with the username and password, then proceeds to call the submit() method I had overridden.  You can find the form handling things in autoLogin.js and autoLogin2.js.  I had to inject autoLogin2.js on the page because chrome content scripts aren’t allowed to override prototype methods.

If we ever update our WHD installation, I’ll try to update this extension again to use the new API — I should be able to add some more features with that, too.  For now, this should work for all versions of WHD 10.0.8 or later.

Update: Code is now on GitHub

Leave a Comment :, , , , , more...

Automatically Associating Label and Input, and Setting Width

by on Jun.26, 2012, under technology

When creating forms in HTML, one of the best practices is to always use <label> to associate the labels with their form fields.  However, this creates the complication of needing to give each label the “for” attribute, and perhaps wanting some extra magic to set the width of each label so that all the form fields are lined up.  Recently, I decided to play around with form fields like this a little to see if I could automate this process using jQuery.

Here’s what I came up with:

var w = 0;
$("label").each(function() {
    if($(this).width()&gt;w) w=$(this).width();
    // Assume the input immediately follows the label
    var input = $(this).next();
    input.prop('id', input.prop('name'));
    $(this).prop('for', input.prop('name'));
});
$("label").width(w+10);
$("label").css('float', 'left');

And here’s what it does: first, it loops through each label on the page looking for the maximum width. When it finds that, it sets all labels to have a width of (maximum width)+10px. The extra 10px are just so the label and field aren’t directly on top of one another.

In the same loop, this code associates the label with the field next to it. For my sake, I made the assumption that I will always have <label>…</label><input />. If this is not the case, the code will associate the label with the wrong field. It simply sets the next element’s id to be the same as its name, and sets the label’s “for” property to be the element’s name, also.

Use this with caution. If you’re not careful, you could end up with duplicate IDs (a no-no). There are other reasons this code isn’t necessarily a good idea, but it’s good enough for me. For a page with a lazy HTML coder, this will work perfectly.

Bonus: Add input.prop(‘placeholder’, $(this).text()); inside the loop to also set the “placeholder” text to whatever the label is. You could also detect if the browser supports “placeholder”, and hide the label if it does:

var w = 0;
$("label").each(function() {
	if($(this).width()>w) w=$(this).width();
	// Assume the input immediately follows the label
	var input = $(this).next();
	input.prop('id', input.prop('name'));
	input.prop('placeholder', $(this).text());
        if('placeholder' in document.createElement('input')) $(this).hide();
	$(this).prop('for', input.prop('name'));
});
$("label").width(w+10);
$("label").css('float', 'left');
Leave a Comment :, , , , more...

How I Wrote My First Software Crack

by on Jun.22, 2011, under technology

Before I really get into this article, I need to place a couple notes here:

  1. This is a semi-technical post.  It assumes some knowledge of programming and how software works, but I’ll try to keep it as simple as possible.
  2. I’ve done my best to not give away what application I’m writing about.  This is on purpose.  While this is an interesting look into hacking software, getting around DRM is, to the best of my knowledge, illegal.  This article is actually about reverse-engineering, not cracking software.
  3. If the author of this application finds this blog post and thinks I’ve given away too much, they should please e-mail me and I’ll take it down.  If you think this article is about your application and it is not, however, I will not remove the article.
  4. If you like software, buy it!  Seriously… software developers need to eat, too!

Now, let’s get into the bread and butter of this article!

(continue reading…)

1 Comment :, more...

Why Did Wave Die so Quickly?

by on Feb.15, 2010, under technology, thoughts

A while ago, I was super excited to finally get a Google Wave invite.  Today, I barely ever used the service.  I just open it every now and then to see if anything’s happened.  Generally, it hasn’t.  But… Google Wave had so much potential!  It was touted as a killer web application!  What happened?  Wave had so much momentum, but it seems to have crashed, and gone into one of those experiments that Google toyed around with, but no one really cares about anymore.

First off, let me say that whether Wave succeeds or not makes little difference for Google.  Google is a company with enough resources to work on a major product, even if that product is a failure.  Google wanted Wave to replace e-mail.  This is where the whole “Federated Wave Servers” idea came from.  In order for Wave to be the new standard, companies had to be able to run their own Wave servers — Google couldn’t control it.  Besides that, Google already controls a good chunk of the e-mail market with GMail, so this was mostly a fun experiment for them.

But, still, it seems like something that should have succeed… or, at least, lasted a good amount of time.  But, Wave has quickly lost momentum and died in everyone’s mind.  The problem is that Google stopped innovating, and the Wave server never became very popular.  I don’t believe there have been any feature additions to Wave since it launched, and I’m not sure there’s any good source other than Google Wave to get a Wave account.

Wave died because Google seems to have abandoned it.  They released a product, and they appeared to have stopped working on it.  Wave is something Google needed to not only push to corporations, but also continue innovating, and releasing new features, and this never happened.  Google was unable to explain to potential customers why they need Wave, and this is where it failed.  I think this is slightly unfortunate, but I’m not very surprised.  While e-mail is antiquated, it still works, and it’s going to take a lot of push in order to move away from it.  Google didn’t seem to have any major corporations backing Wave, which also contributed to the failure.

Who knows… maybe we’ll see Google attempt to revive Wave with some new features.  Maybe it will come back for a couple months… But Google will have to work really hard to get the momentum and excitement about Wave going again.

I do, by the way, have 12 Wave invites.  I suppose you can comment here or contact me if you want one.  That’s a dangerous statement to say on the Internet.  Although Wave has died, I have a feeling there are people who never got in on the game, and are still looking for invites, only to find a product that no one uses.

Leave a Comment :, , , , more...

Understanding n810 NJoy Programming

by on Jun.14, 2009, under maemo

I think this would be a good place to archive my explanation of NJoy programming.  I was asked about how the patterns in mce.ini for the n810 work, with PatternError given as an example.  This was my reply:

The different sections of the line are separated by semicolons. So, priority is the first part, then a semicolon, then the “ScreenOn” value, then a semicolon, etc. So, I’ll use your example and point out each section of the programming.

0;1;0;40002000200040ff200020000000;0000;0000

To make this easier, I’m going to assign an index to each section of the command. I’ll split the string up by the semicolons. We’ll say the first character (a zero, in this case) has an index of 1. The second part of the split (a one), has an index of 2, etc, etc.

0;1;0;40002000200040ff200020000000;0000;0000
Index 1 defines the priority. If two patterns trigger at once, items with a higher priority (lower number for this section), take precedence, because only one pattern can be going at once. Since the priority is 1 (0 being the highest priority, 255 being the lowest), this pattern will display instead of almost any other pattern (the exception is patterns that have a priority of 0)

0;1;0;40002000200040ff200020000000;0000;0000
Index 2 defines whether or not the pattern should fire based on what state the display is in. In this case, it’s a 1, which mce.ini tells us means “show pattern even when the display is on”. So, this pattern will display no matter what.

0;1;0;40002000200040ff200020000000;0000;0000
Index three gives the timeout. This can tell the pattern to stop firing after a certain amount of time. In this case, it’s a zero, which means that the pattern will never stop firing (unless it’s told to).

0;1;0;40002000200040ff200020000000;0000;0000
Index four starts the actual programming of the LED. Index four gives the programming of the RED LED. It also gets a bit more complicated here. We have to split this section up into strings of four characters each in order to understand the programming. This is what the pattern looks like, split into four-character strings, with each string separated by a pipe (|):
4000|2000|2000|40ff|2000|2000|0000
So, there are seven different commands given to the red LED. Let’s take a look at them one by one:

  1. 4000 — This sets the brightness of the LED (anything starting with a 40 will change the brightness). I believe this tells the LED to turn off (0 brightness). I believe that ff would be 100% brightness.
  2. 2000 — This bumps the brightness up over a certain amount of time. This gets REALLY confusing. The first two characters, 20, tell how long it should take to change the brightness. 20 is in the 01 – 3f range, so we get “short” steps. If I understand this, we get 19 “short” steps of time ~0.49ms, so this should take about 9.31 milliseconds. The next two characters, 00, defines how many steps in brightness the LED should take. 00 is no change, so the pattern will pause for about 9.31 milliseconds.
  3. 2000 — Because this is the same command as above, this will also create a 9.31 millisecond pause.
  4. 40ff — Again we see a 40. This says to change the channel brightness. This time, we’re changing it to ff, which should be 100% brightness. So, this command turns the LED on.
  5. 2000 — This creates another 9.31 ms pause.
  6. 2000 — This creates another 9.31 ms pause.
  7. 0000 — This tells the pattern to loop (“jump to the start of the pattern”).

So, the red LED will turn off, pause for (2*9.31 ms =) 18.62 milliseconds, turn on, pause for another 18.62 milliseconds, then loop.

0;1;0;40002000200040ff200020000000;0000;0000
Index five gives the pattern for the GREEN LED. This is a very exciting pattern. It simply tells the pattern to repeat again and again and again. So… nothing happens with the green LED.

0;1;0;40002000200040ff200020000000;0000;0000
Index six gives the pattern for the BLUE LED. Again, very exciting. The blue LED does… nothing.

I hope this helps you understand how the programming works.

2 Comments :, , , , more...

The Danger of “Incorrect Password”

by on May.11, 2009, under thoughts, website

I’m sure you’ve seen the message before.  You try to log into a website you go to every now and then, and forget which password you used for it, or type something in wrong.  ”Sorry, this password is incorrect,” says the website.  You grumble to yourself and try again, paying little attention to the harmless message.  From a programmer’s perspective, it’s a bit more interesting than that.

With a SQL database backend, it’s quite easy to figure out a login problem.  It’s a simple matter of searching the databse for a username that is equal to the one the user entered.  If the password of that row matches the password the user entered (generally md5 encoded), then the user can login.  If it doesn’t, they get the “incorrect password” message, and if the username search returns zero rows, they get an “incorrect username” message.  Simple and secure, right?

Wrong.  The problem with telling the user that the password was the incorrect data entered is that it lets them know that the username is correct.  For someone legitimately logging into the website, this is great.  They know exactly what to fix, they fix it and move on.  For someone who doesn’t actually own the account, however, this message is a lot more interesting.

Potentially, a script could be written to try thousands, even millions of usernames all with the same password.  Once an “incorrect password” message is reached, the script can then try another list of thousands to millions of passwords, until it gets an account.  All automated, and very simple.

So, the solution is to not let the user know what’s wrong.  Just say “incorrect login details.”  Something is wrong, but we’re not gonna tell you what.  Good luck!  This will stop any username-guessing script.  Now, you can’t tell a valid username from an invalid username.  However, some websites like to have lists of their members, or the hacker may already know a username for some reason.  So, how do we combat this?

Login try limits.  After 5 failed attempts, lock out the IP address in question.  Any user who just typed something wrong should be able to get it right within five tries, and blocking the IP will stop from additional attacks.  However, some robots are more complex than this.

When it comes down to it, if someone really wants to get into your website, they will.  A botnet will millions of different IP addresses could foil the above scheme.  Additionally, proxies could get around this block.  It would seem that there is no way to keep a website secure.

The responsibility falls on the user, really.  Most websites say somewhere that if someone breaks into your account, they aren’t responsible.  Website admins should have really long annoying to type passwords, because they can easily save the password somewhere, and normal users should have passwords that are strong enough.  If you’re really worried that someone will break into your account, choose a better, longer password.

Or, do we need to go above and beyond passwords?  Is there a level of security past passwords that we have yet to reach.  A lot of computers now have fingerprint readers.  Could we have websites that require your fingerprint as your password?  How about an image?  A website could issue you a completely random image for your password.  You save this image, and have to upload it any time you want to login.  The image would have to be small enough to let dial up users be able to upload the image, but it could be big enough to be very, very random.

So, security isn’t perfect.  I doubt it ever will be.  If someone really, really wants to break into something, they will.  This is why we have jails.

2 Comments :, , , more...

Programming Brainstorm

by on Apr.23, 2009, under life, python, thoughts

Every now and then when working on a program, I like to have a brainstorming session.  Usually I’m just lying comfortably in my bed, thinking of how I can expand a program more, remove bugs, or make it quicker or more stable.  Last night, I had a brainstorming session for tear bookmarks, and I thought I’d share my notes with everyone who reads this.

My brainstorming session basically consists of my tablet running xournal.  I get nice lined notebook paper, where I can write down any ideas that pop into my head.  I can then look at that later and go “No… that won’t work” or “Hmm… I might be on to something,” and try to implement it.

So, if you’d like to see what I’ve been thinking about for tear bookmarks, look at the following PDF: 2009-04-22-tearbookmarksbrainstorm.  Enjoy!

Leave a Comment :, , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...