Convert stereo mp3 files in a folder to mono using ffmpeg

for f in *.mp3; do ffmpeg -i "$f" -c:a libmp3lame -q:a 2 -ac 1 mono-"$f"; done

Selecting Python version in MacPorts

List installed versions:

port select --list python

Select the preferred version, e.g.

sudo port select --set python python27

For more info:

port help select

Reducing the size of a scanned pdf using ImageMagick

Combining the brightness and contrast adjustments, quality and compression:

 convert -brightness-contrast 5x10 -set colorspace Gray -compress jpeg -quality 10 -density 150 inp.pdf out.pdf 

Configure Tor to use a node in a specific country

Create a configuration file, say “torrc”

(Default configuration file and a sample file location in Mac OS X Lion: /usr/local/etc/tor/)

Include the following lines in the configuration file:

ExitNodes {TR}
StrictExitNodes 1

Run Tor from the Terminal:

tor -f /Users/admin/Documents/Python/MyProject/torrc

To test it with Python:

from selenium import webdriver
import socket
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '')
profile.set_preference('network.proxy.socks_port', 9050)

Useful link for checking Tor status, Tor servers with country information, etc:

See also:

Start OS X in Safe Mode

Set safe mode:

sudo nvram boot-args="-x"


sudo nvram boot-args=""

Recover lost administrator password in OS X (Lion)

Restart the computer in single user mode:
Restart and hold Cmd+s

fsck -fy
mount -uw /
rm /var/db/.applesetupdone

After reboot is completed, go through the wizard. Open System Preferences –> Users and Groups –> reset password of the previous (original, non-root) user.

Reboot and login to the original user.

Generate n-gram Language Profile using the Language Detection Library for Java

For creating n-gram data from xml-formatted Wikipedia abstract files to be used with the language-detection library for Java/Processing:
  • At the same folder as the downloaded file, create a folder called profiles.
  • In Terminal, cd into that folder.
  • Run the following line by replacing the last argument with the language code of your downloaded file (here tr is used for Turkish):

java -jar /[PathToLangDetectFile]/langdetect.jar --genprofile -d ./ tr

More information:

Language codes:

Using Python urllib2 via Tor

If socks is not installed:

sudo easy_install SocksiPy-branch

Then the following code to check the new IP:

import socks
import socket
def create_connection(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    return sock

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "", 9050)

socket.socket = socks.socksocket
socket.create_connection = create_connection

import urllib2

    # Check IP
    print urllib2.urlopen("").read()
    # Change and check user-agent which is normally Python-Urllib2
    req = urllib2.Request("")
    req.add_header('User-agent', 'Mozilla 5.10')
    res = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.code
except urllib2.URLError, e:
    print e.args

Saving Screenshots of Webpages using Python+webkit2png

Example for scanning and saving Google Mars images:

import os 
for j in range(120):
  for i in range(180):
    os.system('python webkit2png -F -W 1280 -H 800 -D img -o test%(imgnum)05d ""'  % {'imgnum': j*180+i, 'lon': 2*i-180, 'lat': j-60} )

Python ile Türkçe heceleme

Girilen metni önce kelimelere ayırıyor, sonra da hecele() fonksiyonu ile heceleri arka arkaya ekrana yazıyor. Girdiyi metin dosyasından okur hale gelirse hece istatistiğinde kullanılabilir.

#! /usr/bin/python
# -*- coding: utf-8 -*-

import sys

def lowercase(ch):
	return {
	}.get(ch, ch.lower())
def sesli(ch):
	ch = lowercase(ch)
	if ch in [u'a', u'e', u'i', u'ı', u'o', u'ö', u'u', u'ü']:
		return True
		return False

def hecele(str):
	while sesli(str[index]) == False and length>index+1:
		if sesli(str[index+1]):
			print str[0:index+1],
		elif length>index+2:
			if sesli(str[index+2]):
				print str[0:index+1],
			elif length>index+3:
				if sesli(str[index+3]):
					print str[0:index+2],
					if str[index+1:index+4] in [u'str', u'ktr', u'mtr', u'nsp']:
						#print "istisna!.."
						print str[0:index+2],
						#print "üç sessiz, normal kural"
						print str[0:index+3],
				print unicode(str),
			print unicode(str),
		print unicode(str),

inp = raw_input("hecelenecek kelime: ").decode(sys.stdin.encoding)
inp = inp.strip('."\',;')
words = inp.split()
for word in words: