Python: Convert datetime to date

In order to do date comparisons, you need to convert your datetime to a date object.

To do that, simply call date() from your datetime object.

now = datetime.datetime.now()
now_date = now.date()

I know, bad example because I could have used datetime.date.today() instead.

tumblr_kp591vlknj1qzxzwwo1_500
Now, if only I could handle time like Sean Connery...

Source

Android: Quickly access resources from anywhere, without passing Activity or Context around

After a while, you really do get sick of passing Context and Activity arguments around just so you can pull resources from your package.

It makes your code messy, unnecessarily clutters up function signatures and is a general pain in the ass.

Well, looks like this problem was solved long ago and I should have looked into it earlier!

  • The first thing you need to do is extend the Application class.
  • Override onCreate() so you can store a static reference to the application context.
  • Create a static function getResourcesStatic() to use it, since getResources() already exists and is non-static.
public class MyApplication extends Application {
private static Context context;

public static Resources getResourcesStatic() {
return context.getResources();
}

@Override
public void onCreate() {
super.onCreate();

this.context = getApplicationContext();
}
}
  • Lastly, change your AndroidManifest.xml file to use the new Application class.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name="MyApplication">

And that's it!

From now on, you can remove all those context arguments and replace them with MyClass.getResourcesStatic()

ZSG5P
Exciting stuff, no?

Source

Flash: Setting up the Cross domain XML policy file

One of the annoying "features" of security is that you constantly have to keep working around it, legitimately.

In order for your flash file to access data on other servers, you have to set up a crossdomain.xml file in the root of your domain.

For example, this is at http://somehost.com/crossdomain.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*.yourhost.com.au"/>
</cross-domain-policy>

Replacing "yourhost.com.au" with whatever remote server you wish to access.

You can also have multiple "allow-access-from" elements to allow multiple domains. For more information see source.

Hope you didn't spend too long looking for the answer to this one!

Source

Eclipse: Ignore certain files in project such as .git and .svn

For some time, the only way to ignore certain file types in Eclipse was to create a plugin.

Resource filters were added recently (apparently in 3.6 Helios) and I had only discovered them recently.

They solve one of the biggest gripes I've had with Eclipse so far. The ability to ignore any file matching a pattern (such as compile .pyc python files, MacOSX .DS_Store or thumbs.db).

It can also extend to folder paths so we can ignore those pesky .git or .svn folders and all of the unnecessary files within them.

image

Enough complaining, more removing!

For this example, I'll be showing how to hide all .git folders and their contents. This can be substituted for .svn.

  1. First step, open your project.
  2. Right click, Properties
  3. Expand Resources and click onto Resource Filters
  4. Click "Add"
  5. Use these settings

Filter type: Exclude all.

Applies to: Folders

Click "All children (recursive)" as any subfolders containing your pattern will still show up (common case for .git and .svn)

File and folder attributes: Name matches .git

OK to save!

Click Apply when ready.

image

Eclipse will now refresh and rebuild the project.

If you're ignoring file names, use the following settings instead.

Applies to: Files

Matches: *.pyc (or .DS_Store, thumbs.db, etc)

No need for all children.

Great feature, very flexible but pain in the ass if you've got 15 projects...

Very much worth setting up if you're working over a remote connection, it saves a LOT of time refreshing your project even if it's a LAN connection.

ZaZEf
Happy times!

Sources

Python & HTML Tidy: Checking and displaying HTML errors

The system I was building allowed for entry of HTML entities, but was used by many non-HTML familiar users.

To prevent broken HTML from entering the database and potentially breaking the site layout upon display, I needed a way of indicating that the markup was broken whilst informative enough to point to where the error is.

Luckily, the HTML Tidy library for Python does just that! Depending on your operating system, you can get it via pip or easy_install with "pytidylib".

Once you're set up, doing the actual check is easy.

from tidylib import tidy_fragment
import re

# Check for missing close tags (bold, italics, links, etc)
document, errors = tidy_fragment(data)
reobj = re.compile(r"(line \d+ column \d+ - Warning: missing </\w+>)")

missing_tags = []

for match in reobj.finditer(errors):
missing_tags.append(match.group())

print missing_tags

Done and dusted!

bCcrQ
Time for a long awaited feel-good "cat pushing another cat off a shelf GIF"!

Sources

Formatting Sony Vaio Z 2011 (VPCZ2390X) with a clean copy of Windows 7 and working dock/external GPU

I've searched far and wide for a solution to this but only found scraps of information here and there. As with my Dell, I'm not a fan of manufacturers filling up the computer with their own bloated software which only slow down the computer.

Before you begin this journey with me, you should make the most of the "Sony Vaio Care" ability to upgrade your BIOS firmware.

Ensure you've got your copy of Windows 7 x64. The drivers for the x86 version aren't available from the site so good luck with that!

You can customise your Windows image using a combination of either RT7Lite (abandoned but still works) and Win Toolkit.

Do not slipstream drivers into the disc. I'm going to provide instructions on how to install them manually. For the external dock to work, the order of installation is important!

I've never had a device be so fussy about reboots or driver install order, so please take the time to reboot when instructed. It's a bloody fast notebook anyway, so you don't really have a reason not to.

Let's get ready to free your Vaio Z from bloat!

tumblr_m7f8vqCSXY1qa5rnho1_400

