Command Prompt: Pause with "Press any key to continue"

In a batch file, add pause to display the "Press any key to continue . . ." message.

@echo off
php generate.php
pause

Optionally you can use "@echo off" to hide the commands being sent, so the script wont display stuff like "php generate.php" and "pause".

Git: Recursively check submodules for diffs

Git is pretty good to work with, but when it comes to merging submodules, sometimes the project dies in the ass because someone (ie. me) forgot to commit a submodule.

kermit miffy
An example of the project dying in the ass.

To check for nested differences, use the following command:

git submodule foreach --recursive git diff --name-status

It'll go through each submodule it finds and check for a diff, spitting out the name of the files that have changed.

Entering 'submoduleA'
M       models.py
Entering 'submoduleB'
M       models.py
Entering 'submoduleC'
Entering 'submoduleD'

Remove the "--name-status" flag to show the actual diffs.

Windows: Regain disk space on C drive with some uncommon methods

I admit I've been lazy and slacking on the computer maintenance side of things lately (which translates to a few years). As a result, things have cluttered up and I'm starting to constantly run low on C:.

I do however perform the usual trimming of the temp folders and restore points, which usually do the trick. I find programs that clear the browser cache to be stupid because the files are eventually redownloaded again when you browse.

So I resorted to TuneUp Utilities' Disk Space Explorer which is a bloody brilliant computer maintenance suite. The Disk Space Explorer is a nice tool that lets you see what folders/files are hogging up space on your computer.

Adobe Acrobat 9

First on the list, and somehow unsurprisingly, Adobe Acrobat. Delete the stupid installer cache files, with half the files in languages I cant even read!

Shaved: 1.22gb.

Windows Installer Cache

Much like the the previous program, incomplete or unsuccessful installations may leave horrendous cache files on your computer.

Use the Windows Installer Cleanup Utility (which is basically MSI Zap with a nice frontend) to remove the files in a safer manner. Just be careful with it. Its sort of like a big hammer so if you go apeshit with it, something will break.

Some programs will have broken shortcuts after this is run. Just edit the shortcut and set a target, or recreate a shortcut that runs the appropriate executable.

It also removes the install logs, which makes it impossible to uninstall the software. Just be sure you want to keep it ;)

Shaved: 2.16gb to 793mb (and thats just by removing Visual Studio 2005!)

ACDSee Catalogue Database

You may have noticed that I use alot of "strange images" in my posts. I'm a massive image hoarder, and that causes my image manager to suffer.

Remember to clean your ACDSee catalogue database!

Shaved: 1.6gb to 860mb.

NOD32 Antivirus Quarantine

The quarantine will store a copy of all infected files, including the gigantic (and infected) setup files that you might of grabbed off torrents.

Go to "Tools" > "Quarantine" and remove any files you know you wont need. Its a shame you cant sort by file size.

Shaved: 530mb to 5.38mb.

Compact Thunderbird POP3 Accounts

IMAP accounts will just download content from the servers when needed, but POP3 will store a copy of the email even after you've deleted it.

To delete the unecessary emails, clear your folders (inbox, sent, etc) and then delete them again from the trash folder. Now select your account, go to "File" > "Compact Folders".

Depending on how much crap you deleted, this may take some time. The first time I discovered this functionality, I saved over 1.2gb of space! Now I do this quite often, so I didn't save as much space.

Shaved: 1.66gb to 1.63gb.

Compact VMWare Virtual Hard Drives

All your VM machines need some loving too. See here to find out how to compact the virtual disks.

This will take quite some time, and the space saved will really depend on how much you use the virtual machines. While you're waiting, you can do the next part.

Vista was disgustingly slow and took the longest to shrink by far. Its ridiculous, because there wasn't even anything installed on the damn image and it took longer than overnight to complete! Vista went from being 6.59gb to 7.9gb. WTF?

Shaved: 60.3gb to 55.19gb

Clean Up Your Mess

You always have the feeling that one day, some point in your life you're gonna have to clean your room. Same deal with your downloads folder, one day you're gonna have to clean it out and remove those duplicate downloads.

Eclipse Workspace History

See here to reduce the size of your Eclipse workspace folder by deleting the local history. The local history is a backup copy of anything you save.

Clearing this also seems to speed up your Eclipse loading times.

Shaved: 943mb

ACDSee: Optimise your catalogue database

My ACDsee catalogue database has been left unoptimised for the last few years. Its managed to grow to the size of a monstrous 1.6gb.

You can access it by selecting "Database" and then "Optimise Database ..." in the main menu. I run the optimisation with both tables/files and remove orphan options selected.

image

After running the optimisation, the database has been reduced by half to 860mb.

There are more uncommon space saving tips here.

Acrobat 9: Delete space wasting cached setup files

I was using a disk space explorer and found that Adobe Acrobat was hogging up a whopping 1.22gb on just the frickken installation to auto-repair itself "in case something broke".

The files were located at "C:\Program Files\Adobe\Acrobat 9.0\Setup Files\{AC76BA86-1033-F400-7760-000000000004}", but it may be differ if you changed the installation path.

Sorry, but I cant be stuffed repartitioning my C: just because I'm running low. Wasteful applications like this have got to fuck off.

0312 
Give Adobe a swift kick to the nads to remind them how much they suck.

If you're paranoid about deleting it straight off, just move it off onto another drive "in case something breaks" and auto-repair fails.

The main file using up all that space is "Data1.cab". Acrobat seems to be working fine without it, and my computer can now enjoy a bit more breathing room.

There are more uncommon space saving tips here.

C: Bitwise operators for AND, OR, XOR and compliment

I'm pretty forgetful, hence the reason for this blog, so I'm keeping this as a little reminder on how to perform these tasks in C.

AND

Result: The result is 1 only if both compared bits are 1.

result = variableA & variableB

OR

Result: The result is 1 if either compared bits are 1.

result = variableA | variableB

XOR (exclusive OR)

Result: The result is 1 only if one or the other bits are 1. If both bits are 1, the result is 0.

result = variableA ^ variableB

Compliment

This flips all the bits in a variable, so all the 1's become 0's and all the 0's become 1's. (It isn't actually an operator, but you'll have to come around to using it one day)

Result: An example would be 1001 becomes 0110.

flippedB = ~variableB

image 
C/C++ bitwise operator skill-point level up! Fuck yeah!

Sources:

Javascript: Print this page

To trigger the "print page" dialog, simply use the following line:

window.print();

HTML: How to prefill mailto subject and content

Using "mailto" might be a bit of a no-no for some people, especially with all those spammers making millions from crawling the net for email addresses.

moneybath

However, if you still want to use this feature, you may want to prefill some data in the email client. To do that, format your "href" with some optional arguments:

<a href="mailto:address@domain.com?subject=title&amp;body=something">Mail Me</a>

It would be a good idea to urlencode() the subject and body fields.

You can also prefill CC and BCC fields. See source for more information.

[ Source ]

jQuery: Animated scroll to element

Alot of sites will just link to an anchor on the page and throw the user straight to it. For a person who is new to browsing, that can be pretty confusing.

TruckWheel
To some users, being thrown directly to an anchor may feel like this...

To smoothly scroll your screen to a specific element, use this one liner to help make your site much nicer to navigate:

$('html,body').animate({ scrollTop: $(element).offset().top }, { duration: 'slow', easing: 'swing'});

Slightly modified from source to allow for different types of easing.

You may want to combine this effect with URL anchors for easier hot-linking.

[ Source, jQuery Docs ]

Firebug: Logging JavaScript variables and output

Firebug adds a handy global variable called "console" to your page, which you can use to print stuff into the console window.

var body = $('body');
console.debug(body);

In the console window you can browse the variable you've printed.

image

Clicking on the object will take you to the DOM tab, which will allow you to explore the information contained within the variable.

image

There are a number of other functions such as console.dir() which displays all the properties of the object and console.trace() which shows you the stack trace.

You can see the full list of functions here.

[ Source ]

Django: Filter to check if string contains substring

Out of all the handy filtery things that Django comes with, surprisingly it doesn't have one for checking if a string is contained within another.

Don't worry, thats easy enough to implement.

