Selenium with Tor+Firefox (Mac)

Install Selenium:

sudo easy_install selenium

If Homebrew is not installed:

ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

Install Tor:

brew install Tor

Run Tor:

tor

In another terminal window, run the python code to open Firefox+Tor and save a screenshot via Selenium:

from selenium import webdriver
profile=webdriver.FirefoxProfile()
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '127.0.0.1')
profile.set_preference('network.proxy.socks_port', 9050)
browser=webdriver.Firefox(profile)
browser.get("http://yahoo.com")
browser.save_screenshot("/Users/admin/Pictures/screenshot.png")
browser.close()

See also:

Image resize to portrait height or landscape width using Python & PIL

from PIL import Image

filename = "car_.jpg"
im = Image.open(filename)

ratio = float(im.size[0]) / float(im.size[1])
print ratio
if ratio > 1:
	target_size=(500, int(500/ratio))
else:
	target_size=(int(500*ratio),500)
im2 = im.resize((target_size), Image.NEAREST)  # use nearest neighbour
im2.save("resized/"+filename)
print filename + "resized to " + repr(target_size) + " and saved."

Creating an animated gif from images

In ffmpeg, for framerate=1:

 ffmpeg -i as%2d.jpg -pix_fmt rgb32 -r 1 out.gif 

This will reduce the 32-bit images to 24-bit ones.

Better results using ImageMagick:

convert -delay 100 -loop 0 as*.jpg out2.gif

Get host by IP address

Code to scan a certain range of IP addresses and display the corresponding hostnames:

import socket
socket.setdefaulttimeout(1)
for octet1 in range(64,64):
	for octet2 in range(233,233):
		for octet3 in range(160,191):
			for octet4 in range(0,255):
				ip = str(octet1)+"."+str(octet2)+"."+str(octet3)+"."+str(octet4)
				print(ip)
				try:
				    print (socket.gethostbyaddr(ip))
				except socket.herror, e:
				    print e
				

Automatically change Mac OS X DNS settings using bash

Saved as an executable file (by running “chmod 755” in Terminal), following code changes the DNS servers used by the selected network adaptor to OpenDNS servers. Modify the name of the adaptor “Ethernet Adaptor (en3)” to fit the active network adaptor you are using.


#!/bin/bash
networksetup -setdnsservers "Ethernet Adaptor (en3)" 208.67.222.222 208.67.220.220;
exit;

Language Detection in Processing

Simple sketch using the Language Detection Library for Java:

import com.cybozu.labs.langdetect.*;
 Detector detector;
 void setup() {
 try {
 DetectorFactory.loadProfile( "/path/to/Documents/Processing/mysketch/code/profiles" );
 detector = DetectorFactory.create();
 }
 catch ( Exception e ) {
 println( e.getMessage() );
 }
 int i = millis();
 try {
 detector.append( "naber abi, nasılsın?" );
 String lang = detector.detect();
 println( ( millis() - i ) + " milliseconds to compute -> " + lang );
 }
 catch (Exception e) {
 println( e.getMessage() );
 }
 }

Useful ffmpeg Commands

Create a FLV video from images:

ffmpeg -r 20 -b 1800000 -i /path/to/myimages%03d.jpg  /Users/macbook/Desktop/out.flv
ffmpeg -s 600x400 -r 20 -b 1800000 -i /path/to/myimages%03d.jpg  /Users/macbook/Desktop/out.flv

Extract images from a video:

ffmpeg -i myinput.avi -r 30 -f image2 folder/myimage%04d.png

Extract images from a video with a fractional frame rate and same image quality:

ffmpeg -i /path/to/myvideo.mov -r 1/2 -sameq outputimages%03d.jpg

Resize + convert (order is important):

ffmpeg -i /path/to/inputvideo.mp4 -s 200x150 /path/to/outputvideo.mov

Convert for ZS4 Video Editor:

ffmpeg -i /path/to/inputvideo.mov -vcodec rawvideo /path/to/outputvideo.avi
ffmpeg -i /path/to/inputvideo.mov -acodec pcm_s16le -vcodec rawvideo /path/to/outputvideo.avi

Display duration:

ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 /path/to/sound.aiff

Create video with sound from images + audio file:

ffmpeg -framerate 24 -start_number 1 -i screen-%04d.tif -i 02.aiff -c:v libx264 -r 24 -pix_fmt yuv420p -c:a aac -strict experimental output.mp4

Loop x times and export:

for i in {1..10}; do printf "file '%s'\n" input.mp4 >> list.txt; done
ffmpeg -f concat -i list.txt -c copy output.mp4

Change aspect ratio by cropping:

ffmpeg -i input.mp4 -vf "crop=in_w*3/4:in_h" -strict -2 out4x3.mp4

Unicode Text Statistics in Python

import nltk
import codecs
f = codecs.open('/path/to/input.txt', encoding='utf-8')
raw = f.read()
raw = raw.lower()
tokens = nltk.wordpunct_tokenize(raw)
text = nltk.Text(tokens)
fdist1=nltk.FreqDist(text)
voc = fdist1.keys()
output_file = codecs.open('output.txt', 'w', 'utf-8')
index = 0
for term in voc[:500]:
 output_file.write(term)
 output_file.write(' ')
 output_file.write(unicode(fdist1[term]))
 output_file.write('\n')
 index+=1
output_file.close()