Downloads

  • WinToFlash to put the setup into a USB drive (if you don't want to install from the DVD dock)
  • Now to make yourself familiar with the drivers download page.

Note that some of these are pretty big, it's about 1.1gb all up!

So it'd be a good idea to skim through the tutorial and start downloading these before you begin formatting.

When saving, name them as such;

drivers

Formatting

1. Windows 7 x64

I installed off USB rather than DVD, but the instructions shouldn't be too different from the regular install process. Just remember the main points:

  • Set BIOS to boot off "external device" (aka USB)
  • Follow the prompts and install Windows
  • Keep an eye on it until you reboot. When it reboots, get back into the BIOS and switch back to HDD as primary boot device
  • Follow the prompts until you get to the desktop

device-manager-unknowns 
Now the fun/tedious part, installing drivers!

Before you continue ...

Tip: Before you begin, plug in your dock and leave it plugged in!

Tip: Reboot whenever it asks you to!

Tip: Follow these instructions in the order presented. Otherwise you run the risk of the dock not working.

Tip: It's a good time to disable UAC even if it's temporarily.

Installing the drivers

2. Chipset

Go nuts and install these. They'll knock off the majority of the unknown devices in the device manager.

3. External Graphics

The external graphics in the dock is next. I've got an ATI Radeon HD 6650M with my Vaio Z so that's being served.

4. Audio

Sound is up next. Follow these in order and you'll have working onboard sound, HDMI output as well as working noise-cancelling headphones.

5. Ethernet

Yay! Now we're getting the internet!

6. Card Reader

Ensures the memory stick/SD card reader is working.

7. Touchpad

Edge, horizontal and 2-finger scrolling with pinch/twist/sensitivity/etc options. You'll want this.

8. Sony Firmware Extension

This one can be found under "System Components". I have no idea what it does, but it gets rid of a yellow "!" mark in the device manager.

9. Bluetooth

10. Intel Management Engine Interface

Another one of those "I have no idea what it is" packages. Just grab and go.

11. Wireless Network

Yay, more internet!

* Update 15/10/2012: Had some issues connecting with wireless and random dropouts. Either re-install the wireless update or just install the update package without the initial.

12. Sony Shared Library

This seems to be a bunch of DLL files that Sony packages run off. Don't worry, I'll only install the important ones that do useful things.

This can be found under "System Components".

13. Automatic brightness, backlit keyboard, battery checker and bluetooth control

These utilities let you control or disable the automatic options such as;

For automatically dimming the screen when it's darker, enabling the backlit keyboard or swapping power profiles when battery levels change.

For turning on/off wireless or bluetooth individually, saving unnecessary battery drain.

14. Fingerprint reader and USB 3.0

Time to get rid of the last few "!" marks.

I can't remember if I installed these or not, but it may be useful for you.

All done!

When it's done, reboot again to lock everything in.

You should now have working FN buttons to control various things from the keyboard such as volume, brightness, display out, etc.

Notice that Sony Vaio Care wasn't installed? That .NET 4.0 resource hog is gone!

Oh, and turn UAC back on if you really want it.

1B1yf
Another day, another victory.

Sources

Django: Fix CSRF Token Cookie not generating for non-html pages

This was a bit of a tricky one to debug. I was creating an API to log into the site via an app which communicated through JSON.

If the user was already logged in, the JSON response contained:

  • the account details
  • session ID (automatically set)
  • the CSRF token from request.META["CSRF_COOKIE"]

Otherwise, the user had to use HTTP POST to gain access to functionality. Since there wasn't any CSRF information yet, I decided to unprotect that view using @csrf_exempt.

This worked fine, as the JSON response was still giving back the right information:

  • account details
  • session ID
  • CSRF token from request.META["CSRF_COOKIE"]

The strange thing was that the CSRF token was being regenerated on each request, making any AJAX type calls fail the CSRF test every time even with "X-CSRFToken" set.

After a little investigation by delving into the Django source files, I realised there were 2 reasons why this was happening.

Firstly, the view to check/login was using @csrf_exempt. The cookie won't be set if the view is exempt. Removing the exemption case is fine, as the app will always perform an initial GET fetch request to check existing login data.

Strangely, this was still not enough to generate the "csrftoken" cookie.

A little more investigation by browsing made me realise something, it's generating when I view regular pages but not my special JSON view.

The view isn't terribly complicated either. Can you spot the problem causing the CSRF token to not be set?

c = {
'success': u.is_authenticated(),
'username': u.username if u.is_authenticated() else '',
'csrf_token': request.META["CSRF_COOKIE"],
}

return HttpResponse(JSONEncoder().encode(c))

No? Don't worry, I didn't either.

The cookie won't be set unless the content/mime type of the page is a known HTML type (such as "text/html" or "application/xhtml+xml").

So apart from changing the mime-type, what can we do?

Easy. Just add in this line just before returning HttpResponse.

# This triggers CsrfViewMiddleware to make it set the CSRF token upon first request.
request.META["CSRF_COOKIE_USED"] = True

That's all it needed. That sneaky little bastard wasn't in the docs when I looked at it, but it should solve this fairly niche issue.

81366568
Now, off to solve more important problems!

django: taggit error "FieldError: Cannot resolve keyword 'tagged_items' into field."

Even with an extremely basic model, the django-taggit submodule was not working. I'm not even sure if this was tested before merging.

class TwigTest(models.Model):
taggit = TaggableManager()

TwigTest.objects.filter(taggit__name = 'dell')

FieldError: Cannot resolve keyword 'tagged_items' into field. Choices are: id, taggit, twigtest_tagged_items

Took a look around a few links gave no certain solutions, so I managed to fix it by commenting out TaggableManager.extra_filters() in manage.py.

Take it with a grain of salt, because I have no idea what I may have broken by doing this.

229196-254280708008944-785296244-n
These instructions will work too!

Sources

Android & Eclipse: Fixing "Derived File Encountered - This file is derived. Do you really want to edit it?"

image

This annoying little quirk also caused my file to stop showing up in the "open resource" dialog.

It happened when I accidentally dragged the java file into the "gen" folder. I guess the SDK automatically marks anything in there as derived.

Derived just tells the Eclipse IDE that files were generated by the system, and will be overwritten if something else changed.

To remove it, simply right click on the file and select "Properties".

From there, untick "Derived" and then save it.

Now, back to business!

bSGfJ

Django: Get name of SQL table from Model

It's rare, but sometimes you have to delve deep into the deep edges of Django's ORM to do raw SQL.

Something that would definitely make your life easier is knowing how to get the table name from a models.Model object.

You can fetch it by grabbing YourModel._meta.db_table.

ibvZA3Ux1aA3Nu
Grab that Model, Gangnam style!

Django: Quick snippet to get user from session ID

This is pretty much a drop-and-go snippet.

def get_user_from_session(session_key):
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session = Session.objects.get(session_key = session_key)
uid = session.get_decoded().get('_auth_user_id')
return User.objects.get(pk = uid)

user = get_user_from_session('6117e4e8882448931b3de1f2440243ff')
print user.username, user.get_full_name(), user.email

That's it!

Lu6DW
Now, back to being productive...

Source

Twitter: Change number of results from twitter search API

The twitter search API is pretty flexible, but one of the things I wanted was to increase the number of results fetched.

By default, it returns about 20. The API is accessed through:

http://search.twitter.com/search.json?q=query&rpp=itemsperpage&page=pagenumber

Could have just been me, but I couldn't find the "results per page" (rpp) argument anywhere in the docs.

You can continue through the pages by feeding it new "page" numbers.

1311359396_129175753884361380
Now go nuts, knock yourself out!

Source

Word/Excel: How to add strike-through (or any other command) to toolbar

This is such an easy task but I've never thought of doing it before! Why!?

image
Current toolbar, without strike-through.

  • Right click the toolbar and click "Customise"
  • Click on "Commands" tab then the group of commands you want.
  • In this case, I want "Formatting".

image

  • Find "Strike-through" in the list and drag it to the position in a toolbar you want
  • Laugh at how easy it is and proceed with striking things out!

deadpool-iDbAEnCEnthry
Deadpool dancing with Castle Crashers? Sure why not!

Sources

Facebook: Remove Recent Places from Timeline

Fuck you Facebook.

Seriously, location awareness disabled on my phone. Not using your information siphoning app and you STILL extract location data from photo EXIF and ISP information.

image
THAT shit!

image
And this shit in the red circle!

Anyway, to remove the recent locations widget from your timeline, do the following:

  • Go to your profile (by clicking on your name in the top right)
  • Just under your cover picture, there are a few squares such as "Friends" and "Photos"
  • Beside it should be a little triangle pointing down (blue circle). Click it.
  • A pencil should appear on the Maps favourites
  • Remove that shit from favourites.
  • Click the triangle again.

Now, don't be freaked out if you still see it in your profile. It'll still appear to YOU, but not anyone else.

To try it out:

  • Click on the cog next to "Activity log" (blue circle)
  • Select "View as"
  • Type in your friend's name and select them
  • You should not see the maps widget in the favourites nor further down in your timeline.

Now you can continue using Facebook without worrying about people scoping out your locations, GANGNAM STYLE!

tumblr_m7759dfBXa1qitqsuo6_r1_250
This cowboy thrusting scene has gotta be one of the best!

Sources

Senate Petition Regarding National Security Inquiry

If you're sick of the Government trying to corrode our online rights, sign this petition backed by the Australian Pirate Party!

I do no wrong, but I'm annoyed at being treated like a criminal.

Being thrown in prison because I don't want to give my encryption keys to my online passwords? Fuck off!

http://pirateparty.org.au/natsecinquiry-petition/

Say something about it now or forever lose your rights.

yyuiU
FIGHT BACK, GET MAD!

Blogger.com: Disable country domain redirects

I'm getting annoyed at my web traffic stats being all messed up because the URLs aren't being counted properly.

Popular Pages - Twigs Tech Tips

People browsing from different part of the world are being redirected to their government friendly top level domains (TLD's) and it's just annoying.

This is meant to be the internet, a place where information roams free from the slow red tape of bureaucracy.

Thankfully, there's a quick fix for this and it doesn't involve any unnecessary pain.

2843_0c8f
  • Firstly, log in to your blogger.com admin.
  • Secondly, open up the dashboard for your blog.
  • Click "Template"
  • Click "Edit HTML"
  • Click "Proceed"
  • Select "Expand Widget Templates" at the top.
  • Using your browser, search for </head>
  • Just before that, paste this in:
<script type="text/javascript">
function check_redirect(your_domain) {
if (window.location.host.split('.').pop() != your_domain.split('.').pop()) {
var new_url = window.location.href;
new_url = new_url.replace(window.location.protocol + "//" + window.location.hostname, window.location.protocol + "//" + your_domain + "/ncr");
window.location.href = new_url;
}
}

check_redirect("twigstechtips.blogspot.com.au");
</script>
  • Change the 2nd last line to whatever you want your domain to be. In this case, I want to enforce it so everyone visits the .au one.
  • Click save.
  • Test it out!

Source

Originally I found the information from here, but from inspection it doesn't seem to cover all the domains I have been seeing in the stats such as .co.uk.

I've rewritten it a little so it does the domain detection and replacement better.

Android: OpenGL textures showing up on emulator and some devices, but not others

Rule #1, RTFM. I'm afraid I break this rule quite often and when it comes to learning something as arcane as OpenGL, you're gonna have to even if the docs suck.

I ran into this problem after testing on the emulator and my Sony Xperia x10 mini fine, but surprisingly my Samsung Galaxy S failed to render the textures.

I soon discovered that for OpenGL 1.x, the dimensions of texture bitmaps have to be in the power of 2. That means the width or height can be any combination of 1, 2, 4, 8, 16, 32, 64, 128, 256, etc.

2x512, 16x64, 8x256, whatever. If any of those were a non-power of two (NPOT), you run the risk of it not loading on some devices.

Obvious fixes

Two ways of dealing with it. First method is obvious, resize your bitmap so it's in the right size in the power of 2's. If you're still running into errors, see the section below.

Second way to use OpenGL 2.x, which allows for NPOT texture files to be loaded. This is a choice between dumping support for older devices or using a newer API.

I believe you'll need at least SDK API level 8 and ensure all devices have OpenGL 2.x and need to set something in the Android manifest.

Not so obvious fixes

Alright, so you've tried the first two methods. But there are many other possible issues you will run into.

Other people had suggestions of putting the drawables into the "/res/raw" folder instead. That isn't an issue if you're using the InputStream method of loading bitmaps.

Others had the solution of putting it into /res/drawable-nodpi. That didn't work for me either.

Why all this hassle? The answer is simple, it's because the Android framework can't be trusted to load the bitmaps accurately. Manufacturers may tweak the source, image compression upon loading works differently across devices, etc etc.

To ensure that it loads exactly the way you've created it, ensure that this function isn't changing your bitmaps:

Bitmap bm = BitmapFactory.decodeResource(context.getResources(), resID)

For the textures to load properly, swap it for this longer snippet to prevent bitmap transformation:

InputStream is = context.getResources().openRawResource(resID);

try {
bitmap = BitmapFactory.decodeStream(is);
}
finally {
//Always clear and close
try {
is.close();
is = null;
}
catch (IOException e) {
}
}

Give it a shot, it'll probably work. Tested on Android 1.6 (Sony Xperia x10 mini) and Android 2.3.6 (Samsung Galaxy S).

1oxBB
Problem solved, FUCK YEAH!

Sources

Android: Scalable background images with clickable hotmaps

Every once in a while I decide to fire up the Android SDK.

Once I start hitting up the GUI development... I wonder what the hell am I doing it for? It's frustrating.

Anyway whilst working on my Diablo 3 Max Stats app, I stumbled upon a problem. A problem of detecting "hit-boxes" on a scalable background image.

Displaying the image itself isn't too bad, as long as it's centered in the middle of the screen. Adjusting the invisible overlay views on top in the right position, pain in the ass.

So I gave up. Fuck it, why waste my time?

Instead, I stumbled upon a post by Bill Lahti which made me think in a different way. Using old-school Duck Hunt technology to determine my coordinates.

Why not? Worth a shot and it looks quick and easy to implement.

Setting up the layout

  • First, we make a FrameLayout the root for our layout.
  • On the FrameLayout, I set:
    image
  • Then we add an ImageView (img_bg) on it. The FrameLayout automatically scales and centers the ImageView.
  • We add an ImageView rather than setting the "Background" option of the Layout, since we can choose the scaling type.
  • For the ImageView, set the width/height to fill_parent, adjust view bounds to True and scaling type to "centerInside".

image
You should now have something like this (ImageView selected)

  • Now add another ImageView (img_hitbox) into the FrameLayout, but this time choose the "hit-box" image (see below).
  • Important! Set the same settings as the background image. They have to be the same size positioned in the same place for this to work!

Your current structure should now look like this.

image

image

  • Finally but most importantly, set the Visibility of the hitbox to be "invisible". If you select "gone", it won't be added to the UI at all.

That's the WYSIWYG side of things done.

Setting up the hit-box code

Now for some code trickery. Because the img_hitbox ImageView visibility is set to invisible, it can't receive touch events.

So, we have to add the event handler to our Activity instead.

Ideally, what will happen is:

  • User touches screen.
  • Activity receives onTouchEvent() signal.
  • We translate the X/Y of that touch into a pixel colour in the hit-box.
  • Depending on the colour, we do various things.

And here's the source that'll do just that!

public class D3minmaxActivity extends Activity {
@Override
public boolean onTouchEvent(MotionEvent event) {
// We only care about the ACTION_UP event
if (event.getAction() != MotionEvent.ACTION_UP) {
return super.onTouchEvent(event);
}

// Get the colour of the clicked coordinates
// And yes, I spell it coloUr.
int x = (int) event.getX();
int y = (int) event.getY();
int touchColour = getHitboxColour(x, y);

StringBuilder sb = new StringBuilder();
sb.append("ARGB(");
sb.append(Color.alpha(touchColour));
sb.append(",");
sb.append(Color.red(touchColour));
sb.append(",");
sb.append(Color.green(touchColour));
sb.append(",");
sb.append(Color.blue(touchColour));
sb.append(")");

Log.e("Clicked", sb.toString());

// We do this because the pixel colour returned isn't an exact match due to scaling + cache quality
for (Integer col : colorMap.keySet()) {
if (closeMatch(col, touchColour)) {
Log.e("SuCESS!", colorMap.get(col).toString());
Intent data = new Intent(this, ModifiersActivity.class);
data.putExtra("slot", colorMap.get(col));
startActivity(data);
return true;
}
}

// No close matches found
Log.e("clicked", "nothing");
return false;
}

/**
* This is where the magic happens.
* @return Color The colour of the clicked position.
*/
public int getHitboxColour(int x, int y) {
ImageView iv = (ImageView) findViewById(R.id.img_hitbox);
Bitmap bmpHotspots;
int pixel;

// Fix any offsets by the positioning of screen elements such as Activity titlebar.
// This part was causing me issues when I was testing out Bill Lahti's code.
int[] location = new int[2];
iv.getLocationOnScreen(location);
x -= location[0];
y -= location[1];

// Prevent crashes, return background noise
if ((x < 0) || (y < 0)) {
return Color.WHITE;
}

// Draw the scaled bitmap into memory
iv.setDrawingCacheEnabled(true);
bmpHotspots = Bitmap.createBitmap(iv.getDrawingCache());
iv.setDrawingCacheEnabled(false);

pixel = bmpHotspots.getPixel(x, y);
bmpHotspots.recycle();
return pixel;
}

public boolean closeMatch(int color1, int color2) {
int tolerance = 25;

if ((int) Math.abs (Color.red (color1) - Color.red (color2)) > tolerance) {
return false;
}
if ((int) Math.abs (Color.green (color1) - Color.green (color2)) > tolerance) {
return false;
}
if ((int) Math.abs (Color.blue (color1) - Color.blue (color2)) > tolerance) {
return false;
}

return true;
}
}

Best part about this solution is that it's orientation friendly!

Extra consideration

The main issue I had with implementing Bill's solution is that I had the Activity toolbar showing. This caused the getPixel() function to bug out, as it was trying to fetch pixels for coordinates from outside of the bitmap.

I've fixed that issue by determining the location of the ImageView and adjusting it accordingly.

Another difference is that his code had a colour tolerance level. My version wants precise colours. Colour me foolish, I didn't realise until I was testing on the actual device that the pixel colours returned are not exact. I've added the tolerance code back in.

Also fixed a memory leak issue when not recycling bitmaps.

Sources

Django: Form.clean() is being called even though required fields are empty

So I decided to randomly check some code by submitting an empty form. To my surprise, Form.clean() was being called even though the required fields weren't valid. I was certain it was a core Django bug.

69E6e
Hello Twig, I'd like to play a game ...

It took a bit of thinking but I finally understand now. It's meant to work like that.

Wait, hear me out!

Most people would do this:

def clean(self):
data = self.cleaned_data
country = data['country']

Assuming that the required field "country" is set, but that's not true.

The framework is so lenient that it allows you to raise custom error messages even if the required fields aren't filled in, just in case you wanted it to.

That's ok, Uncle Twig has a fix for you and it's only 2 lines long.

To remedy this, make sure you do this on every custom Form.clean() function!

def clean(self):
if self.errors:
return self.cleaned_data

data = self.cleaned_data
# ...

That's it! At the start, if there's ANY errors at all, simply don't bother. No more invalid key exceptions.

Android: How to play button click sound

This stupid snippet was harder to find than expected!

Little did I know that it's part of the base functionality of a View.

All you need to do is call:

yourView.playSoundEffect(SoundEffectConstants.CLICK);

And you'll have yourself some annoying clickity click!

Best thing is you don't have to worry about silent mode either, system handles all that for you.

kprywnakn7 
Enjoy your success!

Source

Python: How to parse XML/RSS feeds with namespaces using lxml.etree

Alright, this one had me stumped for a good hour or two.

Take for example a Flickr RSS feed.

image

Those namespaces are a pain, but it's not too bad if you can sort them out before you use them.

# Some basic setup
from urllib2 import urlopen
from lxml import etree

# Namespaces copied straight out of the feed source
namespaces = {
'media': "http://search.yahoo.com/mrss/",
'dc': "http://purl.org/dc/elements/1.1/",
'creativeCommons': "http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html",
}

# Untested fetching code, just for understanding
file = urlopen(feed_url)
xml = etree.parse(file)
item = xml.get_root().find('channel')[0]

Now here's the basic structure of an RSS feed item.

<item>
<title>For the lazy</title>
<link>http://www.flickr.com/photos/handles/7429952158/</link>
<description>blah blah blah</description>
<pubDate>Sat, 23 Jun 2012 21:59:07 -0700</pubDate>
<dc:date.Taken>2012-06-24T14:58:54-08:00</dc:date.Taken>
<author flickr:profile="http://www.flickr.com/people/handles/">Handles</author>
<guid isPermaLink="false">tag:flickr.com,2004:/photo/7429952158</guid>
<media:content url="http://farm6.staticflickr.com/5347/7429952158_962a849b30_b.jpg" type="image/jpeg" height="1024" width="768"/>
<media:title>For the lazy</media:title>
<media:thumbnail url="http://farm6.staticflickr.com/5347/7429952158_962a849b30_s.jpg" height="75" width="75" />
<media:credit role="photographer">Handles</media:credit>
</item>

To get information off those elements, you'll need some slightly different syntax.

# Now to fetch the data from the namespaced elements
media_title = item.find("{%s}title" % namespaces['media']).text

media_thumbnail = media_title = item.find("{%s}thumbnail" % namespaces['media'])
thumbnail = {
'url': media_thumbnail.get('url'),
'width': media_thumbnail.get('width'),
'height': media_thumbnail.get('height'),
}

taTtM
Problem solved, like a boss!

Source

Diablo III: Extracting graphics from .tex files from MPQ and converting them to PNG (or whatever you want)

As always, once I'm bored with a Blizzard game I usually snoop around to see what's in the MPQ files. Diablo 3 is no exception.

Ingredients

Recipe

OK, I'll be honest. I'm going to assume you have a fair level of computer browsing competency. Some of these tools are still in their infancy so they're not the most user friendly.

If you're gonna need help figuring out how to extract things, navigating folders on your computer or editing batch files, you might want to get someone to help you.

  • Start up MPQ Editor
  • Open "Diablo III\Data_D3\PC\MPQs\Texture.mpq"
  • Browse to the "Textures" folder and extract the files you want to "C:\d3textures\" (or whatever folder you want)
  • Feel free to close MPQ Editor if you want.
  • Also extract "xvi32.exe" and "D3Texconv.exe" into that folder.

Now for a little explanation to the stuff you're about to do.

If you go ahead and attempt to convert the .tex files, you're gonna get an error saying "Invalid Texture or Surface (SNO Header Mismatch)". I'm not going to pretend I know what that means.

The whole reason why we have a hex editor is because we can tweak the files to be correct. But of course, we're lazy and we don't want to do it by hand to all 17,000+ TEX files.

  • Now create "textures.xsc", edit it in notepad and paste the following:

ADR 0
REPLACE EF BE AD DE 2D BY EF BE AD DE 2B

  • Save and exit.
  • Create another file called "texfix.bat", open up for editing in notepad. Paste the following (and change your paths if required)

@for /f "tokens=*" %%a in ('dir /b *.tex') do ( "C:\d3textures\xvi32.exe" %%a /S="C:\d3textures\textures.xsc" )

  • Save and exit.
  • Create one last file called "convert.bat", edit and paste:

@for /f "tokens=*" %%a in ('dir /b *.tex') do D3TexConv.exe %%a

  • Save and exit.

Now we're ready to roll!

  • To patch up all the TEX file headers so D3TexConv can read it, run "texfix.bat".
  • Once that's done, run "convert.bat" to extract the DDS data from the TEX files.
  • You'll now get a whole stack of TEX, DDS and TXT files. The only ones you care about are the DDS ones.
  • Install IrfanView and the plugins pack.
  • Now you should be able to view the DDS files.
  • Select the images you want and batch convert them into PNG (or whatever other format you need)

This should take a good while, but you'll be messing with the graphic files in no time!

image
Browsing the converted PNG files using ACDSee

Sources

Big thanks all round to all the crazy ass reverse engineers who've worked on this. I really don't know who they are, but only through their hard work has this been possible.

I've done my best to source my information so I hope you guys eventually get the credit you deserve!

Windows 7: Automatically connect to wireless network

I was a little perplexed to why the network wasn't reconnecting after a reboot.

I've set it to automatically connect even if SSID isn't even detected.

To fix it, you'll need to have administrator access.

  • Open up Windows Explorer
  • Paste in "C:\ProgramData\Microsoft\Wlansvc\"
  • Right click the folder "Profiles"
  • Properties
  • Security
  • Click "Edit"
  • Select "Everyone"
  • Under "Allow", click tick "Full control"
  • Click OK to save

Most people recommend deleting the "Interfaces" folder under "Profiles". Try my method first, since you won't lose any data.

Secondly if you delete the folder, you'll have to re-enter all the wireless password and settings back in.

tumblr_lfkbc8HspD1qzu6nx 
Now get back to what you're doing before you lose any more time aging!

Sources

Dell: Replace all driver "download" buttons with direct links (Australian)

I'm not sure if this works on the US site, but this worked a treat for me on the Australian site.

The main issue was I was getting annoyed with the Javascript download question asking me to use the download manager.

I just wanted to queue up files into my own download manager and batch download the files during my off-peak period.

When you're on the driver download page, open up Firebug and paste this into the console.

var rex = /javascript:DownloadFile\('\d+','\d+','.+','(.+)','\w+','HTTP'\);/;

var x = $('a[href*="javascript:DownloadFile"]').each(function(index, item) {
var obj = $(item);
var href = obj.attr('href');
var match = rex.exec(href);

if (match != null) {
var url = unescape(match[1])
obj.attr('href', url);
}
});

This will change all the "download file" buttons so they point to the direct file download link.

I'm sure someone can easily convert this into a GreaseMonkey script.

BOXOd

Now, back to the horrors of formatting!

PostgreSQL: ERROR: item pointer (16895,17) already exists

The numbers in the error are specific to you, but if you see something like this, be sure to check if your indexes are somehow corrupted.

  • In the console, type "\d tablename" to bring up the details.
  • Under the table, you'll see a list of indexes.
  • For each index, type "reindex INDEX indexname"

Try performing your query again.

barrel-roll
Do a barrel roll!

Android: Upgrading Samsung i9000 to Gingerbread 2.3.6 (build XWJW6, baseband XWJW1) with root

<rant>Alright, I'll be honest. This whole Android flashing business is way more complicated than it should be.

WTF is with all these stupid build "numbers"!? They're not very comprehensible for the average person.</rant>

12-monkeys-crazy-2-o 
My reaction when reading a typical Android-hacker post from XDA

Anyways, I've tried to simplify this process down as much as possible.

Preliminaries

First off, some checking. You need to have the 3-button download/recovery mode fix working in case shit hits fan. It did for me and it'll definitely save your ass if it happens to you. If you decide to proceed without fixing this first, you're either very brave or very stupid.

To test it, turn your phone off. Hold Volume Down + Home + Power to turn it on. If you enter download mode, then you're good to go.

Make sure you've backed up what you need!

Installing the firmware

What you'll need is:

This is probably the easiest part of the process.

  • Extract the firmware
  • Run Odin (without the phone plugged in yet)
  • Select the PDA/Phone/CSC files accordingly
  • Put the phone into download mode
  • Connect via USB
  • When Odin's label turns yellow and assigns the phone a COM port, click Start.
  • Wait a few minutes while it performs the update.
  • It should restart by itself.

If Odin3 gets stuck on "SetupConnection", just make sure you plug the phone in quicker after starting up Odin. It's a bit fussy.

Rooting your phone

Initially I was going to write about it here, but it was getting too lengthy already and not everybody will need it.

I tried a few different root techniques but not all were stable or easy. I eventually found one that's super easy and stable, so if you're keen on rooting your phone, see this post.

Fix your APN's

Remember, the downside to flashing your phone is that you will lose some settings. This also includes stuff like settings for internet and MMS.

If you're an Aussie, you can get the settings from Ausdroid APN.

Sources

Android: Samsung Galaxy S i9000 3-button download/recovery mode fix

Man, I've been putting this one off for years. Not sure why it only affect some models, but a lot of phones left the factory with a faulty secondary bootloader (SBL).

Because of this, it won't recognise the Volume Down + Home + Power combo.

I had to filter through a LOT of jargon and version hunting for these steps.

Prerequisites

  • Removed SIM and SD cards.
  • Phone in USB debugging mode.
  • Without charging or USB connection, type *#0228# in the phone dialer and ensure that the "Voltage" is at least 3800 (mV).
  • Phone detected by computer.
  • Hex codes on your BML1 block (I won't lie, I have no idea what this means. Just check below for instructions)

Just a word of advice, DO THE CHECKS before applying this bootloader. Otherwise you'll brick it, no questions asked.

This is copy pasted from the thread, so please make sure your phone is compatible before fixing the SBL.

HOW-TO check if your mobile is compatible (Windows):
Step 1: Download the XVI32 Hex Editor
Step 2: Dump your BML1 block (rooted phone needed)

 

Open a new command prompt and type:
adb shell
su (a superuser request will be displayed on the phone screen, accept it).
dd if=/dev/block/bml1 of=/sdcard/bml1.dump

The dump will be copied to the root of the internal SD card.

Step 3: Open the bml1.dump file with XVI32.
Step 4: Search (in ASCII Mode) for OFNI.

If the block reads "!@" just follow the tutorial below starting with Step 1.
If it reads "x0" then STOP as this FiX will BRICK your phone if applied !!

Downloads

I really wanted to use Heimdall for this, but it just wouldn't let me.

  • Odin v1.7
  • I already had adb.exe from the Android SDK package. There are plenty of places to get this.
  • Modified SBL

Procedure

  • Open up a command prompt and navigate to adb.exe
  • Type "adb reboot download" to enter download mode
  • Run Odin
  • Wait for the "COM###" label to turn yellow
  • Click on the PDA button and select "P-SBL.tar.md5.tar"
  • Tick "Phone BootLoader update"
  • Tick "Autoreboot"
  • Tick "F.Reset Time"
  • Ensure the other options are NOT ticked.
  • Click start whenever you're ready

The whole process will only take a few seconds. You may need to reboot your phone manually.

Turn the phone off and test if download mode works (Volume Down + Home + Power).

Ensure that your phone still works! For me, it got stuck on the loading screen and refused to start up. Take out the battery and try it again.

If it doesn't work, you'll have to reflash your firmware. This doesn't break the bootloader though, so feel free to reflash.

Sources

Android: Gingerbread 2.3.6 root for Samsung Galaxy S i9000

SuperOneClick. That's all there is to it. No jibberish jargon, checking of build versions, phone models, etc. SO EASY!

There's more information about it here on XDA, but this program worked a charm on my phone where the other methods weren't so "clean".

Preparation

Make sure you've got:

  • Microsoft .NET Framework 2.0+ or Mono v1.2.6+
  • One of the supported operating systems (Vista+, Ubuntu Hardy+, Debian Lenny+)
  • Phone on USB Debugging mode
  • Computer detects your phone (may require USB drivers for your phone to be installed)
  • Download "Mount /system (rw/ro)" app

Procedure

  • Download the package, extract. I tried this on v2.3.3.
  • Run SuperOneClick.
  • Plug in the phone
  • Click root
  • Wait for it to finish
  • Unplug and reboot the phone manually

It couldn't be simpler!

*edit 25/6/2012* (Added following bits)

Now the last part.

You still won't be able to edit system files because the /system folder is mounted as read only. To change that to read/write, you'll need the "Mount /system (rw/ro)" app.

Start it up, enable write and away you go!

Sources

Python: Print stack-trace

Surprisingly, this doesn't come as a standard function in the Exception class.

import traceback
try:
raise Exception("print exception!")
except:
print traceback.format_exc()

Short and simple, so good!

21e03c8c-ca74-4007-a3af-631871431c2c

Source

Windows: Find and delete files of a given pattern (also searching subdirectories)

I needed a quick way to clear out all the compiled Python ".pyc" and Java ".class" files on my drive, and searching via Windows Explorer is just slow.

  • Open up a command prompt.
  • Go to the folder to start from.
  • Type in:

del /S *.pyc

del /S *.class

It'll all be over after the wall of text has finished moving.

8QmIp 
So simple, so effective.

Source

CPanel: No Such User Here \ Sender verify failed

Well, this one had me baffled for a while. I thought that the user had to exist before I could send emails "from" that address.

But that makes no sense if I were to ignore all emails from noreply@thatawesomeshirt.com.

So, I did a little research and discovered that it's a CPanel setting!

Log into your CPanel and go to "Email" > "Set default address".

You can choose to forward the email to a valid address, but in the case of a "no-reply", just discard it by selecting "Discard (Not Recommended)".

Click "Change" to save.

3bBTW
This is what I felt like after putting up with error emails for so long...

Source

Python: Get string value of a PIL Image without writing to a temporary file

It's often useful to fetch the raw image data without having to save it to a file first (eg. as serving images by HTTP or sending email attachments)

To do that, we make use of the class StringIO.

import StringIO

# Save the file to a temporary file because that's how email attachments work
output = StringIO.StringIO()
pil_image.save(output, format = "PNG")
email.attach(filename = "whatever.png", mimetype = "image/png", content = output.getvalue())
output.close()

And there you have it!

425770_391213704223668_100000051259380_1581660_222260695_n

Source

Linux: How to scroll back up in GNU screen

Screen is a handy little thing that lets you run an extra persistent console in the background which stays active after you disconnect.

However, scrolling back up the screen buffer is a tad more tricky.

After using it on and off for a few years, I've finally run into the need to scroll up to see what's in the buffer.

To do that:

  • Press Ctrl+A
  • then [
  • And use J or K to move up and down (or the arrow keys)

41bde299_abc5_36ea
Enjoy!

Source

Python: Convert RFC 2822 string to datetime with timezone support

Since it's such a short snippet, I'll keep this post nice and simple.

from email.utils import parsedate_tz
print parsedate_tz('Fri, 15 May 2009 17:58:28 +0700')

That's it!

Source

Eclipse: Install HTML editor plugin

This is a lightweight editor plug-in with syntax highlighting and folding.

My Eclipse didn't have it, probably because I downloaded the classic release without all the extra Java trinkets.

Firstly, find out which release you're on. It usually displays a name under the word "Eclipse" on the splash screen when loading.

Then go to:

  • Open the "Help" menu
  • Click "Install new software"
  • Select "<your release name> - http://download.eclipse.org/releases/<release name>" from the dropdown
  • The URL could be http://download.eclipse.org/releases/galileo or http://download.eclipse.org/releases/indigo, depending on what you've got installed.
  • Wait for it to load...
  • Go to the bottom of the list and expand "Web, XML, and Java EE Development"
  • Select ONLY "Web Page Editor"
  • Click "Next"
  • Next again.
  • Accept agreements and finish
  • It may ask for you to accept the certificates when it's finished downloading. Tick the checkbox next to the item in the list and then click Next to install.
  • When it's done, it'll ask you to restart Eclipse. Do it.

Once your back in Eclipse, try editing a HTML file.

If it's not highlighted, you'll have to:

  • Open the Window menu
  • Click "Preferences"
  • General > Editors > File Associations
  • Select *.html
  • Select "HTML Editor" (not web page editor)
  • Click "Default"
  • Click "OK" to save

0df061d558a1bc8921bc7d11e829db19df94e6b3
You should now have a great HTML editor!

Source

Windows Live Messenger: How to disable Smartscreen security page?

This thing was driving me NUTS!

After upgrading to the new Messenger, I contemplating going back because I often receive dev links from workmates.

Unfortunately, these dev links are marked as "low traffic sites" and "isn't well known" because, well. they're secret dev links...

An example of the annoying "Protect yourself" screen is here:

image

Seriously, I'm not protecting myself, YOU ARE. STOP IT!

It might just be an extra click, but it's annoying!

Firstly, disabling Internet Explorer's smart screen filter won't fix anything. This is coming straight from WLM 2011 into your default browser (Firefox/Chrome/etc).

Secondly, GreaseMonkey scripts are flakey at best.

To properly disable it:

  1. Click on "More info" to expand some text.
  2. "Don't show me this message again"
  3. "Continue anyway"

tumblr_lzu7et1yWh1qdlh1io1_400
Now, back to being productive.

Sony Vaio Gate: How to uninstall?

Argh preinstalled software which cannot be uninstalled... the worst kind.

Usually you can just uninstall crap like this from the control panel or from the Vaio Care suite, but no not this one...

Open up a command prompt and paste these instructions.

regsvr32 /u "C:\Program Files\Sony\VAIO Gate\VAIOGateDesktopShellExt.dll"
regsvr32 /u "C:\Program Files\Sony\VAIO Gate\EN-US\VAIOGateShellExt.dll"
del /F "C:\Program Files\Sony\VAIO Gate"

And viola!

grandfather_clock 
Anything else I can help you with?

Synaptics Scrybe: How to uninstall

When I downloaded the latest drivers for Synaptics touchpad, I didn't expect it to come with Scrybe (even though the package specifically says "with Scrybe")

Well, when I saw it appear on my taskbar my immediate instinct was to kill it. What foul heathen dare trespass on my grounds!?

Shamefully, there was no uninstaller provided. Strangely enough, it was easy to kill it, which I'm not complaining about.

  1. Delete it from your startup folder (Start menu > All Programs > Startup > Scrybe > Right click> Delete)
  2. Quit Scrybe (Right clickon Taskbar icon, exit)
  3. Run the following commands

net stop ScrybeUpdater
sc delete ScrybeUpdater
del /F "C:\Program Files (x86)\Synaptics\Scrybe"

Obviously replacing "Program Files (x86)" with "Program Files" if you've got 32bit Windows.

57327

Eat that bundleware!

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