Saturday, April 2, 2016

How to set custom screen resolution in X-Windows

This post will explain step-by-step how to configure custom screen resolutions in X-Windows. This may be useful in situaction when, for example the system is unable to automatically detect all modes supported by monitor, or when we are working on a virtual machine (VMWare, Parallels, etc.) and want to adjust the screen size to the host. To list all available modes we have to open the Terminal (Ctrl+Alt+T) and type the following command:
xrandr
The output will look similar to this:

We can then select desired mode using command:
xrandr -s [selected mode]
If the mode that we are interested in is not listed, it will be necessary to add it manually. The first step is to create a proper modeline using CVT:
cvt 960 1080 60
CVT is a built-in tool which calculates and prints out valid VESA Coordinated Video Timing modeline for given screen resolution and refresh rate.

Once that step is done, it's time to add the mode to the set of valid modes for our output:
xrandr --newmode "960x1080_60.00"   86.00  960 1024 1120 1280  1080 1083 1093 1120 -hsync +vsync
xrandr --addmode Virtual1 "960x1080_60.00"
Note that the params used for the --newmode command are copied exactly from the output of the cvt command. Also, the --addmode operation requires the name of the device the mode will be associated with. In my case it was "Virtual1".



To confirm that the mode has been successfully added, run xrandr again:



That's it. Now we can select the mode using:
xrandr -s "960x1080_60.00"
To delete it from the list use the following commands:
xrandr --delmode Virtual1 "960x1080_60.00
xrandr --rmmode "960x1080_60.00


The above steps explain how to dynamically create and set custom screen resolution. However this will only last until the system is rebooted. To make the changes persistent we will have to use X-Windows configuration files. Here's how to do it:
cd /usr/share/X11/xorg.conf.d
sudo touch 10-monitor.conf
sudo notepadqq 10-monitor.conf
I'm using notepadqq to edit text files, but any other will do as well. Here's the content of the file:
Section "Monitor"
 Identifier "Virtual Monitor"
 Modeline "960x1080_60.00" 86.00 960 1024 1120 1280 1080 1083 1093 1120 -hsync +vsync
EndSection

Section "Screen"
 Identifier "Default Screen"
 Device "Virtual1"
 Monitor "Virtual Monitor"
 DefaultDepth 24
 SubSection "Display"
  Modes "960x1080_60.00"
 EndSubSection
EndSection
/usr/share/X11/xorg.conf.d stores configuration files for the X Server. All files in the directory have specific format and contain various parameters used to configure the system.

Friday, April 17, 2015

Overloading, overriding and method resolution

Today, I'm going to shed some light on the mechanics of method resolution for overloaded and overridden methods in Java. Will start with a small piece of code:

package net.progsign.prep;

class Base {
 public void method(int... params) {     //Method #1
  System.out.println("[B] int...");
 }
  
 public void method(int param1, long param2) {  //Method #2
  System.out.println("[B] int, long");
 }
 
 public void method(int param1, Integer param2) { //Method #3
  System.out.println("[B] int, Integer");
 }
 
 public void method(int param1, Number param2) {  //Method #4
  System.out.println("[B] int, Number");
 }
 
 public void method(int param1, Object param2) {  //Method #5
  System.out.println("[B] int, Object");
 }
 
 public void method(int param1, int... param2) {  //Method #6
  System.out.println("[B] int, int...");
 }
 
 public void method(int param1, long... param2) { //Method #7
  System.out.println("[B] int, long...");
 }
 
 public void method(int param1, Integer... param2) { //Method #8
  System.out.println("[B] int, Integer...");
 }
}

public class OverloadingTest {
 public static final void main(String[] args) {
  Base base0 = new Base();
  base0.method(1, 1);
 }
}
The code, when compiled and executed, will result in the following message printed to the console:
[B] int, long  //Method #2

OK, so what exactly happend, and how did the virtual machine figure out which method should be executed? With reference to Java Language Specification for Java SE 7 Edition, there are three phases of resolving the proper method signature:

Phase #1: performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation.
During this phase the compiler will try to find an exact match (overloaded method which parameters types match the invocation). If no such method is found, the compiler then will try to upcast (widen) the argument types until the closest match is found. Below diagram shows the direction the upcasting will process for primitive types:


For non-primitive types (instances) it will follow up the inheritance tree. If no applicable method is found during this phase then processing continues to the next phase.

Phase #2: performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation.
In this phase the compiler will try to utilize the auto-boxing mechanism introduced in Java 5. If boxing (wrapping primitive type with its istance representation) occurs, then, same as before the whole class hierarchy is taken into account, however the most specific type takes precedence over the more generic types. Example:

