Go to the navigation

elblogg

Posts Tagged ‘code’

Round, Floor and Ceiling in Expression Language

Java Conference 2006 by Matteo Penzo ( matteopenzo on flickr)

Expression Language makes working with Java Server Pages a slightly less pain in the behind. But, its functionality is very limited, there is for instance no way to round off a number, neither as floor, ceiling or to the closest integer

Floor(foo) -> ${foo - ( foo % 1 ) }
Ceiling(foo) -> ${foo + ( 1 - (foo%1)) % 1}
Round(foo) -> ${foo +0.5 - ((foo+0.5) % 1) }

This still gives you a float, so to get an integer, you must either use the <fmt:formatNumber>-tag

<fmt:formatNumber value="${foo - ( foo % 1 ) }" var="fooAsInt" maxFractionDigits="0"/>

(really, this returns a string, representing the number without the decimals. But as EL automatically casts between strings, floats and integers, this is mostly OK.)

or you can hack it using fn:replace():

${fn:replace(foo - ( foo % 1 ),'.0','') }

(Yes, you may use singlequotes for strings in EL, even though this is supposed to be Java….)

Blogging code

As a programmer and linux geek I often need, or at least want to write about code, scripts and commands on my blog, but as many of you know, displaying raw code in HTML is setting yourself up for failure. The simplest part of the problem is the fact that line breaks and whitespace might be significant, this is simply solved by putting the code inside a <pre> block. The more tricky part is that code often is full of characters like &, > and <. Characters that have a specific meaning in HTML and can’t be echoed directly. & needs to be typed as an HTML entity (&amp;), just as > (&gt;) and < (&lt;). Talking about HTML and XML code on your blog can be a really tedious task (as the above).

I have usually solved this by writing the code in a file first, and then running the file through this sed command

cat file.html|sed -e 's/&/&amp;/' -e 's/</&lt;/' -e 's/>/&gt;/'

But as I work on a Macintosh these days, I’ve been using TextMate a bit.. Not as much as i use OpenKomodo though. TextMate has some nice blogging capabilities. You can use it to post directly onto your blog, and it has shortcuts for converting sections of your post into HTML entities. Just select the text, and hit ⌘+&, 1

Edit: it seems like there is some compatibility problems with WordPress 2.7 and TextMate. The post was published two hours off, and as a private post.

Unreadable code

If you’re really trying, you will always be able to write completely unreadable code in any programming language. All the language designers attemts to force you to write readable code, and even making it so the easiest way ahead, even for quick hacks is to write it as readable and reusable code will fail if you’re really trying to write unreadable code.

This guy is obviously concerned about “job security”. (not the blog author, but the code author)

?View Code PYTHON
#!/usr/bin/env python
import os,sys
C=os.chdir
S=os.system
M=os.mkdir
J=os.path.join
A=os.path.abspath
D=os.path.dirname
E=os.path.exists
W=sys.stdout.write
V=sys.argv
X=sys.exit
ERR=lambda m:W(m+"\n")
PRNT=lambda m:W(m+"\n")
assert len(V)==2,"you must provide a sandbox name"
SB=V[1]
H=A(D(__file__))
SBD=J(D(H),SB)
C(SBD)
PST=J(SBD,'bin/paster')
VAR=J(SBD,'var')
ETC=J(SBD,'etc')
S("mkdir -p "+VAR)
PRNT("restarting "+SB)
CMD=";".join(['source %s'%J(SBD,'bin/activate'),PST+" serve --daemon --pid-file=%s/sandbox.pid --log-file=%s/sandbox.log %s/sandbox.ini start"%(VAR,VAR,ETC)])
PRNT(CMD)
S(CMD)
PRNT("All done!")
X(0)

Aaannd… Heres my understanding of the code:

?View Code PYTHON
#!/usr/bin/env python
import os,sys
 
#bail out if there's no sandbox specified
assert len(sys.argv)==2,"you must provide a sandbox name"
sandbox=sys.argv[1]
 
#get the dir of this script
home=os.path.abspath(os.path.dirname(__file__))
 
#sandboxdir is this dir/sandboxname
sandboxdir=os.path.join(os.path.dirname(home),sandox)
 
#go into the root of the sandbox
os.chdir(sandboxdir)
PST=os.path.join(sandboxdir,'bin','paster')
VAR=os.path.join(sandboxdir,'var')
ETC=os.path.join(sandboxdir,'etc')
 
#make var directory if it doesnt exists
if not os.path.exists(VAR):
    os.mkdir(VAR)
 
print "restarting "+sandbox
 
# Build the system commands required to restart the sandbox
cmds=[]
cmds.append('source %s' % os.path.join(sandboxdir,'bin','activate'))
cmds.append(PST+" serve --daemon --pid-file=%s/sandbox.pid"
            "--log-file=%s/sandbox.log %s/sandbox.ini start" % (VAR,VAR,ETC))
CMD=";".join(cmds)
PRNT(CMD)
 
#run the cmds
if os.system(CMD) == 0:
    print "All done!"
    sys.exit(0)
else:
    print "Ooops. failed."
    sys.exit(1)

Should have guessed it

I have sort of a love/hate relationship with Python, the programming language. Coming from PHP and Java which both have excellent documentation, while lots can be said about the solutions. With Python 2.6 the documentation really has improved, but its still not really there, while the solutions are so elegant that the only reason you don’t guess how to do stuff is that it feels too simple.

Today I had one of these realizations, while reading Wayne’s snippet of the day.

Python has a really nice list-generation scheme, so you can generate lists of the content you want from another list of object with only one line of code.

Example:

?View Code PYTHON
&gt;&gt;&gt; from math import floor
&gt;&gt;&gt; a = [1.5, 1.9, 2.5, 3.1, 5.7]
&gt;&gt;&gt; b = [floor(i) for i in a]
&gt;&gt;&gt; print b
[1.0, 1.0, 2.0, 3.0, 5.0]

Here I generated a list of whole numbers from a list of non-whole numbers.

Now We’ll take this further.
Lets say we want to filter the list, so we’ll only get the numbers that satisfy 1<=x<2.

We could do this using filter() and lambda functions. Which is totally OK. It'll make Python newbies totally confused (which it did with me until recently, when I realized what lambda functions really are (I'll get back to this)), but it'll work nicely.

But wouldn't it be nice if we could use the same list generation scheme for this as well?
Guess what. You can!

?View Code PYTHON
&gt;&gt;&gt; a = [1.5, 1.9, 2.5, 3.1, 5.7]
&gt;&gt;&gt; b = [i for i in a if 1<=i and i<2]
&gt;&gt;&gt; print b
[1.5, 1.9]

Doing the same using filter and a lambda function will look like this

?View Code PYTHON
&gt;&gt;&gt; a = [1.5, 1.9, 2.5, 3.1, 5.7]
&gt;&gt;&gt; b = filter(lambda x: 1<=x and x<2, a)
&gt;&gt;&gt; print b
[1.5, 1.9]

and without using a lambda function:

?View Code PYTHON
&gt;&gt;&gt; def myfilter(x):
&gt;&gt;&gt;     return x: 1<=x and x<2
&gt;&gt;&gt; a = [1.5, 1.9, 2.5, 3.1, 5.7]
&gt;&gt;&gt; b = filter(myfilter, a)
&gt;&gt;&gt; print b
[1.5, 1.9]

All of these will work equally fine, and none of them is very hard to understand, as long as you keep in mind that lambda functions just are like anonymous functions/classes.

But there is something very facinating with the elegance and simplicity in the syntax of the list generator snippet.

Bloggurat Twingly BlogRank Blogglisten