In a new template tag file:

from django import template
register = template.Library()

@register.filter()
def contains(value, arg):
"""
Usage:
{% if text|contains:"http://" %}
This is a link.
{% else %}
Not a link.
{% endif %}
"""

return arg in value

Now just make sure the tag file is loaded in the template before using.

Office: Manage Microsoft Word's automatic formatting which has gone out of control

image

A friend asked "Does anyone know how to get rid of extra blank pages on Word? Trying to fix up my resume and for some reason I added 4 extra blank pages".

Well, good thing its simple enough to enable the "Show All" button in the toolbar.

If the option is enabled, all non-printable characters are now shown and you know exactly where to select and delete them.

This includes all sorts of rogue new lines, page breaks and tabs.

After you're done, just disable it again.

Bash Shell: Check for optional arguments

One day, I got sick of typing up the whole command over and over.

I needed to write a script that took in one mandatory argument and a second optional argument.

To make the second argument optional, use the "-z" operator checks if a string is empty. The "-n" operator checks for the string being not empty.

if [ -z "$1" ]; then
echo "You need at least 1 argument"
exit 1
fi

if [ -z "$2" ]; then
DOMAIN=$1
else
DOMAIN=$2
fi

CMD="command something $1 -some -flags $DOMAIN"
echo $CMD
$CMD

Remember to "chmod +x filename" to make it executable.

Now you can begin performing all crazy sorts of bash-fu.

PowerPunch

[ Source ]

SQL: Zero padding your numbers

Most SQL servers should support LPAD() and RPAD().

The syntax for these functions are "LPAD(string, length, pad)".

The padding is space by default, but just set it to "0" to use zeros.

Django: Formatting numbers with commas

Its makes it easier to read data in a format such as "$1,000,000" instead of "$1000000".

Template tag

To use it as a template tag, first add "django.contrib.humanize" to your INSTALLED_APPS setting.

The in the template:

{% load humanize %}
{{ price|intcomma }}

Code

Or in your view code:

from django.contrib.humanize.templatetags.humanize import intcomma

return "$ %s" % intcomma(price)

[ Source ]

Lotus Notes: Set Out of Office Message

Its a bit tricky to find, but select the "More" item from the email toolbar and select "Out of Office".

image

JQuery: Selecting appropriate content based on anchor in URL when displaying page

If a user is given a link to your page, you can automatically display certain content depending on the anchor provided in the url.

http://www.yoursite.com/article_page.html#show-comments

This makes your page more user friendly when people copy pasta links to a friend, removing the need to provide instructions on how to navigate to the content.

First, create an anchor with a name matching the anchor.

<a href="#show-comments">Show</a>

The last bit of code on the page should execute after everything else has been initialised and set up correctly.

function displayAnchor() {
var url = document.location.toString();

// URL contains an anchor
if (url.match('#')) {
var anchor = '#' + url.split('#')[1];
$('a[href="' + anchor + '"]').trigger('click');
}
}

It checks if the URL given contains an anchor name ("#show-comments" in this instance) and tries to trigger the click event on the corresponding element.

This will only work if your "href" is the target anchor name (href="#anchor") and not something like href="/page/something.html#anchor".

If it is the latter, you'll need a different selector.

You can also use an animation to slide to an anchor.

[ Source ]

Vista/Win7: Disable Restart your computer to finish installing updates nag box

  • Run "gpedit.msc"
  • Expand "Local Computer Policy"
  • Computer Configuration
  • Administrative Templates
  • Windows Components
  • Windows Update
  • Enable the option “No auto-restart with logged on users for schedule automatic updates installations“.

image

This won't prevent the popup above from nagging you, but at least it wont automatically restart and destroy any unsaved work.

Just another safety reminder kids, do not to take any candy from strangers.

candy from strangers

Fake SMTP "Server" for Developers

I've always wanted a nice fake SMTP server for testing outbound emails, without actually having to run a full fledged SMTP server and wait for my email to be delivered to test the message.

SMTP Server For Developers is a nifty little program by Antix Software that does just that. You set your SMPT server to be the address of the computer running it and it'll log all SMPT requests.