package net.progsign.prep;

class Base {
 public void method(int param1, Integer param2) { //Method #3
  System.out.println("[B] int, Integer");
 }
 
 public void method(int param1, Number param2) {  //Method #4
  System.out.println("[B] int, Number");
 }
 
 public void method(int param1, Object param2) {  //Method #5
  System.out.println("[B] int, Object");
 }
}

public class OverloadingTest {
 public static final void main(String[] args) {
  Base base0 = new Base();
  base0.method(1, 1);  //Line #1
  base0.method(1, null);  //Line #2
 }
}
The result will be as follows:
[B] int, Integer  //Method #3
[B] int, Integer  //Method #3

In line marked as Line #1 the second argument was automatically boxed to an Integer. In Line #2 the second argument is null, but since Integer is more specific type than Number and Object, the compiler will favour Method #3 over the other two. If the compiler is still not satisfied, it continues to the third phase.

Phase #3: allows overloading to be combined with variable arity methods, boxing, and unboxing.
As you can see, varargs (short for "variable arguments", also introduced in Java 5) have the lowest priority. This is to ensure backward compatibility with legacy code that doesn't support this feature. Knowing the above rules, there should be no problem with predicting the output of the following code:

package net.progsign.prep;

class Base {
 public void method(int... params) {   //Method #1
  System.out.println("[B] int...");
 }
  
 public void method(int param1, int param2) {  //Method #2
  System.out.println("[B] int, int");
 }
 
 public void method(int param1, Integer param2) { //Method #3
  System.out.println("[B] int, Integer");
 }
}

public class OverloadingTest {
 public static final void main(String[] args) {
  Base base0 = new Base();
  base0.method(1, 1);
 }
}

Of course Method #2 will be invoked first, and in case of its absence the compiler will prefer Method #3 rather than Method #1. Simple enough. OK, what about this code:

package net.progsign.prep;

class Base {
 public void method(short... params) {   //Method #1
  System.out.println("[B] short...");
 }
 
 public void method(int param1, int param2) {  //Method #2
  System.out.println("[B] int, int");
 }
 
 public void method(short param1, double param2) { //Method #3
  System.out.println("[B] short, double");
 }
}

public class OverloadingTest {
 public static final void main(String[] args) {
  Base base0 = new Base();
  base0.method((short)2, (short)5);
 }
}

This is where things get a bit tricky. From earlier we know that Method #1 will be the last to take into consideration. But what about the other two methods? There's section 15.12.2.5. Choosing the Most Specific Method in the JLS that explains the rules of selecting the most specific method signature. Here's what is going to happen in the above code. The compiler will compare the first parameter and will find a perfect match in Method #3. Spot on! But when it gets to the second parameter it will actually lean forward Method #2 (see the upcasting chart). This ambiguity will lead to a compiler error.


Having more fun!

Hope everything makes a bit more sense now. Let's add some petrol to the fire:
package net.progsign.prep;

class Base {
 public void method(int... params) {     //Method #1
  System.out.println("[B] int...");
 }
 
 public void method(long param1, double param2) { //Method #2
  System.out.println("[B] long, double");
 }
}

class Subclass extends Base {
 public void method(int... params) {
  System.out.println("[D] int...");    //Method #S1
 }
 
 public void method(int param1, int param2) {  //Method #S2
  System.out.println("[D] int, int");
 }
 
 public void method(int param1, int... param2) {  //Method #S3
  System.out.println("[D] int, int...");
 }
}

public class OverloadingTest {
 public static final void main(String[] args) {
  Base base0 = new Base();
  Base base1 = new Subclass();
  Subclass subclass0 = new Subclass();
  Subclass subclass1 = (Subclass)base1;
  
  base0.method(1, 1);   //Line #1
  base1.method(1, 1);   //Line #2
  subclass0.method(1, 1);  //Line #3
  subclass1.method(1, 1);  //Line #4
 }
}
And the output will be...
[B] long, double
[B] long, double
[D] int, int
[D] int, int

Right as expected, isn't it? So what have we got here. Class Base declaring two overloaded methods. Also another class, Subclass, with three more overloaded (overriden?) methods.
In the main function we first instantiate Base class, and refer to it by its base type. Then we create an instance of a Subclass class, but we're using its super type as a reference. Also another class is being created and assigned to a proper reference type. And finally another reference of type Subclass is created to point to one of the previously created objects.
I believe Line #1 is clear enough. But what actually happened in Line #2? In Line #1 the compiler resolved Method #2 to be the best match of the Base class. Since we're using the same reference type in Line #2, the same Method #2 was invoked again. Please note that the only overriden method in the Subclass is Method #1 (overriden by Method #S1, so there's no polymorphism taking place in this case. Also, because Base doesn't know anything about Method #S2, which otherwise would be the best candidate, that method is not called. There's no black magic in Line #3 and Line #4.

