Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Friday, 27 May 2011

$100 Free Google Adwords Credit - from Hong Kong to Australia

Mail from Hong Kong
Today I received a letter from Google. The postmark and return address were both labeled "Hong Kong". Naturally I was more than a little curious as to what Google might be sending me from Hong Kong. As it turns out, the letter wasn't anything to do with Hong Kong at all.

The envelope contained a $100 gift card from Google Adwords, and a letter signed by Lucinda Barlow, Head of Marketing for Google Australia. Not Hong Kong. Either Google Australia uses Hong Kong for some of their mailouts, or they're sending out a global campaign and attaching local signatures depending on the destination. Either way, it's pretty crazy that mail sent to Australia comes from Hong Kong.

The full letter transcript is below:
Come back to AdWords and get $100 in free advertising

Hello from Google!

We understand how important it is for a business to stand out online - and that's one of the main reasons small businesses use Google AdWords everyday. Over the past year, we've made a lot of changes to make AdWords easier to use, and to help ensure your online ad campaigns deliver the results you expect. We hope you'll try AdWords again and are giving you $100 to get started.

There are a lot of things you can do to make your campaign more successful - refine your keywords, change your bid, or maybe try a new headline. We'd like to recommend the AdWords Online Classroom (www.google.com.au/adwords/classroom). It's a free resource that offers a series of video tutorials covering quick tips designed to help you get the most out of AdWords.

The first step is redeeming your $100 and reactivating your campaign. Then, it's just a matter of time, and a little bit of effort, before you start attracting new customers to your business.

Sincerely,

Lucinda Barlow
Head of Marketing, Google Australia

Wednesday, 2 June 2010

Javascript Card Guessing Game - Sample Code

I've been doing some coding in Javascript lately, and thought I would share some of the code I've been writing. Hopefully some of it will be useful for anyone looking for some sample code in Javascript, or examples of looping, keeping tallies, or writing basic functions.

Without further ado, here is the code. It's a simple playing card guessing game.
Javascript Card Guessing Game

Tuesday, 1 June 2010

Android: Using Accelerometer to Calculate Total Force

I'm in the process of building an app that calculates how far you could throw something, based on the speed you swing your phone. This involves tracking your phone's movement as you swing it, and calculating the total maximum force involved. I couldn't find any examples on how to do this, so I've mocked up a bit of a tutorial below.

How do we get the accelerometer values?

private SensorManager mgr=null;
mgr=(SensorManager)ctxt.getSystemService(Context.SENSOR_SERVICE);
mgr.registerListener(listener,
mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);



private SensorEventListener listener=new SensorEventListener() {
        public void onSensorChanged(SensorEvent e) {
            if (e.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
                //Total acceleration will be sqrt(x^2+y^2+z^2)
                double netForce=e.values[0]*e.values[0];    //X axis               
                netForce+=e.values[1]*e.values[1];    //Y axis
                netForce+=(e.values[2])*(e.values[2]);    //Z axis (upwards)
               
                netForce = Math.sqrt(netForce) - SensorManager.GRAVITY_EARTH;    //Take the square root, minus gravity
               
                Log.d("ForceCalculator", "Net force:"+netForce+"");
            }
        }
       
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // unused
        }
    };


This will create and register an event listener for the accelerometer. This listener then calculates the net force.

This calculation is pretty self-explanatory. It involves three components - X axis, Y axis, and Z axis. To calculate the magnitude of these vector components, we simply take the square root of their combined squares:
netForce = sqrt( x^2 + y^2 + z^2 )
The only point to note is that we then subtract the acceleration due to gravity (approx. 9.8m/s^2). Otherwise we could have a resting acceleration of +9.8.

Full code will be coming later, when I've got some more time to play around with it. For now, this should show you how to get net force using the accelerometer. Still to come is code to calculate maximum force over a specified period of time, with threshold starting and finishing velocities.

Wednesday, 17 February 2010

Ubuntu: How to automatically lock & unlock screen with Android phone

Evan Boldt has a useful script: Unlock your screen with ANY USB device. I've modified it slightly to work with my HTC Magic / Google Android device. A script is run every minute, which polls the system log every 2 seconds to determine when the USB device is plugged in in or unplugged. It then forwards the relevant command to GNOME Screensaver. The script is posted below for your interest.

Firstly, run lsusb and locate your phone. In my case, it was the highlighted line:

Bus 002 Device 002: ID 08ff:2580 AuthenTec, Inc. AES2501 Fingerprint Sensor
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 002: ID 045e:0752 Microsoft Corp.
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 002: ID 045e:0039 Microsoft Corp. IntelliMouse Optical
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 006: ID 0bb4:0c02 High Tech Computer Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub


Copy everything from ID to the end of the line (i.e. "ID 0bb4:0c02 High Tech Computer Corp.") This will be the ID used to determine when your device is plugged in & unplugged.

Paste this file into your /home/username/bin folder:

#!/bin/bash

#Replace with the ID of your USB device
id="ID 0bb4:0c02 High Tech Computer Corp." # Example: id="ID 05ac:1292 Apple, Inc"

#runs every 2 seconds
for ((i=0; i<=30; i++))
do
if [ -z "`lsusb | grep "$id"`" ]
then

    echo "Device is NOT plugged in"

    if [ -n "`DISPLAY=:0 gnome-screensaver-command --query | grep "is active"`" ]
    then
    if [ -e /tmp/autoUnlock.lock ]
    then
    #stop locking the screen
    rm /tmp/autoUnlock.lock