The requests are stored in an EML file that email clients can open, such as Thunderbird and Outlook.

There is no installation required, so just run it when needed. It needs the .NET framework to be installed (not sure which version), so I presume it'll work with MONO as well.

image
It also minimises to tray so it wont bother you during testing.

Django: Filter results within date range

I needed to add some sort of date ranging filter into my query. To do that, we first calculate the date range.

import datetime

six_months_ago = (datetime.date.today() - datetime.timedelta(6 * 365 / 12))

This simply figures out the date which was 6 months from today.

To use that to filter a date field (without time information):

SomeModel.objects.filter(create_date__gte = six_months_ago.isoformat())

[ Source ]

Drupal: Paging made easy

This example shows all the information it takes to implement a simple pager.

$sql = "SELECT nid FROM node n WHERE type = '%s' AND status = %d ORDER BY created DESC";
$res = pager_query($sql, 5, 0, NULL, array('node_type_name', TRUE));

while ($res && ($row = db_fetch_array($res))) {
$node = node_load($row['nid']);
// Display node information here
}

echo theme('pager');

The query can be changed easily, as long as you update pager_query() with the right arguments.

theme('pager') displays the pager widget.

Drupal: Redirect create node form to custom page after save

Normally, we'd set $form['#redirect'] within the hook_form_alter() step if we want to edit the redirect.

But for node forms, the 'Save' and 'Preview' buttons change the behaviour, so we'll need to add our own submit handler and do it within the callback.

/*
* Implements hook_form_alter().
*/
function mod_form_alter(&$form, $form_state) {
$form['buttons']['submit']['#submit'][] = 'mod_form_finish_redirect';
unset($form['buttons']['preview']);
}

/**
* Custom submit handler. Overwrites the form redirection variable.
*/
function mod_form_finish_redirect($form, &$form_state) {
$form_state['redirect'] = '/some/other/path';
}

JavaScript: Call a string as a function with arguments

Man, I sure had trouble giving a proper name to this post.

// Convert string to a function reference
var strFun = "myFunctionName";
var func = eval(strFun);

if (typeof func == 'function') {
// call it
func(param1, param2);
}

The string "strFun" is converted to a function "func". If func() checks out to be a valid function using typeof to check if the function exists, then we just call it with the arguments it needs.

Python: PHP equivalent of in_array() for Python

To check if a value exists within a PHP array:

if (in_array("x", $php_array)) {
// Exists
}

To check if a value exists within a Python list:

if "x" in python_list:
# Exists

Django: Stop filter from always escaping HTML

The majority of the time, Django's automatic escaping of filter output is very handy. But sometimes you actually want the output to be unescaped HTML, so for that you can use the "is_safe" property.

@register.filter
def add_xx(value):
return '<%s>Blah blah blah</%s>' % (value, value)
add_xx.is_safe = True

[ Source ]

Python: Insert string into another string

Sometimes you have to insert a string into the middle of another string, like "C" into "ABDE" so it becomes "ABCDE".

def insert(original, new, pos):
'''Inserts new inside original at pos.'''
return original[:pos] + new + original[pos:]

[ Source ]

PHP: SimpleXML->xpath() not working correctly

It has to do with the namespace and document types not being set properly, so xpath() doesn't know how to parse it.

If you're only after a quick and dirty way of parsing (X)HTML, then all you need is to load it into a DOMDocument to create the SimpleXML object.

$contents = @file_get_contents($url);

if (!$contents) { echo "Error for some reason.";
return;
}

// Parse the document
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML($contents);

$xml = simplexml_import_dom($doc);

foreach ($xml->xpath('//img') as $image) {
$images[] = (string)$image['src'];
}

[ Source ]

Drupal 6: Remove unnecessary CSS files

Creating a new Drupal theme is fairly simple, but its really annoying when the overly ambitious CSS selectors from "system.css", "node.css", "defaults.css" and "user.css" start messing up your layout.

To get rid of them, override phptemplate_preprocess_page() in your theme "template.php" file and append:

