Referring Methods that Throw Exceptions in Java
Unhandled Exception, which doesn't go away by wrapping the call in a try/catch or adding a throws clause to the method signature. See the following code,import java.util.function.Function;
public class PassingMethodsThatThrowExceptions {
public static int addOne(String value) throws NotANumberException{
int v = 0;
try{
v = Integer.parseInt(value);
} catch (NumberFormatException e){
throw new NotANumberException();
}
return v+1;
}
public static void increment(Function<String,Integer> incrementer, String value){
System.out.println(incrementer.apply(value));
}
public static void main(String[] args) {
increment(PassingMethodsThatThrowExceptions::addOne, "10");
}
}
- an
addOnefunction that takes in aStringvalue representing a number then adds1to it and returns the result as anint. - an
incrementfunction that simply takes a function, which can perform the increment and a value then apply the function to the value. - the
mainmethod that callsincrementwithaddOnefunction and value"10"
addOne function is declared to throw possible exception of type NotANumberException (the type of exception is NOT important here). Error: java: incompatible thrown types exceptions.NotANumberException in method reference
Unhandled Exception: NotANumberException for the increment method call in mainand adding try/catch will not work.increment function expects a function that takes a String and returns an int, but you forgot to mention that this method may also throw an exception of type NotANumberException.incrementer parameter in increment function.throws NotANumberException to thejava.util.function.Function interface that's used to define the type of incrementer parameter here.public class PassingMethodsThatThrowExceptions {
public interface IncrementerSignature{
public int apply(String value) throws NotANumberException;
}
public static int addOne(String value) throws NotANumberException{
int v = 0;
try{
v = Integer.parseInt(value);
} catch (NumberFormatException e){
throw new NotANumberException();
}
return v+1;
}
public static void increment(IncrementerSignature incrementer, String value) throws NotANumberException {
System.out.println(incrementer.apply(value));
}
public static void main(String[] args) {
try {
increment(PassingMethodsThatThrowExceptions::addOne, "10");
} catch (NotANumberException e) {
e.printStackTrace();
}
}
}
NOT something to do with referring methods or Java 8 in general. You may face a similar situation even in a case where you implement a method of an interface and in the implementation you add the throws SomeException to the signature. Here's a stackoverflow post you'd like to see on this.Blogging with Markdown in Blogger
tl;dr - Use Dillinger and paste the formatted content directly to blogger- Use makrdown aware static blog generator such as Jekyll or something based on it like Octopress
- Use a blogging solution based on markdown such as svbtle
- Use a tool that'll either enable markdown support in blogger (see this post) or can post to blogger (like StackEdit)
Weekend Carpentry: Baby Gate
Running C# MPI.NET Applications with Mono and OpenMPI
- Mono 3.4.0
- MPI.NET source code revision 338.
svn co https://svn.osl.iu.edu/svn/mpi_net/trunk -r 338 mpi.net- Also, download the Unsafe.pl.patch, which was originally available here
- OpenMPI 1.4.3. Note this is a retired version of OpenMPI and we are using it only because that's the best that I could get MPI.NET to compile against. If in future MPI.NET team provides support for a newer version of OpenMPI, you may be able to use it as well.
- Automake 1.9. Newer versions may work, but I encountered some errors in the past, which made me stick with version 1.9.
- I suggest installing everything to a user directory, which will avoid you requiring super user privileges. Let's create a directory called
build_monoinside home directory.mkdir ~/build_monoThe following lines added to your~/.bashrcwill help you follow the rest of the document.BUILD_MONO=~/build_mono PATH=$BUILD_MONO/bin:$PATH LD_LIBRARY_PATH=$BUILD_MONO/lib ac_cv_path_ILASM=$BUILD_MONO/bin/ilasm export BUILD_MONO PATH LD_LIBRARY_PATH ac_cv_path_ILASMOnce these lines are added do,source ~/.bashrc - Build automake by first going to the directory that containst
automake-1.9.tar.gzand doing,tar -xzf automake-1.9.tar.gz cd automake-1.9 ./configure --prefix=$BUILD_MONO make make installYou can verify the installation by typingwhich automake, which should point toautomakeinside$BUILD_MONO/bin - Build OpenMPI. Again, change directory to where you downloaded
openmpi-1.4.3.tar.gzand do,tar -xzf openmpi-1.4.3.tar.gz cd openmpi-1.4.3 ./configure --prefix=$BUILD_MONO make make installOptionally if Infiniband is available you can point to theverbs.h(usually this is in/usr/include/infiniband/) by specifying the folder/usrin the aboveconfigurecommand as,./configure --prefix=$BUILD_MONO --with-openib=/usrIf building OpenMPI is successfull, you'll see the following output formpirun --versioncommand,mpirun (Open MPI) 1.4.3 Report bugs to http://www.open-mpi.org/community/help/Also, to make sure the Infiniband module is built correctly (if specified) you can do,ompi_info|grep openibwhich, should output the following.MCA btl: openib (MCA v2.0, API v2.0, Component v1.4.3) - Build Mono. Go to directory containing
mono-3.4.0.tar.bz2and do,tar -xjf mono-3.4.0.tar.bz2 cd mono-3.4.0Mono 3.4.0 release is missing a file, which you'll need to add by pasting the following content to a file called./mcs/tools/xbuild/targets/Microsoft.Portable.Common.targets<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="..\Microsoft.Portable.Core.props" /> <Import Project="..\Microsoft.Portable.Core.targets" /> </Project>You can continue with the build by following,./configure --prefix=$BUILD_MONO make make installThere are several configuration parameters that you can play with and I suggest going through them either inREADME.mdor in./configure --help. One parameter, in particular, that I'd like to test with is--with-tls=pthread - Build MPI.NET. If you were wonder why we had that
ac_cv_path_ILASMvariable in~/.bashrcthen this is where it'll be used. MPI.NET by default tries to find the Intermediate Language Assembler (ILASM) at/usr/bin/ilasm2, which for 1. does not exist because we built Mono into$BUILD_MONOand not/usr2. does not exist because newer versions of Mono calls thisilasmnotilasm2. Therefore, after digging through theconfigurefile I found that we can specify the path to the ILASM by exporting the above environment variable.Alright, back to building MPI.NET. First copy the downloadedUnsafe.pl.patchto the subversion checkout of MPI.NET. Then change directory there and do,patch MPI/Unsafe.pl < Unsafe.pl.patchThis will say some hunks failed to apply, but that should be fine. It only means that those are already fixed in the checkout. Once patching is completed continue with the following../autogen.sh ./configure --prefix=$BUILD_MONO make make installAt this point you should be able to findMPI.dllandMPI.dll.configinsideMPIdirectory, which you can use to bind against your C# MPI application.
- Here's a sample MPI program written in C# using MPI.NET.
using System; using MPI; namespace MPINETinMono { class Program { static void Main(string[] args) { using (new MPI.Environment(ref args)) { Console.Write("Rank {0} of {1} running on {2}\n", Communicator.world.Rank, Communicator.world.Size, MPI.Environment.ProcessorName); } } } } - There are two ways that you can compile this program.
- Use Visual Studio referring to MPI.dll built on Windows
- Use
mcsfrom Linux referring to MPI.dll built on Linuxmcs Program.cs -reference:$MPI.NET_DIR/tools/mpi_net/MPI/MPI.dllwhere$MPI.NET_DIRrefers to the subversion checkout directory of MPI.NETEither way you should be able to getProgram.exein the end.
- Once you have the executable you can use
monowithmpirunto run this in Linux. For example you can do the following within the directory of the executable,mpirun -np 4 mono ./Program.exewhich will produce,Rank 0 of 4 running on i81 Rank 2 of 4 running on i81 Rank 1 of 4 running on i81 Rank 3 of 4 running on i81wherei81is one of the compute nodes in FutureGrid cluster.You may also use other advance options with mpirun to determine process mapping and binding. Note. the syntax for such controlling is different from latest versions of OpenMPI. Therefore, it's a good idea to look at different options frommpirun --help. For example you may be interested in specifying the following options,hostfile=<path-to-hostfile-listing-available-computing-nodes> ppn=<number-of-processes-per-node> cpp=<number-of-cpus-to-allocate-for-a-process> mpirun --display-map --mca btl ^tcp --hostfile $hostfile --bind-to-core --bysocket --npernode $ppn --cpus-per-proc $cpp -np $(($nodes*$ppn)) ...where,--display-mapwill print how processes are bind to processing units and--mca btl ^tcpforces to turn offtcp
Avoid Comcast DNS Hijacking in Ubuntu
Then when I opened the /etc/resolv.conf I found that Comcast has inserted its nameservers into that and after removing those entries and setting the nameserver to Google's 8.8.8.8 I was able to connect and browse as usual.
Hope this helps someone in a similar situation!
Get PID from Java
public static String getPid() throws IOException {
byte[] bo = new byte[100];
String[] cmd = {"bash", "-c", "echo $PPID"};
Process p = Runtime.getRuntime().exec(cmd);
p.getInputStream().read(bo);
return new String(bo);
}
C# and Java Operators Thread Safety
It seems these two step operations, i.e. x op= y, x++, x--, ++x, and --x, are NOT thread safe. It makes sense as these operations require reading the current value of the given variable and then updating it with the computed value. It is possible for threads to interleave between these operations resulting erroneous final values.
There are many ways to guarantee the atomicity in such cases including synchronized blocks, atomic data types such as Java AtomicInteger, and interlocked operations like in C#.
Here are some links that may help,
C# interlocked methods: http://msdn.microsoft.com/en-us/library/System.Threading.Interlocked_methods.aspx
Java atomic classes http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html
C# library to do threading similar to OpenMP like constructs http://msdn.microsoft.com/en-us/library/dd460717.aspx
A Java alternative OpenMP like parallel constructs https://wiki.rice.edu/confluence/display/HABANERO/Habanero+Multicore+Software+Research+Project
Weekend Carpentry: Shaver Holder
Running Chapel Programs on Titan
The following is a quick start to get Chapel programs run on multi-locale with Titan.
- Modules – the default set of modules is all what you need. You may load PrgEnv-cray/4.1.40 instead of the one loaded.
- Environment – you’ll need to have the following variables exported, usually through ~/.bashrc (in my case I used Chapel 1.7.0)
export CHPL_LOC=/tmp/work/csep65/chapel-1.7.0
export CHPL_HOME=$CHPL_LOC
export CHPL_COMM=gasnet
export GASNET_QUIET=yes
export CHPL_HOST_PLATFORM=cray-xk
export CHPL_LAUNCHER=pbs-aprun
export CHPL_LAUNCHER_QUEUE=batch
export CHPL_LAUNCHER_WALLTIME=00:10:00
export CHPL_LAUNCHER_ACCOUNT=TRN001
export CHPL_HOST_COMPILER=gnu
export PATH=${CHPL_LOC}/bin/$CHPL_HOST_PLATFORM:$PATH
Also, note the values in red need to be changed accordingly. The CHPL_LAUNCHER_ACCOUNT will be the account in Titan to get billed. You can find more information on this in the $CHPL_HOME/doc/platforms/README.cray (search for NCCS).
- Launcher tweak – note this fix is avaialble in Chapel code trunk following revision 21702 (http://sourceforge.net/p/chapel/code/21702/tree/trunk/) so will be necessary only if you are using a release 1.7.0 or older. A minor change to Chapel’s PBS launcher is necessary for these versions to work with Titan due to some upgrade in the qsub wrapper used by Titan. The fix is to change the two occurrences of –l size with –l nodes in $CHPL_HOME/runtime/src/launch/pbs-aprun/launch-pbs-aprun.c
- Compile Chapel – once the above steps are completed use the Makefile under $CHPL_HOME to compile Chapel as usual
- Compile your program – use the chpl compiler to compile your program, which will create two outputs, for example a.out and a.out_real. More information on what each of this means is available in the $CHPL_HOME/doc/README.multilocale
- Start your program – you can use, for example ./a.out –nl 4 to launch your program on 4 locales. Chapel launcher will take care of submitting the correct PBS job for Titan’s job scheduler.
Tail Recursion with Python
Weekend Carpentry: Wall Shelf
Update Aug 2014
Sketchup file at https://www.dropbox.com/s/0qa79linxceagwr/shelf.skp
PDF file at https://www.dropbox.com/s/5iaalnhmfmkkke8/Shelf.pdf
If you like to give it a try, here's the plan.
The top two are the vertical and horizontal center pieces. The last four pieces are for top, bottom, left, and right dividers. The joints are simply half lap joints (see http://jawoodworking.com/wp-content/uploads/2008/09/half-lap-joint.jpg).
Just remember to finish wood pieces before assembling. It's much easier than having to apply finish to the assembled product, which unfortunately is what I did.
How to Remove Shelf Liner Adhesive
Never ever use adhesive shelf liners, they suck!
Anyway, since you are here already, here are few tips to help you out.
1.) If you can, use a hairdryer to apply heat while pulling the liner.
2.) No matter how much caution you take, these will always leave a layer of sticky residue behind. This is where it sucks.
2.1) Use WD-40 (http://en.wikipedia.org/wiki/WD-40) and scrape off (using a plastic ruler edge or a small scraper) the sticky mess. You’ll have to do this multiple times and when you scrape use smooth single strokes rather going back and forth.
2.2.) Once you remove bulk of the goo, you’ll still end up having a sticky surface. This is where you need to use coconut oil. Apply oil to a piece of cloth and rub to remove the remaining left over adhesive.
3.) Once all this is done, it’s a good idea to wash away any remaining WD-40 and coconut oil with soapy water and wipe clean with a piece of cloth or sponge.
Excel Histograms
C# String Vs Secure String
Interesting articles on the subject at,
1.) http://blogs.msdn.com/b/shawnfa/archive/2004/05/27/143254.aspx
In summary, a string object is not the best place to keep sensitive information such as passwords, credit card numbers, etc. due to its nature of not being able to lock in one place of memory, immutability (results multiple copies if modified), and possible page swaps (sensitive data now in tmp files) (see 1). Use SecureString as a solution, but sometimes you may still want to get the unsecured string representation as some APIs still don’t support secure strings (see 2).
While at it, you may also like to read about reading a string securely from console,
3.) http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx
4.) http://stackoverflow.com/questions/3404421/password-masking-console-application
Running MPI.NET Applications with Mono in Ubuntu
The following blog post is a great starting point with all the details you'll need. So I'll skip the steps, except to point out couple of caveats you need to consider.
http://blog.biophysengr.net/2011/11/compiling-mpinet-under-ubuntu-oneiric.html
- automake versions above 1.9 will give you an error when building MPI.NET. May be you can change the make script to work with them, but I found it easy to just install automake1.9 to solve it.
- You'll need to add /usr/local/lib to your LD_LIBRARY_PATH. Essentially what you need to do is add this path to /etc/ld.so.conf and run ldconfig as root. See documenation from Mono on this at http://www.mono-project.com/DllNotFoundException
- Make sure to do chmod +x to your dlls