fi

elif [ -e /tmp/autoUnlock.lock ]
then

    DISPLAY=:0 notify-send -t 5000 –icon=dialog-info “Device Disconnected” “Bye!”

    #lock the desktop
    DISPLAY=:0 gnome-screensaver-command --lock

    rm /tmp/autoUnlock.lock

fi
else

    echo "Android IS plugged in"
    if [ ! -e /tmp/autoUnlock.lock ]
    then
    DISPLAY=:0 gnome-screensaver-command --deactivate
    DISPLAY=:0 notify-send -t 5000 --icon=dialog-info "Device Connected" "Welcome Back!"
    touch /tmp/autoUnlock.lock

    ##Uncomment the 3 following lines if you would like your computer to remind you if you lock your screen without disconnecting the device
    #echo "Don't forget your device!" > /tmp/androidReminder
    #DISPLAY=:0 festival --tts /tmp/androidReminder
    #rm /tmp/androidReminder
    fi

fi
sleep 2
done


Now you simply add a line to your crontab to run this script every minute:

crontab -e


add the line:

* * * * * bash /home/username/bin/autoUnlock & >/dev/null 2>&1


That's it! Now, when you unplug your Android phone it should lock the screen. When you plug in again, the screen unlocks. Easy!

More information:
http://echowarp.neomenlo.org/2009/scripts/unlock-your-screen-with-any-usb-device
https://help.ubuntu.com/community/UsbDriveDoSomethingHowto

Thursday, 11 February 2010

Google Buzz: How to publish to Twitter automatically

At present, Google Buzz has the ability to import, index and display your Tweets. One feature that is notably missing, however, is the ability to tweet from Buzz. You can't export Google Buzz to Twitter. At least, not officially.

I've written a python script to grab your Google Buzz feed (as detailed in the Buzz API), and automatically post your Buzz-es to Twitter. It includes a link back to the original Buzz URL (shortened with Bit.ly) It also uses a local sqlite database to store previous posts, and print bit.ly statistics for your published links.

You'll need to have python installed, and the following modules:
python-twitter
python-bitly
python-sqlite
feedparser
You'll also need a free account at Twitter and Bit.ly, and a Bit.ly API key.

Download the python source code from Google Code, or copy the text below. Please let me know if you found this useful, or have any improvements or modifications to suggest.


Update: To run this script every minute, add the following line to your crontab:
* * * * * /path/to/buzz-twitter-bot.py
This will update Twitter with your Google Buzz posts at least once per minute.

Code:

#!/usr/bin/python
from time import strftime
import sqlite3
import sys
import re

import twitter     #http://code.google.com/p/python-twitter/
import bitly       #http://code.google.com/p/python-bitly/
import feedparser  #available at feedparser.org


DATABASE = "tweets.sqlite"

BITLY_LOGIN = "username"
BITLY_API_KEY = "insert_your_key"

TWITTER_USER = "username"
TWITTER_PASSWORD = "secret"

def print_stats():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
c = conn.cursor()

b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)

c.execute('SELECT title, url, short_url from RSSContent')
all_links = c.fetchall()

for row in all_links:

short_url = row['short_url']

if short_url is None:
short_url = b.shorten(row['url'])
c.execute('UPDATE RSSContent SET `short_url`=? WHERE `url`=?',(short_url,row['url']))


stats = b.stats(short_url)
print "%s - User clicks %s, total clicks: %s" % (row['title'], stats.user_clicks,stats.total_clicks)

conn.commit()

def tweet_rss(url):
print "Opening database...."
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
c = conn.cursor()
print "Database opened."

#create the table if it doesn't exist
c.execute('CREATE TABLE IF NOT EXISTS RSSContent (`url`, `title`, `dateAdded`, `content`, `short_url`)')

print "Logging in to Twitter...."
api = twitter.Api(username=TWITTER_USER, password=TWITTER_PASSWORD)
print "Logging in to Bitly...."
b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)

print "Parsing feed...."
d = feedparser.parse(url)

for entry in d.entries:

#check for duplicates
c.execute('select * from RSSContent where url=?', (entry.link,))
if not c.fetchall():
print entry
#Get data from this entry
title = entry.title
content = entry.content[0].value
link = entry.link
updated = entry.updated
#Strip HTML from content
r = re.compile(r'<[^<]*?/?>')
content = r.sub('', content)

print "Found new item"
print "Title: "+title
print "Content: "+content
print "Link: "+link
tweet_text = "Buzz: %s" % content

#Shorten link
print "Shortening link...."
shortened_link = b.shorten(link)
print "Shortened link: "+shortened_link

#Add this entry to the database
t = (link, title, updated, content, shortened_link)
c.execute('insert into RSSContent (`url`, `title`,`dateAdded`, `content`, `short_url`) values (?,?,?,?,?)', t)
print "%s.. %s" % (tweet_text[:115], shortened_link)

#Post to twitter
print "Posting to twitter...."
api.PostUpdate("%s.. %s" % (tweet_text[:115], shortened_link))
print "Post complete."

conn.commit()

if __name__ == '__main__':
tweet_rss(sys.argv[1])
print "Listing stats...."
print_stats()

Special Thanks to Halotis for the RSS Twitter Bot, and love-python.blogspot.com for how to strip HTML tags.