function phptemplate_preprocess_page(&$vars) {
// Remove the stupid Drupal css stuff from being added
unset($vars['css']['all']['module']['modules/node/node.css']);

unset($vars['css']['all']['module']['modules/system/defaults.css']);
unset($vars['css']['all']['module']['modules/system/system.css']);
unset($vars['css']['all']['module']['modules/system/system-menus.css']);
unset($vars['css']['all']['module']['modules/user/user.css']);

$vars['styles'] = drupal_get_css($vars['css']);
}

This code was ported from John Forsythe's Drupal 5 post.

[ Source ]

jQuery: Filter out non-printable keypress events

Its pretty handy to listen in for keydown, keyup and keypress events, but it also listens in for a bunch of stuff that, most of the time, we're really not interested in (such as ESC, Tab, F1-F12, backspace, CTRL+C, ALT+Tab, etc).

To filter out those extra triggers we don't need, add the following check at the start of your event handler:

// Filter out special keys
if (e.charCode && !e.originalEvent.altKey && !e.originalEvent.ctrlKey) {
alert('OK');
}
else {
alert('DUD');
}

"e.charCode" will excluse the majority of the non printable keypresses. If you want to keep a specific key (such as backspace, which is useful for searching), then use the following snippet to check for the corresponding key code you want.

var code = (e.keyCode || e.which);

This ensures its compatible with more browsers.

HTTP headers to force a file to download

If you're protecting a file from direct access, you can add some sort of gateway script which spits out the content without redirecting and exposing the URL.

To do that (using PHP in this example), send the following headers to the browser before displaying the content.

$filename = "files/path/something.zip";
$content = file_get_contents($filename);

header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"hello world.zip\"");
header("Content-Type: " . mime_content_type($filename));
header("Content-Length: " . strlen($content));

echo $content;
exit();

The headers are in the same format no matter what language you use, so it should be fairly simple to port it.

[ Source ]

C++: Pre-processors to compile between 32bit and 64bit code

Sometimes you HAVE to make small changes in your code for it to compile for both x86 and x64 code. To do that, add the following statements into your code.

#ifdef _M_X64
// 64bit code here
#else
// 32bit code here
#endif

Digsby: High CPU usage when computer idle

I'm not sure when this was introduced, but I keep noticing my CPU usage graph flat-lining at 100% everytime I'm away from the computer.

Wondering which program was causing my electricity bill to skyrocket, I found out it was Digsby! You little fucker!

image

Open up the preferences and go to the "Research Module". Disable it.

Win7: Enable Hibernation

Go to the Command Prompt and run as Administrator.

Type in:

powercfg /hibernate on

It should now appear in your start menu shutdown options.

image

C++: Menu does not disappear when mouse clicked outside

From MSDN:

To display a context menu for a notification icon, the current window must be the foreground window before the application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise, the menu will not disappear when the user clicks outside of the menu or the window that created the menu (if it is visible).

So whats the solution?

Simple. Just call the function on the window receiving the menu messages before JUST before you call TrackPopupMenu() or TrackPopupMenuEx().

SetForegroundWindow(m_hwnd);
TrackPopupMenuEx(hMenu, ..., x, y, m_hwnd, ...);

C++: Open URL in default browser

ShellExecute(NULL, "open", "http://twigstechtips.blogspot.com/", NULL, NULL, SW_SHOWNORMAL);

For more details, see ShellExecute() on MSDN.

Win7/Win8: Remove Breadcrumbs from Windows Explorer

There are people who love the Windows Explorer crumbs, there are people who just accept it and then there are people who absolutely hate it (me).

image
What drive am I on again?
And WTF is with all that wasted whitespace on the right?

