Wednesday, September 28, 2011

Friday, September 23, 2011

[Python] Easy Facebook Scripting.

Need a small and neat api for doing Facebook scripting? Look no further!


from urllib import urlretrieve
import imp
urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fbconsole.py'
fb = imp.load_source('fb', '.fbconsole.py')
fb.AUTH_SCOPE = ['publish_stream']
fb.authenticate()
status = fb.graph_post("/me/feed", {"message":"Hello from my awesome script"})
#Note: Recommend that you download fbconsole.py locally with eg. wget https://raw.github.com/gist/1194123/fbconsole.py

Post a status update:
status = fb.graph_post("/me/feed", {"message":"Hello from my awesome script"})

Fetch likes on a status update:

likes = fb.graph("/"+status["id"]+"/likes")
Delete a status update:
fb.graph_delete("/"+status["id"])
Upload a photo:

fb.graph_post("/me/photos", {"message":"My photo", "source":open("my-photo.jpg")})
Query FQL tables:
friends = fb.fql("SELECT name FROM user WHERE uid IN "
"(SELECT uid2 FROM friend WHERE uid1 = me())")


Source:  Easy Facebook Scripting in Python

Tuesday, September 20, 2011

[Linux]Redshift.

This kinda neat if you have sensitive eyes. Redshift adjusts the color temperature according to the position of the sun.

Introduction:

Redshift adjusts the color temperature of your screen according to your surroundings. This may help your eyes hurt less if you are working in front of the screen at night ...

Installation:

Ubuntu: Packages for Ubuntu.

[Linux] Create your own Cloud service #2.

http://sparkleshare.org/

Another post regarding Cloud service:

http://patrick-henriksson.blogspot.com/2011/09/linux-create-your-own-cloud-service.html

Saturday, September 17, 2011

[Linux]KILL THE CAPS-KEY NOW PLEASE!

The most annoying and useless key, just simply:

setxkbmap -option caps:super




This will map caps-lock to the super key. If you wanna add this feature permanently you could add it to your .profile file.

Friday, September 16, 2011

[Linux]List available upgrades from the terminal.

sudo apt-get update;apt-get -s upgrade
Will list packages that are available for upgrades on Debian-based systems.

[Linux]Enable encrypted home folders in Ubuntu.

Introduktion:

Sometimes you want to keep your sensitive information/data for yourself. And most of the time you will store private documents and files in your home folder. A way of keeping this private is to use encryption for the home folder.

Thursday, September 15, 2011

[Linux]BootUp Manager.

The scripts located in /etc/init.d are part of the bootup sequence of every Debian-like distro. Very often Ubuntu's documentation and guides have suggested - in order to deactivate init scripts - to change the permissions of the scripts in /etc/init.d, making them non-executable.

This will have the following consequences:

Wednesday, September 14, 2011

[Linux]Join a Windows Domain with Ubuntu.

This could be resolved in many different ways(e.g. Samba) but it could also be a real struggle.

[Other]Install Windows 8 developer preview.

Ok, I know! Windows is not my usual topic when it comes to this blog but since i'm a curious person this has to be done :-)

You can try out Windows 8 developer preview in Virtual box by doing following:

Tuesday, September 13, 2011

[Linux] Create your own Cloud service!

With ownCloud!

Features

Current
file management, WebDAV access, sharing, music streaming, users & groups, OpenID, LDAP, unhosted storage

In development
encryption, calendar, contacts, bookmarks, desktop sync client, Android & webOS apps, server-server sync

Planned
file editing, versioning & recovery, connecting to other services

Installation

Monday, September 12, 2011

[Linux] Quick encrypt a file with openssl.

Sometimes you may need to a quick solution for encrypting a file. You can use openssl for this.

Friday, September 9, 2011

[Linux]Mark your Ubuntu server.

Wanna put your Ubuntu server on the map? Then visit this site: http://maps.ubuntu.com/



[Linux]Reboot required?

Doing updates on your Ubuntu installation sometime results in a recommended reboot(for example installing a new kernel). But how do we check if a reboot is required(if you have no access to a GUI or running Ubuntu server)?

Thursday, September 8, 2011

Learn in OOP in the most amusing way.

Having issues trying to understand all that weird concepts when it comes to OOP? Fear(!) not! This is probably the most funny and educating paper I have seen when it comes to approaching OOP.

Dont Fear The OOP.pfd

[Linux] Debugging Bash scripts.

Not a fun but still a necessary task when it comes to bash scripting.

Debugging the entire script:

bash -x myScript.sh


Debugging parts of script:

    set -x : activate debugging.
    set +x : stop debugging.
Example:

#!/bin/bash

echo "Simple example script\n"

set -x
for i in $(seq 3)
do
   echo "Hello World!"