One last thing to remember: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.

Monday, February 18, 2013

Brainfuck plugin for Eclipse IDE

Features:
  • Brainfuck interpreter
    • launch configurations
    • launch configuration shortcut
  • Brainfuck editor
    • associates with *.b & *.bf files
    • syntax highlighting
    • code hover tool tips
    • loop select on double click
Repository: hg clone https://code.google.com/p/brainfuck-eclipse-plugin/

Enjoy!

Tuesday, November 13, 2012

Local functions prototyping

A trivial piece of C++ source code:
#include <iostream>

class Foo {
    public:
        Foo(int=5);
};

Foo::Foo(int) {
    std::cout << "[Foo]";
}

int main() {
    Foo Foo0();
    Foo Foo1(1);
    return 0; //SUCCESS?
}
And a trivial question: how many times will the Foo constructor execute?

Explanation:
in the above code, line:
    Foo Foo0();

is not a declaration of a variable named Foo0 of class Foo initialized with default constructor. Instead, it is, what can be called local function prototyping. More precisely, it is a declaration of a new function, named Foo0, which returns result of type Foo.

It seems to be legacy code after nested functions, supported by GCC C Compiler. See the example:
#include <stdio.h>

int main() {
 auto int m_nested();
 int m_nested() {
  return 666;
 }

 printf("%d", m_nested());
 return 0;
}
Function m_nested() is nested within another function (main()), and its scope is limited to that surrounding function.

Getting back to the original code, any attempt to access Foo0 will result in error:
int main() {
    Foo Foo0();
    Foo Foo() { //error: a function-definition is not allowed here before '{' token
        //...
    };
    Foo0(); // error: undefined reference to 'Foo0()'
    Foo0 = *new Foo(); // error: cannot convert 'Foo' to 'Foo()' in assignment
}
The only thing, that would make sense and would actually compile is defining this function somewhere else:
//...
int main() {
    // no access to Foo0() here
    Foo Foo0();
    Foo f = Foo0();
    //.. do some stuff with 'f'
    delete &f;
    return 0;
}

Foo Foo0() {
    std::cout << "Foo0()";
    return *new Foo();
}
Such code will narrow access to Foo0() to the place where it was declared for the first time, and will end as soon as the program leaves the execution block.

Monday, February 6, 2012

java.net.URL, content handlers and HTML/XML parsing

Below is an example of using java.net.ContentHandler class while retrieving resources from URL.

The objective is to get traffic stats from a network device. The device may present its status in two ways: as an XML data or human readable HTML page. In this example will use both the sources to get the information.

My network device collects data from different interfaces. The interface may be described as follows:

public class InterfaceStatus {
    private String name;
    private long txPackets;
    private long txBytes;
    private long rxPackets;
    private long rxBytes;
    
    // getters and setters...
}

To override default behaviour of the URL.getContent() method, a custom content handler factory must be created, i.e. class that implements ContentHandlerFactory interface. There's only one method to implement in this interface: public ContentHandler createContentHandler(String mimetype).

import java.io.*;
import java.net.*;

import javax.swing.text.html.parser.ParserDelegator;

import org.xml.sax.*;
import org.xml.sax.helpers.XMLReaderFactory;

public class UrlContentHandlerFactory implements ContentHandlerFactory {

    @Override
    public ContentHandler createContentHandler(String mimetype) {
        if("application/xml".equals(mimetype)) {
            return new XmlContentHandler();
        } else
        if("text/html".equals(mimetype)) {
            return new HtmlContentHandler();
        }
        // default content handler will be selected by JVM
        return null;
    }
    // ... inner *ContentHandler classes below...
}

The mimetype value is taken from the [JAVA_HOME]\lib\content-types.properties file. Now, it's time for the concrete implementation of the ContentHandler abstract class.

HtmlContentHandler
public class UrlContentHandlerFactory implements ContentHandlerFactory {
    // ...
    protected class HtmlContentHandler extends ContentHandler {

        @Override
        public Object getContent(URLConnection urlc) throws IOException {
            HttpURLConnection conn = (HttpURLConnection) urlc;
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // using HTML Editor Kit API
                HtmlTrafficExtractor hte = new HtmlTrafficExtractor();
                new ParserDelegator().parse(new InputStreamReader(conn.getInputStream()), hte, true);

                return hte.getExtractedList();
            }
            return null;
        }
    } // HtmlContentHandler
}