If only Microsoft put an option to disable them =(
(Skip rant for download)

image
My rant starts here

I've used Windows 7 for about 8 months now and my first opinion of the crumbs still hold true, "Explorer crumbs are still there, and they still suck". Why?

  • Because they take up heaps of space, wasting space on a small resolution screen.
  • There is only a small area on the far left or far right which you can click to "begin editing".
  • Small clickable areas means more mouse movement (which sucks for touchpad or pointing stick notebook users).
  • It also means I've gotta concentrate more to click on a small area. If I'm not careful and click on a crumb, I'll navigate to another fricken folder.
  • Crumb zealots are almost as annoying as the actual breadcrumbs, especially when they say "reinstall XP".
  • I'm not Hänsel nor Gretel, so I'm familiar enough with my own computer that I don't need to leave little trails along the path to find my way home.

You're probably thinking its just a small thing and I should simply learn to ignore it. Don't get me wrong, I've used those bloody things for 8 months now and I still think they're an absolute prick to deal with.

Think of it this way. Those Explorer crumbs are like an eyelash in your eye. Your eye still functions properly, it's small, but its fucking annoying.

image
If that wasn't enough of a case for you...

And if it were so awesome, Andreas Verhoeven wouldn't of bothered making a small program to get rid of them in Vista. His "AveNoBreadCrumbs" app is pretty good, if you're using 32bit Vista. On 64bit Vista or Windows 7 (either 32bit or 64bit), no suck luck.

Anyway, </rant>.

I've spent about a week learning how to get rid of these things and I'm glad to say I've finally succeeded!

It performs the same functionality that his app does, but it also ensures that the path is visible when Explorer first starts. The path is also updated when you browse to another folder using the tree.

Managed to learn a few extra things on the side =)

Download

Now that its cleaned up and hosted, the links are

Usage

  • Simply run the file to kill the crumbs.
  • Close the program to restore breadcrumb functionality.
  • Run with the argument "--no-icon" to disable the tray icon.

It seems to be running fine on Windows 8 (dev and consumer previews) as well.

Alternatives

For those who wish for a more all-out and installed solution to bringing back XP features into Windows 7, check out ClassicShell by Ivo Beltchev.

If you want to keep everything intact and only remove breadcrumbs, then use my Breadcrumb Killer.

And as mentioned previously, AveNoBreadCrumbs works nicely on Windows Vista 32bit, only.

Credit

Props to Tux and Shawn for helping me figure out some C++ strings stuff.

Thanks to Ami/Narusegawa_Naru for giving me a starting point (even though she thinks this is stupid).


piratetoasticonbycalacr[1] The icon is "Pirate Toast Icon" by Calacruf at DeviantArt, but the account has been closed so I don't know how else to contact him/her.


If you don't want me using the icon, let me know!

Thanks Ivo Beltchev for reminding me about the KillTimer() call.

Screenshots

Not much to show here. It's the same effect as when you select the address bar.

image 
Normal Windows Explorer.

image 
Windows Explorer with BreadCrumb Killer running.

image 
Address bar selected.

Things left to do

  • Make an "About" dialog
  • Fix duplicate dropdown arrow
  • Fix crumbs not removed when Explorer launched in a separate process
  • Figure out how Andreas Verhoeven hides the crumbs.
    It seems more effective than my method as Spy++ shows fewer messages being sent.
  • Make it work on 32 bit Win7.

Its been tested on Windows 7 (x64 and x86). Would be great if I had some feedback on any issues.

Not sure about Vista, but if it works then that's always a bonus.

History

v1.41 (20/03/2011)

  • Minor release, removed debug message.
  • Update this page a little
v1.4 (14/03/2011)
  • Rewrote portion of the code so the DLL and EXE share information.
  • Added a refresh so it has a fair idea when to reapply hooks.
  • Listens for WM_TASKBARCREATED.
  • Added a check for "already running".
  • Correctly returns the shell proc value.
  • Updated version info.
v1.3 (09/09/2010)
  • Removed the duplicate dropdown arrow
  • Changed the "Website" button into a syslink
v1.2 (05/09/2010)
  • Fixed x86 version so it works again
  • Added command line argument "--no-icon" to disable tray icon
v1.1 (11/04/2010)
  • Fixed x86 DLL function name mangling
  • Cleaned up some code
  • Combobox creation trigger now works more reliably
  • Added a missing KillTimer() call
  • Added build version to executable
v1.0 (15/02/2010)
  • Initial release.

Other Small Tweaks

Python: Select a random element from a list

from random import choice

image = choice(image_list)

rihannabrown[1] 
Fuck yeah!

C++: GetProcAddress() fails with local DLL