done

set +x
echo "Done debugging!"

exit 0
Alternative:

Replace the shebang with following:

#!/bin/bash -xv
 

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan

Monday, September 5, 2011

[Linux] Create a random password.

cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 10 | head -n 1

tr=type of characters
fold=length of password

Sunday, September 4, 2011

[Linux] Simple sync/backup script.

Just polished my backup script including wake on lan. Just a simple script, but still essential to me.

#!/bin/bash

#function for syncing folders
function sync {
rsync -avrz /folders/to/sync user@host:/destination/folder
rsync -avrx /var/www/data/ ~/Dropbox/wiki/ #makes my wiki pages accessible remotely
}

#function for shutdown remote host, remember to change the rights for the poweroff command(eg. chmod u+s(Set the suid bit) poweroff)
function shutdown {
ssh user@host "poweroff"
}

#wol function, requires the wakeonlan package(on Ubuntu, apt-get install wakeonlan). Or you could use my python script(link).
function wol {
wakeonlan macaddress
}

#check if host is up(my rules: if server is up, only sync. If down start server, sync and then shutdown.
if ping -c 3 host
then
        sync
else
        wol
sync
shutdown
fi

exit 0

Note: Since we are using SSH for remote access it's a good idea to setup SSH login without password, follow this link

Note2: This is added to the crontab for automatic execution once a day.

Note3: I'm using hostname lookup instead of ip(which is assigned by my routers dhcp). This means that if my router suddenly changes the assigned ip(I know it's possible to reserve ip) the script is none dependend on ip. Use avahi-daemon and avahi-autoipd for this feature.

Friday, September 2, 2011

Books - Android Development.

I'm currently struggling to learn the Android Platform. Besides from following my absolutely favorite  The New Boston tutorials I also picked up this excellent book:

Beginning Android Application Development (Wrox Programmer to Programmer)

This usually my learning strategy, always use multiple sources.





Tuesday, August 30, 2011

Leveling in Vim.

Here is a nice guide if you are like me only knowing the basic and essential in Vim.

Learn Vim Progressively

Note: I'm currently on Level 2 :-)

Ubuntu issues?

Well then follow my directions: Ask Ubuntu!


Saturday, August 27, 2011

Magic package - WOL.

Python is fun! Did a script for Wake On Lan.

import socket

mac = "00:00:00:00:00:00" # mac address
decoded = "" # string for converting characters to hex

package = mac.split(':') # remove ':''

# iterate through mac address and convert to hex 2 characters at a time
for x in package:
decoded += x.decode('hex')

macAddress = '\xff'*6+decoded*16 # magic package!

#method for sending magic package
def wakeOnLan(mac):
mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
mySocket.sendto(mac, ('255.255.255.255', 9)) # broadcast address and port
mySocket.close()
wakeOnLan(macAddress) # Send it away baby!

---

Short version(where you have to manually edit the mac address):


import socket

macAddress = '\xff'*6+'\x00\x00\x00\x00\x00\x00'*16

def wakeOnLan(mac):
mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
mySocket.sendto(mac, ('255.255.255.255', 9))
mySocket.close()
wakeOnLan(macAddress)

get-flash-videos.

We all know that Linux and Flash doesn't play well together, especially if you're on a low spec system like me(laptop with a single core). I usually try to avoid Flash but sometime it's inevitably. This is were the get_flash_videos tool gets handy.

Description:

Download videos from various Flash-based video hosting sites, without having to use the Flash player. Handy for saving videos for watching offline, and means you don't have to keep upgrading Flash for sites that insist on a newer version of the player.

Supports Linux, Windows and OS X - see Installation for more details and how to install.

Includes support for the following sites/players (and more!):

YouTube, eHow, Brightcove (used by many sites like Channel 4, Daily Telegraph ...), BBC (news, etc), Metacafe, 5min, Google, fliqz, nicovideo, vimeo, Blip, Break, Collegehumor, Muzu, Sevenload, Megavideo, Wat.tv.

Also includes a 'generic' method which works on many other sites.

Friday, August 26, 2011

Hug a Tree.

Don't really know why im posting this but me and my daughter went for a walk in the forest last weekend. Really enjoyable, but on our way we came a cross a big tree and decided to give it a hug(don't ask me why).

If you're unsure how to hug here is a guide for you: Hug a Tree




Thursday, August 25, 2011

dmidecode.

I'm was going to upgrade the memory on my server and I was a bit unsure of which type of modules that was supported by the motherboard(DDR2/DDR3?). Couldn't find the manual or type of motherboard. And a second thing is that there is no monitor connected aswell. Well, this is how i solved that.

ssh server

sudo dmidecode --type 17 | more


And voilá!

