VirtualBox set Guest interface as a bridged adapter

December 10th, 2012

A bridged adapter means that the Guest adapter is bridged to the Host adapter i.e. it can see the whole network (request address from DCHP server etc)

VBoxManage modifyvm my-guest-name --nat1 bridged
VBoxManage modifyvm my-guest-name --bridgeadapter1 eth3

nat1 is the first interface of the Guest machine.

.NET and matching element name with wildcard using XPath

December 7th, 2012

This is similar to matching a name space with a wildcard.

'This is the node we are searching in
Dim someXmlNode As XmlNode = FetchXmlNode() 
Dim xPathExpr As String = String.Empty
 
'find all nodes with names that starts with nisse_
xPathExpr = ".//*[starts-with(name(), 'nisse_')]"
 
'loop through all elements that matches our XPath
For Each elementWithNisse As XmlNode In someXmlNode.SelectNodes(xPathExpr)
 
    AndHereAMiracleHappens(elementWithNisse)
 
Next

.NET and matching namespace with wildcard using XPath

December 5th, 2012

.NET framework’s XslCompiledTransform only supports XPath and XSLT 1.0.

With XPath 1.0 ‘*’ is allowed to select all elements and nisse:* is allowed to select all elements in the namespace bound to the prefix ‘nisse’ but *:nisse to select ‘nisse’ elements in all
namespaces is not allowed in XPath 1.0, see http://www.w3.org/TR/xpath#node-tests.

And here is an example in vb.net where InnerText is read from the nameOfElementToFind in any name space

' This is the xmlnode the search is done with
Dim node As XmlNode = FetchSomeNode()
 
Dim innerTextFromNode As String = String.Empty
Dim xPathToSearchFor As String = String.Empty
 
'Will find all direct decendants nameOfElementToFind in any name space
xPathToSearchFor = "*[local-name() 'nameOfElementToFind']" 
 
'Will find all nameOfElementToFind in any name space and anywhere under this node
xPathToSearchFor = ".//*[local-name() 'nameOfElementToFind']" 
 
'Will find all nameOfElementToFind in any name space and anywhere in the document the node belongs to
xPathToSearchFor = "//*[local-name() 'nameOfElementToFind']"
 
If (node IsNot Nothing) Then
	innerTextFromNode = node.selectSingleNode(xPathToSearchIn).InnerText
End If

MS SQL Update WHERE value is NULL

December 3rd, 2012

This example replaces null with an empty string in SomeTable.SomeColum

UPDATE SomeTable SET SomeColumn = '' WHERE SomeColumn IS NULL

The important thing to note here is that the check to find the value that is NULL is based on “IS NULL” (it is not possible to use the equals sign to check for NULL)

MS SQL SELECT WHERE value is NULL

December 3rd, 2012

Here is how to do a select where a column have NULL as the stored value.

SELECT * FROM SomeTable WHERE SomeColumn IS NULL

Equals sign does not work for null, trying to use the equals operator generates the result Unknown (it is not true nor false)

IF i = NULL THEN
      SELECT 'Result is True'
ELSEIF NOT(i = NULL) THEN
      SELECT 'Result is False'
ELSE
      SELECT 'Result is Unknown';
 
--This will end with Result is Unknown

This is based on the fact that null was introduced to represent “missing information and inapplicable information” in the database model and based on that statement using equals null was not implemented.

Arduino ultrasonic sensor (HC-SR04 or HY-SRF05)

September 10th, 2012

Both these ultrasonic range modules are fairly cheap modules, expect the HY-SRF05 to be the more expensive of the these two.

At a quick glance there are only small differences between these two:

  HC-SR04 HY-SRF05
Working Voltage 5 VDC 5 VDC
Static current < 2mA <2 mA
Output signal: Electric frequency signal, high level 5V, low level 0V Electric frequency signal, high level 5V, low level 0V
Sensor angle < 15 degrees < 15 degrees
Detection distance (claimed) 2cm-450cm 2cm-450cm
precision ~3 mm ~2 mm
Input trigger signal 10us TTL impulse 10us TTL impulse
Echo signal output TTL PWL signal output TTL PWL signal
Pins
  1. VCC
  2. trig(T)
  3. echo(R)
  4. GND
  1. VCC
  2. trig(T)
  3. echo(R)
  4. OUT
  5. GND

