Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

How to Exploit UltraEdit-32 to Highlight Code Based on File Extensions

UltraEdit-32 (UE for short from now on) is a wonderful text editor. You can use it as a simple text editor or to write programs using your favorite languages. Besides other features, UE offers syntax highlighting for the most common programming languages out there. UE recognizes the type of file by looking at its extension. However, sometimes, you might want to use one syntax highlighting for an extension that is not mapped in UE. For example if you use ProC, which file extension is .pc, you may want UE to default to the C highlighting for ProC files. You can do that by editing the UE’s wordfile.txt file. UE uses this file to understand how to highlight words. To edit this file, from the UE menu go to: Advanced -> Configuration -> Editor Display -> Syntax Highlighting. From this window you can open wordfile.txt by clicking on the Open button in the Full path name word list section. In this file you’ll find all the languages that UE highlight. Each language start with /Ln, where n is a number. At the end of the row where /Ln is you can see “File Extensions = extensions”. Just append the extension you need to highlight for that language and save the file. Restart UE and open the file with the extension you just mapped. Enjoy the result! :-)

Here is an example for the Pro*C extension (.pc):

/L1”C/C++“ C_LANG Line Comment = // Block Comment On = / Block Comment Off = / Escape Char = String Chars = ”‘ File Extensions = C CPP CC CXX H HPP AWK

This line is extracted from the wordfile.txt file. To add the Pro*C extension I just added PC at the end of File Extensions, that is after AWK:

/L1”C/C++“ C_LANG Line Comment = // Block Comment On = / Block Comment Off = / Escape Char = String Chars = ”‘ File Extensions = C CPP CC CXX H HPP AWK PC

How to Display an Element to the Center of the Browser

Sometimes you might need to display an element, for example a div, to the center of the browser. Here is an example of how you can do it using JavaScript and CSS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function init() {
  // Reference to the element
  var loading = document.getElementById("loading");
  // The div's width, set within the CSS class
  var loadingWidth = loading.offsetWidth;
  // The div's width, set within the CSS class
  var loadingHeight = loading.offsetHeight;
  // The browser's body's width
  var documentWidth = document.body.clientWidth;
  // The browser's body's height
  var documentHeight = document.body.clientHeight;
  // Position the element absolutely
  loading.style.position = "absolute";
  // Center horizontally
  loading.style.left = (documentWidth - loadingWidth) / 2;
  // Center vertically
  loading.style.top = (documentHeight - loadingHeight) / 2;
}

This code supposes you have a div element within your page with id=“loading”, for example:

1
2
<div id="loading" class="loading">Loading...</div>
<!-- Other HTML code -->

The CSS class could be the following

1
2
3
4
5
6
7
8
9
10
11
12
.loading {
  border: 1px solid #90A6B8;
  background-color: #FFFF80;
  height: 100px;
  width: 300px;
  z-index: 1000;
  text-align: center;
  padding: 20px;
  color: #000000;
  font-size: 18px;
  font-weight: bold;
}

The result should be that the browser displays the div centered within the browser.

Of course you need to take care of the div hiding and showing according to your needs. For example, when an Ajax call starts/ends you might want to show/hide it, maybe with a “loading gif” within it.

How to Detect the Selected Checkboxes Using JavaScript

Here is an example of how you can retrieve the selected checkboxes using a JavaScript function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<html>
<head>
<script>
function getSelectedValues(elem) {
  var elemNumber = document.myForm.test.length;

  var selectedElems = [];
  for(j = 0; j < elemNumber; j++) {
    if(elem[j].checked) {
      selectedElems.push(elem[j].value);
    }
  }
  return selectedElems;
}
</script>
</head>

<body>
<form id="myForm" name="myForm">
<input type="checkbox" id="test" name="myCheckBox" value="test1">
Test 1


<input type="checkbox" id="test" name="myCheckBox" value="test2">
Test 2


<input type="button" value="Click Here"
  onclick="alert(getSelectedValues(document.myForm.myCheckBox));">
</form>
</body>

</html>

In the previous example when the user clicks on the button the selected checkboxes are displayed through an alert.

How to Add Scrollbars to a Block (e.g. A <div> Element)

If you need to customize a list box then the <select> HTML element might not be enough. In such a case you’d like to have something that simulates the <select> behaviour.

Here is the code to use to obtain a custom list box:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
  <head>
  </head>

  <body>
    <div style="width: 200px; height: 200px; overflow: auto;">
      <table width="100%" height="100%">
        <script>
          for (var i = 0; i < 30; i++) {
            if (i % 2 == 0) {
              document.write(
              "<tr style='background-color:#0066ff; color: #ffffff'>" +
              "<td>JavaScript</td></tr>");
            }
            else {
              document.write(
              "<tr style='background-color:#ff6600; color: #ffffff'>" +
              "<td>JavaScript</td></tr>");
            }
          }
        </script>
      </table>
    </div>
  </body>
</html>

The key CSS element is overflow. If you use overflow: auto then the scrollbars are displayed only if they are needed. If you want to display them in any case then you need to use overflow: scroll.

Sorting an Array of Objects With the sortBy Method of Prototype

Here is an example of how easy it is to sort an array of objects using the Enumerable.sortBy method of the Prototype framework:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var obj1 = {
  lastName : "Lacava",
  firstName : "Alessandro"
};

var obj2 = {
  lastName : "Brown",
  firstName : "John"
};

var obj3 = {
  lastName : "Simpson",
  firstName : "Bart"
};

var arr = [obj1, obj2, obj3];

//order by last name
var sorted = arr.sortBy(function(obj) {
    return obj.lastName.toLowerCase();
  }
);

