Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Saturday, June 6, 2009

Quick Remote Editing With Vim

I am sure that anyone who has created their own website has had to make simple edits. There are many ways that one may connect, edit, and then publish the changes and all of these ways accomplish the task at hand. I wish to show a quick and easy way to edit remote files using Vim.

user@local~$ vim ftp://hostip/file.py

OK thats it. Told you it was quick. Save and quit (:wq) and your file is updated and published.

There is a huge learning curve to Vim but I think that with time, you will find yourself being more efficient.

Wednesday, March 11, 2009

March Madness on your Conky

March Madness is here and and what better way to keep track of the action than with a scoreboard tracker at the bottom of your screen. Check out the image below:

This is accomplished by combining a python script with the conky variable scroll. The python script will get the data, parse it and put it into a acceptable format for conky to handle the display. I've talked about conky earlier and using displaying the last instant message.

Copy the following code and save it as bottomscore.py


#!/usr/bin/python
import urllib
# Open html page
fweb = urllib.urlopen("http://scores.espn.go.com/ncb/bottomline/scores")

gamestr=''
score=''
# Manipulate str for unneccessary chars
raw=str(fweb.readline())
raw=raw.replace('%20',' ');
raw=raw.replace('^','');
raw=raw.replace('&','\n')

# Open data storage
f=open('bottom.dat', 'w')
f.write(raw)
f.close()
f=open('bottom.dat', 'r')

# Parse each line, get game, create str, append str
for line in f:
if line.find('_left')>1:
gamestr=line[line.find('=')+1:-1]
score= score + gamestr + ' | '

f.close()
print score


My conky script is as follows. Save this
#avoid flicker
double_buffer yes

#own window to run simultanious 2 or more conkys
own_window yes
own_window_transparent no
own_window_type normal
own_window_hints undecorate,sticky,skip_taskbar,skip_pager, above

#borders
draw_borders no
border_margin 0

#shades
draw_shades no

#position
gap_x 0
gap_y 0
alignment bottom_middle

#behaviour
update_interval 1

#colour
default_color 8f8f8f
#default_shade_color 000000
own_window_colour 262626

text_buffer_size 1400

#font
use_xft yes
xftfont bauhaus:pixelsize=10

#to prevent window from moving
use_spacer none
minimum_size 1400

TEXT
${color e0e0e0} ${scroll 2847 ${execpi 60 python ~/scripts/bottomscore.py}}

Remember to edit your .conkyrc to run the right path to bottomscore.py. You may need to edit certain parameters for your screen resolution but this should give you a good start. Any questions, post a comment.
Pro Tip:To run multiple conky screens:"conky -c .conkyrc2"

Monday, March 2, 2009

How to Burn Compressed Video Files to DVD in Ubuntu

With some help from Realtimeedit and MEncoder, I developed a script file to convert common compressed video files into an .iso file which can be burned onto a DVD for set top playback on your TV.

Before you run the script, you'll need to install the following packages:

MEncoder: sudo apt-get install mencoder
DVD Author: sudo apt-get install dvdauthor

Download the script file here.

When you run the script it will prompt you for the directory, name, and extension of the video file. It will then prompt you for the aspect ratio of video file and run MEncoder to decompress the file to an mpeg format. It will then run DVD Author to write to DVD format and create an .iso file.

Use any DVD burning software to burn the .iso image to a DVD.

Hope this works for you, any comments are always appreciated.

Friday, January 16, 2009

MATLAB: Set working path at startup

Many times when MATLAB is started there is a certain program that you want to work on. In order to work on this program, the current directory or path of that program must be changed or set.  This little script here will prompt the user for the module to work on and then add that directory to the path listing. When MATLAB is terminated, that path will not be saved.
% startup.m

% Set Production Directory
prod='~/MATLAB/Production/';

% Prompt user for module name
module=input('What module do you want to work on? ','s');

% If module is set, add to top of path. Otherwise don't add
if ~isempty(module)
path([prod,module],path);
end
Place the startup.m in your MATLAB work directory.

Thursday, December 18, 2008

Pretty Plots in MATLAB

Using MATLAB to crank through some calculations, but having trouble making the plots pretty? Here's an example that should make a nice looking plot that's ready to be inserted into a report.