To parse HTML pages, I've used HTMLEditorKit and ParserDelegator from javax.swing.text.html package. Why not to use XML parser? Here's the answer:

<html>
    <!-- head -->
    <body bgcolor=#00cccc>                <!-- no quotation marks around attribute value -->
        <img src="logo.gif" alt="Logo">   <!-- no closing "img" tag -->
    </body>
</html>

Although HTML pages consist of tags, tag attributes, text, etc., just as XML documents do, they don't have to conform to XML specification as illustrated in the above snippet. This would cause unnecessary exceptions being thrown.

XmlContentHandler
public class UrlContentHandlerFactory implements ContentHandlerFactory {
    // ...
    protected class XmlContentHandler extends ContentHandler {

        @Override
        public Object getContent(URLConnection urlc) throws IOException {
            HttpURLConnection conn = (HttpURLConnection) urlc;
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // this is where the SAX2 API kicks in
                try {
                    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
                    XmlTrafficExtractor te = new XmlTrafficExtractor();
                    xmlReader.setContentHandler(te);
                    xmlReader.setErrorHandler(te);
                    xmlReader.parse(new InputSource(conn.getInputStream()));

                    return te.getExtractedList();
                } catch(SAXException saxe) {
                    System.err.println("Parsing failed due to the following error: " + saxe.getMessage());
                }
            } // if
            return null;
        }
    } // XmlContentHandler
}

The content handler for XML documents is very similar. In contrast to the previous code, it uses SAX2 parser, which is a part of Java environment.

Both APIs use callback objects to parse documents. In HTML Editor Kit, the object must extend static HTMLEditorKit.ParserCallback class, and in SAX2 it is org.xml.sax.helpers.DefaultHandler.

HtmlTrafficExtractor
import javax.swing.text.html.HTMLEditorKit;

public class HtmlTrafficExtractor extends HTMLEditorKit.ParserCallback {
    private List<InterfaceStatus> statusList;

    // overriding essential callback methods here

    public List<InterfaceStatus> getExtractedList() {
        return statusList;
    }
}

XmlTrafficExtractor
import org.xml.sax.helpers.DefaultHandler;

public class XmlTrafficExtractor extends DefaultHandler {
    private List<InterfaceStatus> statusList;
    
    // overriding essential handler's methods here
    
    public List<InterfaceStatus> getExtractedList() {
        return statusList;
    }
}

Both the callback classes provide a method to return a list of available/found interfaces.

And here's how to use the code:

public class TransferStatus {
    private static final String URL_ADDRESS_XML = "http://router/stats/traffic.xml";
    private static final String URL_ADDRESS_HTM = "http://router/stats/netstat.html";