# dmidecode 2.9
SMBIOS 2.5 present.

Handle 0x0027, DMI type 17, 27 bytes
Memory Device
Array Handle: 0x0025
Error Information Handle: Not Provided
Total Width: 64 bits
Data Width: 72 bits
Size: 1024 MB
Form Factor: DIMM
Set: None
Locator: DIMM0
Bank Locator: BANK0
Type: DDR2
Type Detail: Synchronous
Speed: 400 MHz (2.5 ns)
Manufacturer: Corsair
Serial Number: 00000000
Asset Tag: AssetTagNum0
Part Number: CM2X1024-6400

Using dmi is just great for a purpose like this!

man dmidecode
dmidecode is a tool for dumping a computer's DMI (some say SMBIOS) ta‐
ble contents in a human-readable format. This table contains a descrip‐
tion of the system's hardware components, as well as other useful
pieces of information such as serial numbers and BIOS revision.


RuntimeError: maximum recursion depth exceeded.

Fooling around with a simple recursive method. Apparently there is an default limit in Python preventing infinite recursion. You can bypass it by using following method of the sys class:

sys.setrecursionlimit(limit)

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.


Sample test:

# Simple recursive funcktion in Python
import sys

sys.setrecursionlimit(10000)

def method(arg):
if arg == 0:
print "End."
else:
arg -= 2
print arg
method (arg)

method(10000)




Process big text files in Python.

I'm pretty sure that you could do this in several different and better ways(as usual when it comes to coding). But this is my solution for reading big text files in Python.


from sys import argv

file = argv[1]
input = ""

inputData = open(file)

#Function for reading chuncks

def readChuncks():
return inputData.read(1024)

#Iterate through the file

for data in iter(readChuncks, ''):

input += data #process the data

inputData.close()



Any thoughts/comments/suggestions would be greatly appreciated :-)

Tuesday, August 23, 2011

You can imagine the Hollywood-type of scene where a group of Google engineers collude to delete everybody’s Gmail unless they’re given $3 million

Interesting article:

Keep ideas and information organised!

A great thing for keeping ideas and personal information is to install a local wiki on your computer. I just a great way to document things like code snippets, to do lists and so on.

This is my setup on my main laptop:
  • Lighttpd - A light blazing fast webserver.
  • Dokuwiki - Simple, but a great wiki(stores the pages in files so there's no need for a database server)
  • A simple rsync bash script for backing up the wiki to my main server through the network.



Saturday, August 20, 2011

DuckDuckGo on Time's top 50 websites.

My favorite search engine apparently made it to the top 50 websites of 2011 according to Time's.

So what's DuckDuckGo? Wikipedia summarize it as follow:

DuckDuckGo is a search engine based in Valley Forge, Pennsylvania that uses information from crowd-sourced sites (like Wikipedia) with the aim of augmenting traditional results and improving relevance. The search engine philosophy emphasizes privacy and does not record user information

What's makes this search engine stand out according to me is the privacy policy and the awesome function of what they call bangs. The bang function is simply a search function to search other sites directly.

Type a bang command like:

!amazon mad caddies - which will directly list all the albums of the artist.
!python - math - lists the methods of math class.
!askubuntu nvidia 11.04 - gets issues regarding Ubuntu 11.04 and Nvidia cards.

Other goodies you can use:

md5
password 15 strong
whois duckduckgo.com

And so on, check out all the bangs and goodies on DuckDuckGo.

Note: Try search for "Simpsons characters"

Link to Time's article.:

Like cartoons?

US economy explained in a simple manner.

Friday, August 19, 2011

Stanford University is...

Offering a free online course in databases. Check out following link:



Awesome! I really need to refresh my database knowledge. At this point 22,855 people have signed up(!)

Course Description

This course covers database design and the use of database management systems for applications. It includes extensive coverage of the relational model, relational algebra, and SQL. It also covers XML data including DTDs and XML Schema for validation, and the query and transformation languages XPath, XQuery, and XSLT. The course includes database design in UML, and relational design principles based on dependencies and normal forms. Many additional key database topics from the design and application-building perspective are also covered: indexes, views, transactions, authorization, integrity constraints, triggers, on-line analytical processing (OLAP), and emerging "NoSQL" systems.

Android educational video tutorials

Wanna start develop on the Android platform but you never have the time to read all those boring and ineffective 800 pages books? Well sir, then I have the following excellent video tutorials ready for you:


This is all provided by Bucky Roberts which is the man behind The New Boston(site). This guy is just amazing when it comes to sharing knowledge.

Don't know Bucky? Well, check this out:


Echo "Alright folks let's get it started in here..."

Gonna pinpoint the essence of this blog:

  • Linux
  • Python
  • Android
  • Life

Enjoy!