While trying to retrieve the address of an exported DLL function, I noticed that GetProcAddress() kept failing.

The error code from GetLastError() gave me 127, being ERROR_PROC_NOT_FOUND. Why the hell?

The function being exported is this:

extern __declspec(dllexport) LRESULT CALLBACK BCK_WndRetProc(int nMsg, WPARAM wParam, LPARAM lParam);

So given that information, I was expecting the function name to be "BCK_WndRetProc", because thats the name of the function exported... right?

Quickly checking the exported symbols gave me a surprising result.

1    0 0000100F ?BCK_WndRetProc@@YA_JH_K_J@Z = @ILT+10(?BCK_WndRetProc
@@YA_JH_K_J@Z)

So apparently the exported function name is "?BCK_WndRetProc@@YA_JH_K_J@Z". WTF?

I found out that we're meant to prepend something to the export call.

extern "C" __declspec(dllexport) LRESULT CALLBACK BCK_WndRetProc(int nMsg, WPARAM wParam, LPARAM lParam);

Amazingly, just by adding a little "C" (with quotes) to the export call, the symbol has cleared up quite a bit!

The x86 compiler spat out "_BCK_WndRetProc@12" symbol for the DLL, and the x64 compiler spat out the correct "BCK_WndRetProc" function name.

Weird stuff. I haven't been able to find reasoning behind why this happens, but for curiosity sake any explanations would be appreciated!

 

*edit 11/03/2010*

Thanks Anonymous, I took a look for DLL mangling and found that the "CALLBACK" declaration was using __stdcall, causing the output function name to be all mangled.

[ Extern "C", Cause of DLL mangling ]

Visual Studio: View Exported DLL functions

Visual Studio comes with a crapload of tools, but most of which wont ever be used.

However, "dumpbin" is quite handy if you want to quickly see what functions are exported from a DLL file.

Fire up the Visual Studio Command Prompt and navigate to your DLL file. Then type:

dumpbin /exports Test.dll

Whalla, the function names should be listed below.

Firefox: Unignore the unresponsive script popup

Occasionally you'll run into a site that has a long running script. Firefox gives you the option to stop the script or continue waiting (shouldn't each tab run scripts in its own thread anyway?).

image 
A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete.

Sometimes its quite tempting to click "Don't ask me again" and ignore the script dialog.

But if you ever want to get it back:

  • Type "about:config" in the address bar
  • Search for "dom.max_script_run_time"
  • Reset the value

Visual Studio: Debug with trace logs to the Output window in C++

If you need to debug a loop or some sort of Window callback, its ridiculously difficult to use breakpoints.

Instead, we can use some formatted output to the debug "Output" window that'll provide us with some handy information.

First, import <crtdbg.h>. This now gives you access to the macros _RPT(), _RPTF(), _RPTW() and _RPTFW(). All of these functions have a similar signature of (reportType, format, [args]).

Each function can also take up to 4 arguments. Simply append a number of 0-4 after the function name to allow for that many number of args. The functions with "W" support wide characters (unicode).

#include <crtdbg.h>

for (int x = 0; x < 10; x++) {
    _RPT1(_CRT_WARN, "x = %d\n", x);
    //_RPTW1(_CRT_WARN, L"Unicode x = %d\n", x);
}

Will give you this output:

image 

Amazingly helpful and simple, but bloody damn hard to find the exact information online.

[ Source ]

CSS: Internet Explorer, position relative/absolute and z-index don't act right

Another day, another IE6/IE7 CSS quirk. Good thing it doesn't affect IE8 and luckily this ones a bit easier to fix than most.

image

It doesn't make sense. The light blue div on the bottom left has the "position: relative;" style set, while the menu has "position: absolute" with a higher z-layer index.

For some reason, IE decides to just ignore the z-layer and put the div on top anyway. Annoying little critter...

To fix this:

  • Give the troublesome div a small z-index (0 or so)
  • Give the menu a higher z-index, say 10 (anything higher than 1 will do)
  • Give the menu's parent a z-index of anything thats higher than the menu.

[ Source ]

jQuery: Window height given wrong value in Opera