    public static final void main(String[] args) {
        URLConnection.setContentHandlerFactory(new UrlContentHandlerFactory());

        try {
//          Object content = new URL(URL_ADDRESS_XML).getContent();
            Object content = new URL(URL_ADDRESS_HTM).getContent();
            if(content != null && content instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<InterfaceStatus> statusList = (List<InterfaceStatus>) content;
                for(InterfaceStatus status : statusList) {
                    // doing things with the data
                }
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

First, URLConnection.setContentHandlerFactory() static method is called to set the content handler factory. From now on, every call to URL.getContent() will ask the factory for a proper content handler (if none is found, i.e. the factory returns null, JVM will try to load default handler).
The next step is to check if the content returned is of correct type and further processing of the data.
Now, the only thing that changes in the above code is the resource URL address passed as an argument to the URL() constructor.

Friday, December 16, 2011

Initialization block as a constructor for anonymous class

Although not broadly used, [static] initialization blocks are quite interesting features in Java. They may be used to initialize static and instance fields with own default values, before a constructor kicks in. In byte-code, such blocks are represented by two special methods: void <clinit>() for static initialization block and void <init>() for instance initialization block. There may be multiple declarations of initialization blocks in one class. In such case the code from each block is combined into one of the above methods. All instructions are invoked in the same order as they were declared in source code. Example:

package net.progsign.java6;

public class InitializationBlockTest {
 
 private static char charValue;
 private boolean boolValue;
 private int intValue;
 private String stringValue;
 
 static {
  charValue = '$';
  System.out.println("[clinit] " + charValue);
 }
 
 {
  System.out.println("[init-0] " + boolValue);
  System.out.println("[init-0] " + intValue);
  System.out.println("[init-0] " + stringValue);
  System.out.println();
 }
 
 {
  boolValue = true;
  intValue = 1024;
  stringValue = "default";
 }

 public InitializationBlockTest() {
  System.out.println("[constr] " + boolValue);
  System.out.println("[constr] " + intValue);
  System.out.println("[constr] " + stringValue);
 }
 
 public static final void main(String[] args) {
  new InitializationBlockTest();
 }
}

The output of the above code will be:
[clinit] $
[init-0] false
[init-0] 0
[init-0] null

[constr] true
[constr] 1024
[constr] default

Good code design expects from us to initialize class fields in a constructor. Also, because of the characteristics of initialization blocks, it may cause some confusion when trying to understand the order in which the object is created.
However, there is a case where initialization block may be successfuly used. Examine the following code:

package net.progsign.java6;

interface IFace {
 int method();
}

public class AnonymousConstructor {
 public static void main(String[] args) {
  // anonymous class implementing IFace interface
  IFace foo = new IFace() {
   private int value;
   
   {
    value = 1024;
    init();
   }
   
   public int method() {
    return value;
   }
   
   private void init() {
    System.out.println("<init> called init()");
   }
  };
  System.out.println("[main] foo.method() = " + foo.method());
 }
}

In the above code, I declared an interface IFace and, in the main() method, I created anonymous class that implements this interface. My anonymous class has one private attribute value of type int. Because anonymous classes have no name, thus it's not possible to define own constructor (default non-argument constructor will still be created for the class by the compiler). Without initialization blocks, we would be unable to init the class field with our own values.

When compiled and run, the code will produce the following output:

<init> called init()
[main] foo.method() = 1024

Things to know about [static] initialization blocks:
  • there may be multiple initialization blocks in one class (they run in the order they occur in code)
  • they are invoked before any constructor
  • you can't call constructors (neither super() nor this()) from inside initialization block
  • same as constructors, initialization blocks may throw runtime exceptions (in such case the object will not be created)
  • you can assign default value to fields declared as final, but only if they haven't been initialized at declaration time



PS: noticed quite an interesting behaviour of initialization blocks. See the following code:

package net.progsign.java6;

public class InitializationTest {

 static {
  sfield = 1;
  //System.out.println("<clinit> " + sfield);
  //System.out.println("<clinit> sfield=" + InitializationTest.sfield);
 }
 
 {
  ifield = 2;
  //System.out.println("<init> " + ifield);
  //System.out.println("<init>   ifield=" + this.ifield);
 }
 
 static int sfield = 10;
 int ifield = 20;
 
 public static void main(String[] args) {
  InitializationTest it = new InitializationTest();
  System.out.println("[main]   sfield=" + it.sfield);
  System.out.println("[main]   ifield=" + it.ifield);
 }
}

Will the code compile? What will be the output? What will happen if you uncomment the "System.out.println(...)" lines?

Tuesday, October 11, 2011

OT: Chatting with Windows shell (VBScript)

Just a short memo on how to use WMI (Windows Management Instrumentation) and VBScript to simplify some administration tasks.

Rebooting remote machine (have to have privileges to WMI on the remote host):
Sub Reboot(host)
On Error Resume Next
    Set wmi = GetObject("winmgmts:{(Shutdown)}\\" & host & "\root\cimv2")
    If Err.Number <> 0 Then
        Exit Sub
    End If
    Set osList = wmi.ExecQuery("SELECT * FROM Win32_OperatingSystem")
 
    For Each os In osList
        os.Reboot()
    Next
End Sub

Checking host availability:
Sub Ping(host)
    Set pingStatus = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("SELECT * FROM Win32_PingStatus WHERE address = '" & host & "'")
    For Each pingReplay In pingStatus
       If pingReplay.StatusCode = 0 Then
            WScript.Echo "Response: OK [Time (ms)=" & pingReplay.ResponseTime & "/TTL (ms)=" & pingReplay.ResponseTimeToLive & "]"
       Else
            WScript.Echo "No response from host '" & host & "'"
       End If
    Next
End Sub

Mounting network resources:
Sub Mount(folder)
On Error Resume Next
    Set NetworkObj = CreateObject("WScript.Network")
    Set ShellObj   = CreateObject("WScript.Shell")
    NetworkObj.MapNetworkDrive "X:", folder, true', "user", "pass"
    If Err.Number = 0 Then
        ShellObj.LogEvent 0, "Network resource '" & folder & "' mounted"
    Else
        WScript.Echo "Failed (Status code: " & Err.Number & ")"
    End If
End Sub