var str = "";
sorted.each( function(obj, index) {
    str += index + 1 + " - " + obj.lastName + " " + obj.firstName;
  }
);

//display the elements ordered by last name
document.write(str);

Why You Shouldn’t Be Concerned About Optimization

When you were at the university or in any programming course, you–like me–were probably thought of the importance of optimization. In the real world though, you should strive for writing good code–possibly using bullet-proof Design Patterns–and defer optimization until later. Actually, you should optimize your code only if, after testing, you realize that optimization is strongly necessary. There are three aphorisms concerning optimization that you cannot but know:

  1. More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason, including blind stupidity.
    William A. Wulf

  2. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
    Donald E. Knuth

  3. We follow two rules in the matter of optimization: Rule 1 Don’t do it. Rule 2 (for experts only). Don’t do it yet, that is, not until you have a perfectly clear and unoptimized solution.
    M. A. Jackson

Notice that these great computer scientists wrote these aphorisms when computers were much slower than today’s!

How to Select Any Character Across Multiple Lines In Java

You can do that using the following pattern in the compile static method of the java.util.regex.Pattern class. The pattern is (.|n|r)*? which means: any character (the .) or (the |) n or r. Zero or more times (the *) of the whole stuff.

Example: The following method strips the multiline comments (those between /* and */) from a string passed in and returns the resulting string:

1
2
3
4
5
6
7
8
9
10
import java.util.regex;

// ... other code 

// Strip multiline comments
public void deleteMultilineComments(String subject) {
  Pattern pattern = Pattern.compile("(/\\*(.|n|r)*?\\*/)");
  Matcher matcher = pattern.matcher(subject);
  return matcher.replaceAll("");
}

Note: rn works for Windows systems. n works for Unix-like systems. r works for Mac systems.

How to Include a .js File (a JavaScript File) Within Another .js File

Actually, there is no function you can call to include a JavaScript file within another one. This is the bad news. The good news is that you can use a trick to accomplish this task. Suppose you have two JavaScript files, say file1.js and file2.js. You want to include file1.js within file2.js because you want to use file1’s functions. Here is the code you can use:

1
2
3
4
//this is file2.js
document.write("<script src='file1.js' type='text/javascript'></script>");

// here you can use functions defined in file1.js

As you can see it suffices “to write” in the browser the code you generally use to include a JavaScript file within an HTML file and you’re done!

Java Passes EVERYTHING by Value!

It’s a common misconception thinking (or worse teaching!) that, in Java, primitives are passed by value and objects by reference. Actually, everything in Java is passed by value as well as object references.

When a parameter is passed by value, an actual copy of it is really passed so that any change made will have only a local effect. For example:

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
  int a = 0;
  increment(a);
  System.out.println(a); //it prints 0 so increment didn't work as expected
}

public static int increment(int a) {
  ++a;
  System.out.println(a); //it prints 1
  return a;
}

As you can see the change made to the parameter passed to increment, that is a, affects only the local copy of it. This proves that Java passes primitives by value.

Well, this is no surprise to anyone since you already knew that.

I’ll prove now, that also object references are passed by value, that is only a copy of the reference is passed. Suppose you want to write a swap method to swap two integers. Since you know you can’t use primitives you might think to write the method using the wrapper class for int values, that is Integer. Let’s try that:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
  Integer a = new Integer(1);
  Integer b = new Integer(5);
  swap(a, b);
  System.out.println(b.intValue()); //it prints 5 so swap didn't work!
}

public static void swap(Integer a, Integer b) {
  Integer temp = a;
  a = b;
  b = temp;
  System.out.println(b.intValue()); //it prints 1!
}

This means that, even the object references are passed by value, as I stated at the beginning of this post!

What really happens is that, in case of references, a copy of the reference is passed and not the reference itself. This means that, if the class is not immutable, you can change it’s state but you CANNOT change the actual memory address the reference points to. Since Integer is an immutable class you cannot change its state. So if you want to swap two int values, you need to write your own class that wraps an int and provides a method to change the state of this instance variable. In this case you can pass the copy of the references to a swap method and call the method that lets you change the state of the object. This is left as an exercise though. :-)

What Happens if You Write Something Like a = a++ In Java?

I often happened to see discussions about this topic. Basically, here is the question. If you have such a code:

1
2
3
int a = 0;
a = a++;
System.out.println(a);

What does it print?

More than 50% of the programmers will answer 1, some of the remaining will say “I don’t know” and the others will say 0. Well “the others” are right!

Provided that such a code MUST NEVER BE WRITTEN, let’s try to understand, for academic purposes, why it prints 0.

The reason lies in the JLS (Java Language Specification). The JLS mandates that, in an assignment expression, the right side of the = must be evaluated first and then the value of the expression must be assigned to the left side. When the right side gets evaluated, a++ evaluates to 0 since it is a post-increment. This value is then saved into some temporary variable. At this point the post-increment takes place -> a = a + 1 and, finally, the value of the temporary variable is assigned to a, losing the increment previously done!

If we translate that code in pseudo-code we have:

1
2
3
4
a = 0
temp = a (the value of the a++ expression)
a = a + 1 (the effect of the post-increment)
a = temp;

That’s why you get 0! I hope this is clear enough.

An important thing to say is that, if you use a good IDE you’ll get a warning about that assignment. For example, using Eclipse (my version is 3.1.1 at the time or writing this post) I get: “The assignment to variable a has no effect”.

Final Note: In C and C++ that expression gives an “undefined behaviour”! That means that there’s no specification about it. Indeed, some compilers give 0 and others give 1 as the final value of a.