Not sure what the out pin is about, I have seen claims that it goes high when it detects a obstacle.
From my personal observations the HY-SRF05 seems like a slightly more accurate sensor and seems to have a much better range [I even got it to measure beyond the 4.5 meters it claims] – but if I were to build for instance a robot that should not collide with a wall that would not matter.

In short a ultrasonic sensor like this works like:

  • Send a pulse signal to I/O TRIG which is at least 10us long, this will activate the module to start detecting
  • The ultrasonic module will automatically send eight 40khz square waves, and will automatically detect when there is a reflect signal;
  • When there is an reflect signal back, the ECHO I/O will output a high level, the duration of the high-level signal is the time from untral sonic launch to return. As a result, the Measured distance = (T(Time of High Level output ) * (340M / S)) / 2 The reason for the division by two is that since this is a echo it has traveled both to and from the object. Note the speed of sound is dependent of the temperature so keep that in mind if you need accuracy

And here comes a code sample that works with both of these

/*
Tested with HY-SRF05, HC-SR04
Assuming a room temp of 20 degrees centigrade
The circuit:
	* VVC connection of the sensor attached to +5V
	* GND connection of the sensor attached to ground
	* TRIG connection of the sensor attached to digital pin 12
        * ECHO connection of the sensor attached to digital pin 13
*/
 
const int TRIG_PIN = 12;
const int ECHO_PIN = 13;
 
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
 
  pinMode(TRIG_PIN,OUTPUT);
  pinMode(ECHO_PIN,INPUT);
}
 
void loop()
{
   long duration, distanceCm, distanceIn;
 
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  duration = pulseIn(ECHO_PIN,HIGH);
 
  // convert the time into a distance
  distanceCm = duration / 29.1 / 2 ;
  distanceIn = duration / 74 / 2;
 
  if (distanceCm <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distanceIn);
    Serial.print("in, ");
    Serial.print(distanceCm);
    Serial.print("cm");
    Serial.println();
  }
  delay(1000);
}

And something that I noticed is very important is the quality of the 5V I got from my USB port when the Arduino was hooked up. At first I got a very noisy signal that was only able to detect ranges of about 10 cm, but after I swapped the connection to not use a usb-hub the results were much better.

And to finish off here comes a bit more about how to calculate the distance based on the time for the sound:

c = 331.3 + 0.606 × Temperature_in_C

so for 20 degrees it would be

c = 331.3 + 0.606 × 20 = 343.42 m/s

And for a lot better explenation, check out wikipedia

Java: Getting the Document from a Node or Element

September 3rd, 2012

When we for instance wishes to add a new element we need to pass along the document. If we have a element or a node we can get the document that way. Simply call getOwnerDocument and we are good.

Element element = //code to get a element
Node node = //code to get a node
 
//document from Node
Document document = node.getOwnerDocument();
 
//document from a Element
Document document = element.getOwnerDocument();

Java: Adding a Element under an Element (or Converting a Element to a Node)

August 31st, 2012

When using Document a Element can only be appended with a Node, but what if we have a Element ?

Easy, Element extends Node so just pass the Element along and all is well

import org.w3c.dom.Document;
import org.w3c.dom.Element;
 
Document doc;
Element newElement;
Element oldElement; //code to find that
newElement = doc.createElement("tag");
oldElement.appendChild(newElement);

Java: Creating a enum and converting from a string to the Enum

August 29th, 2012

Here is a simple example of how create a Enum and how to convert from a String to the Enum (the common reason for doing this would be is we at some point have for OurEnum.toString() and now wishes to get back to the OurEnum)

First we need to create the Enum, and this needs to be in its own file

public enum OurEnum { ENUM_A, ENUM_B, ENUM_C }

When we then later on (for instace have saved the toString value in a xml file) wish to

String ourEnumAsAString = "ENUM_A"; //replace with code to read the value
OurEnum ourEnum = OurEnum.valueOf(ourEnumAsAString);

Android resize a bitmap

August 27th, 2012

Here is a snippet to scale down a bitmap – the original bitmap still needs to fit on memory though

InputStream bitmap = mContext.getAssets().open("image.file");
Bitmap scaledBitmap= Bitmap.createScaledBitmap(BitmapFactory.decodeStream(bitmap), 120, 120, false);
bitmap.