figure
set(gca,'fontsize',14)
set(gcf, 'PaperSize', [8. 6.],'PaperPositionMode', 'auto');
plot(X,Y,'k^','markersize',10,'markerfacecolor','auto')
legend('mylegend','location','northeast');
xlabel('myxlabel','Interpreter','latex','fontsize',16);
ylabel('myylabel','Interpreter','latex','fontsize',16)
AXIS([xmin xmax ymin ymax])
print('-r600','-dpdf',['filename','.pdf'])

Alright, a quick rundown.

1. The 'figure' command is letting MATLAB know that we're making a picture with all the following attributes.
2. The 'set gca' command is setting the axes, which have the default handle 'gca', to have a font size of 14 here. This will control the size of the numbering on the axes, as well as the size of the font in the legend.
3. The 'set gcf' command is setting the paper size to 8" by 6", a size I find works well with the default figure output of MATLAB. This will prevent you from having to crop the plot later in a third-party photo editor.
4. The 'plot' command lists the X and Y arrays youd like to plot, 'k^' plots black upward facing triangles in a 'marker size' of 10pt, and automatically filled.
The 'legend' command puts in your legend, one entry per pair of vectors being plotted, in the northwest position.
5. The 'xlabel' and 'ylabel' commands are pretty straightforward, but the interpretter command displays the labels in the default LaTeX font instead of the MATLAB font. You can use the '$$' pairing to put in maths.
6. The 'axis' command sets the range for x and y, just comment this out if you like what MATLAB does.
7. The 'print' command will save your figure as .pdf with the filename you specify in the current directory (where your .m file is). Here, you can always specficy a path if you'd like to save figures in a different folder.

Still to come, using str2num and num2str to automatically number plots that are part of a for loop, or to name output graphs based on input data.

Wednesday, November 19, 2008

MATLAB: Don't ', transpose(it)

Doing a little homework for ME 7040, I discovered that there is more to transposing a matrix than just rows becoming columns and vice versa. I was doing a simple stress, strain, displacement analysis of a beam under static load. The code snippet in question is when the elemental stiffness matrix needed to be calculated by:
k = int(int(B'*D*B,r,-0.5,0.5),s,-0.5,0.5)
B is a 3xn matrix of shape functions and D a 3x3 relationship of Modulus of Elasticity and Poisson's ratio. There is obviously more to this code, including the calculations of stress and strain and the writing of an output file.

Running the code using the prime ('), the code took 143.106 seconds to run. I was initally confused by how long it took because the matrices were not that large. I then heard about the function transpose() and decided to use that. In code form:
k = int(int(transpose(B)*D*B,r,-0.5,0.5),s,-0.5,0.5)
This took only 19.735 seconds to run. So digging a little further, the operator ', also checks for complex conjugates of the matrix as well.

In conclusion, if you know that you are not dealing with complex numbers, you may want to use the transpose function and not its operator.

Tip: To time the running time of your code, put tic on the top line and toc on the last line.

Saturday, October 11, 2008

Conky: Display Last Pidgin Message

Recently, I removed the gnome-panels, added awn, and had a conky bar at the top. However, I missed having a system notification of when I would receive a message via Pidgin. So I browsed the pidgin wiki and create somewhat of a hack to display the last IM that received from Pidgin. This method is probably not the best way however I had some diffuculty.

The DBus method that listens for the received messages was chocking conky and not allowing the conky script to load correctly. So I had to create two files. getim.py would run at startup, listen for a new message and then write that message to a data file. lastim.py would be executed within conky and check the data file for the new message. I know its not real efficient and redundant but it just works. If you have any brilliant ideas please let me know.

Here is the getim.py file:
#!/usr/bin/python

# ----- GETIM.PY // LISTEN FOR AN RECEIVED MESSAGE ------------#
################################################################
# MOST OF THIS SCRIPT WAS TAKEN FROM THE PIDGIN DEVELOPER WIKI#
# PLEASE VISIT http://developer.pidgin.im/ FOR MORE INFORMATION#
################################################################

def conky_im(account, sender, message, conversation, flags):
reg = '<(.|\n)+?>' # REGEX FOR HTML TAGS
message = re.sub(reg,'',message) # REMOVE HTML TAGS
sender = sender.split("@")[0] # GET GCHAT NAME
message = message[0:24] # LIMIT TO 25 CHARS
file = ' ' # LOCATION OF DATA FILE
fim = open(file,"w")
IM = sender + " said: " + message
fim.write(IM)
fim.close()

import dbus, gobject, re
from dbus.mainloop.glib import DBusGMainLoop
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()

bus.add_signal_receiver(conky_im,
dbus_interface="im.pidgin.purple.PurpleInterface",
signal_name="ReceivedImMsg")

loop = gobject.MainLoop()
loop.run()



Copy and paste the following and save as lastim.py:
#!/usr/bin/python

# SHOW LAST IM
f=" " # REPLACE WITH YOUR DATA FILE. ie.CONKYIM.DAT
fim = open(f,'r')
im = fim.read()
print im
fim.close


Finally, add this to your .conkyrc script
${execi 1 python ~/scripts/lastim.py}

Any questions/comments let me know. Here is a screen shot of what my conky looks like:

Monday, May 12, 2008

Batch Convert FLV to MP3

Many times on youtube I find concert videos or acoustic shows that I want to keep for later. Using the Firefox plugin VideoDownloader, I can download these videos as flv files but these flv's are not as portable as mp3. So I searched for a way to convert flv to mp3 and found help on the Ubuntu forums.

After looking at the script and looking at my flv files, I noticed that it would be very inefficient to do each file individually. Therefore, I modified the script to convert a whole folder of flv's. I will show the whole script itself and how to run it, but first lets install some programs that we need in order to convert the flv's.

sudo apt-get install ecasound mpg123 lame ffmpeg

The script itself is the following:
#!/bin/bash
# FLV to MP3
#flv2mp3.sh

FLV_FILE=/home/ditto/Videos/
cd $FLV_FILE

for vid in *.flv
do
ffmpeg -i $vid -f mp3 -vn -acodec copy /tmp/temp.mp3
ecasound -i /tmp/temp.mp3 -etf:8 -o ${vid/.flv}.mp3
rm -f /tmp/temp.mp3
done

exit 0

I save my scripts in a ~/scripts and don't forget to make the script executable.
chmod u+x flv2mp3.sh

Run as follows:
user@home:/scripts~$ ./flv2mp3


Let's take a closer look at the code.
FLV_FILE=/home/ditto/Videos/
cd $FLV_FILE


FLV_FILE is the location of the flv video files that we want to be converted. In the next line, the directory is changed to the location of the videos.

Next, we will look through the files in that directory, only using the .flv files. Notice:
for vid in *.flv
Next we will convert the video to mono audio and create a temporary mp3 called temp.mp3
ffmpeg -i $vid -f mp3 -vn -acodec copy /tmp/temp.mp3
Since the audio by default is mono, we will then convert it to stereo, output it into the current directory, and save it as an mp3, while keeping the basename. The file is renamed by ${vid/.flv}.mp3
ecasound -i /tmp/temp.mp3 -etf:8 -o ${vid/.flv}.mp3
rm -f /tmp/temp.mp3
That is pretty much it. Any comments or ways to make it better, please let me know.

Monday, April 14, 2008

Download Archive of Tweets

Today I came across a script written in Python to download all of your Twitter updates. This has a lot of possibilities for me since it will be in xml format, which will allow for many transformations. Perhaps create a nice time-line, as the author references, or create tags for myself to see how often I do something. I am very excited to see where this will lead.

I expect to customize the script for my liking and compatibility. Stay tuned for updates.

Friday, April 4, 2008

Update Kopete with Twitter Status

I love how twitter can update my facebook status but it would be even better for it to update my away message for gchat and aim while on kopete. The most important finding for me was the dcop command for kde programs. The usage of the command is as follows:

dcop kopete KopeteIface setAway "away message" false


Once I figured that out, I surfed around the Twitter API for my favorite scripting language wrapper, python. So after install python-twitter, I created a script that will check my Twitter status every minute and update by away message for kopete.

#!/usr/local/bin/python
import twitter, os, time


while True:
api = twitter.Api()
user = ""
statuses = api.GetUserTimeline(user)
stat = [s.text for s in statuses]
stat = str(stat[0])
os.system("dcop kopete KopeteIface ...
... setAway \"" + stat + "\" false")
time.sleep(60)


So just have this script load at start up and your away message will change even when you aren't there. I know this isn't the best way to code it, but it works :P