After some messing around with jQuery, Opera and CSS, I figured it wasn't my fault the element wasn't being centered in the middle of the screen.

The reason being that as of Opera 9.5, they relocated the body height of the document to another place, so jQuery retrieves the wrong size when you call $(window).height().

A simple one line fix would to retrieve the correct height would be:

// fix a jQuery/Opera bug with determining the window height
var h = $.browser.opera && $.browser.version > "9.5" &&
$.fn.jquery <= "1.2.6" ?
document.documentElement["clientHeight"] :
$(window).height();

[ Source ]

Internet Explorer 6: No String.trim() support

Its not exactly a well kept secret that web developers loathe IE6, but I never expected to leave out a simple function such as String.trim().

A simple test script such as this would cause an error.

alert("     hello world    ".trim());

image
An unwelcome surprise.

Luckily, theres an easy fix for that! Simply paste this code near the top before any trim() calls are made.

if (!('trim' in String.prototype)) {
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); };
}

image 
Yay its working now!

[ Source ]

Blogger: Can't copy/paste in comment entry text boxes

For some reason, Blogger.com doesn't seem to play nice with comments on Firefox (and surprisingly not Internet Explorer). It's taken me a good while to sit down and figure out whats wrong.

There isn't much information on the net regarding this bug that I could find, and all the pages seem to link back to this one post, which basically has summed up all the symptoms I've noticed.

What a frikken annoying bug this has turned out to be.

Symptoms

  • Copy/Paste doesn't work
  • Right clicking on the text field shows no options Undo/Cut/Copy/Paste/Delete/Select All
  • Home/End keys don't work
  • Arrow keys (up, down, left, right) keys don't work
  • Selecting all by pressing CTRL+A doesn't work

image 
Just in case you didn't believe it

Steps to produce

  • In your Blogger account settings, set the comments to "embedded below post"
  • Sign out of your account
  • Turn off any ad-blockers you may have
  • Using Firefox, view post and enter a comment
  • Try to copy or paste from the form

Affects

  • Firefox 3.5.7 (at time of writing)
  • All platforms

Problem?

I was wondering why ad-blocker had to be off for this to happen. After some trial and error, I found the culprit.

For some reason, a gif file loaded by Google Analytics was causing the textbox bug.

The file is loaded at:

http://www.google-analytics.com/__utm.gif?...

Where "..." is a whole bunch of tracking information that records your information.

Blocking this file specifically will stop this bug from occurring, but will probably prevent Analytics from working.

I'm still unsure why being signed in or previewing alleviates the problem.

Solution

Not too sure. I tried removing the image using jQuery but the image isn't actually part of the page, so that doesn't help.

Until Mozilla decides to get around to fixing it, you pretty much have two solutions.

On one hand you can make the comments appear in a popup, which is uber annoying.

On the other, you can stop using Google Analytics.

If you wish to keep using both, leave a message for users to either sign in or preview comments before submitting. This way, it re-enables copy/paste in the form.

If you have any other solutions, feel free to let me know!

Youtube: Link to video and also time it starts playing from

Its easy enough to send somebody a YouTube link, but when a video contains a bunch of crap at the start or you want to skip straight to the good part, its handy to know how to skip straight to the bits that are interesting.

Take for example this link:

http://www.youtube.com/watch?v=yBdsvmcZUC0

If I wanted to show the fun parts of the video that start at 0:51, I'd have to tell the person "Hey, watch this and skip to 0:51 because theres a bunch of stupid kids at the beginning that nobody cares about".

They'd have to open the video, wait for it to load and then drag the cursor to the given time. That's annoying.

Instead, we can just give them the slightly modified link that'll skip straight to the time given. We add an anchor called "#at=51" at the end of the url so now it should look like:

http://www.youtube.com/watch?v=yBdsvmcZUC0#at=51

Now the link given will skip straight to the 51st second of the video.

If the time you're skipping to is over a minute, then you'll have to convert the time to the number of seconds.

For example, skipping to 2m30s takes converts into 150 seconds. The link is now:

http://www.youtube.com/watch?v=yBdsvmcZUC0#at=150

Another great example would be this video ;)

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog