Friday, November 12, 2010

Java XML DOM Document creation

/**
 * Since if found some crap on the Internet, here a better example for creating an XML document in Java. 
 * 
 * Copyright: Harald Schilly
 * License: Apache 2.0
 */


package at.schilly.aldap2.ue12131415xml;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;


/** @author harald schilly */
public class MapToXml {
  
  final private SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
  
  /** this method takes a Map of Strings to Strings and builds an xml document.
   * 
   * @param xmlfn
   *          xml output filename
   * @param map
   *          just a plain Map
   * @throws ParserConfigurationException
   * @throws FileNotFoundException
   * @throws TransformerException */
  public void write(final File xmlfn, final Map map)
      throws ParserConfigurationException, FileNotFoundException,
      TransformerException {
    // Docbuilder to create the xmldoc
    DocumentBuilderFactory docbuilderfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docbuilder = docbuilderfactory.newDocumentBuilder();
    Document xmldoc = docbuilder.newDocument();
    
    // That's the root element
    Element root = xmldoc.createElement("map");
    
    // last saved element
    Element lastsaved = xmldoc.createElement("lastSavedBy");
    lastsaved.setAttribute("name", "Harald Schilly");
    lastsaved.setAttribute("date",
        dateformat.format(Calendar.getInstance().getTime()));
    root.appendChild(lastsaved);
    
    // iterate over map and add the entry/value elements
    for (Map.Entry mapentry : map.entrySet()) {
      Element entry = xmldoc.createElement("entry");
      entry.setAttribute("key", mapentry.getKey());
      
      Element value = xmldoc.createElement("value");
      Node node = xmldoc.createTextNode(mapentry.getValue());
      
      value.appendChild(node);
      entry.appendChild(value);
      root.appendChild(entry);
    }
    xmldoc.appendChild(root);
    
    // get a transformer with the given .dtd
    TransformerFactory transormerfactory = TransformerFactory.newInstance();
    Transformer transformer = transormerfactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "map.dtd");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    
    // transform and write to a file
    // use a StringWriter() object to write to a string.
    FileOutputStream fos = new FileOutputStream(xmlfn);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    StreamResult result = new StreamResult(bos);
    DOMSource source = new DOMSource(xmldoc);
    transformer.transform(source, result);
  }
}

Saturday, March 6, 2010

Anchors in Sage Notebooks

If you have a lengthy Sage Notebook and you want to quickly jump to a certain header or paragraph as a reference, use HTML anchors. They work like follows:
  1. An <a name="anchorname"></a> tag must be inserted at the position you want to jump to.
  2. Reference it via <a href="#anchorname">some text</a>.
After that, you can jump to the marked position just by clicking on the some text link.

To insert rich text and HTML, use the rich text editor accessible via <shift>+<click on blue insert bar>. There is an "HTML" icon. Alternatively, you can use the html() function:
i.e. html('<a name="test"></a>') ...

Saturday, February 13, 2010

dotA Itemkauf Optimierung

Mein Mitbewohner ließ nicht locker,
spielte täglich dieses dotA.

Nach jedem Itemkauf fragte er sich,
ob sich das nicht besser machen lies.

Hier ein ZIMPL Skript zum optimieren,
bitte schreib es fertig, sonst ists zum genieren.

Flott sagt dir SCIP dann ganz korrekt,
wo du am besten dein Gold hinsteckst.




# zimpl model for optimizing buying dotA items
# copyright 2010: harald schilly
# license: CC-BY-NC-SA 3.0


# helden
set helden := { 1 to 5 };


# freie plätze zum einkaufen
param frei[helden] :=  <1> 6, <2> 4, <3> 4, <4> 2, <5> 6;


# welche items es gibt
set items := { 1 to 3} ;


# kosten pro item
param itemcost[items] := <1> 100, <2> 50, <3> 63;


# menge der fähigkeiten die jeder item pushen kann
set abilities := { 1 to 4 };


# was jeweils besser wird
param itempower[abilities * items] := 
  |   1,  2,   3 |
|1|   5,  1,   0 |
|2|   0,  1,   4 |
|3|   1,  1,   8 |
|4|   1,  4,  10 |;


# basiswert der zum maximum einer spalte addiert wird
# notwendig in der zielfunktion für die gewichtung
param baseval := 1;


# gesamtbuget an gold
param budget := 500;


# die variablenmatrix
var buy[helden * items] integer >= 0 <= 6;


# man kann nur so viel kaufen wie geld da ist
subto costs:
  sum <h,i> in helden * items: 
    buy[h,i] * itemcost[i] <= budget;


# man kann nur so viel kaufen wie der
# held noch freie plätze hat
subto maxperheld: 
  forall in helden:
    sum in items: buy[h, i] <= frei[h];


# ich will die fähigkeiten meines teams maximieren
maximize obj: sum <h,i,a> in helden * items * abilities:
  (itempower[a, i] / (baseval + max <a> in abilities: itempower[a,i])) * buy[h, i];




Thursday, January 21, 2010

Compiling Sage on my Atom N270 Netbook

Here are some notes to myself regarding compiling Sage on my HP Mini 2140 with an Atom N270 CPU. I'm running Linux Ubuntu 9.10. This successfully compiles Sage 4.3 and 4.3.1 and might also work for later version.

Download


# using aria2, first get aria2
sudo apt-get install aria2
# go to a local directory and just use the .metalink link
$
aria2c http://server/path/sage-x.y.z.tar.metalink


# note, that aria2c doesn't stop when it has finished.
# it will start seeding the file to others via bittorrent.
# You can terminate this by hitting Ctrl-C


####

# or download via http/ftp from the download page

Verify

# If you think your download might have been corrupted, verify it:
aria2c -V http://server/path/sage-x.y.z.tar.metalink


Extract


# any local directory is fine
$ tar xf sage-x.y.z.tar


Prerequisites

# You need some tools to compile Sage:
$ sudo apt-get install build-essential m4\
readline libreadline-dev gfortran texlive
# read more: Installation Guide

Setup Build Environment

$ cd sage-x.y.z

# get rid of some environment variables, unless
# you know what you do (i.e. ccache, ...)
$
unset CC
$
unset CXX

see README.txt if you need this
$
export SAGE_FAT_BINARY="yes"

# if you have gfortran library problems
# find your correct paths via $ locate gfortran
# setting these variables is necessary on Ubuntu 9.10
$
export SAGE_FORTRAN=/usr/bin/gfortran
$ export SAGE_FORTRAN_LIB=/usr/lib/libgfortran.so.3

# note: do not start over compilation if that problem happens,
# you have to remove and clean up everything first

# there are two cores in the CPU
# use both of them in parallel!
$
export MAKE="make -j2"

Start Compilation

# in a resource friendly mode
$ ionice -c 3 nice make

Testing and Packaging


If compilation didn't end with an error (otherwise: search, sage-support and sage-devel or irc chat)

# Test the entire beast (2 for 2 CPU cores):
$ ./sage -tp 2 devel/sage-main
# or
$ ./sage -testall
# once again, please report problems

If you want to build a
binary distribution, upload it to us at sagemath.org or send it to a friend with a similar machine+system:



$ ./sage -bdist x.y.z-LinuxVersion;

On systems like Ubuntu, you can shrink the resulting archive much smaller using lzma compression. "trans-compress" it via:


$ zcat sage-x.y.z-...tar.gz | lzma -zv > sage-x.y.z-...tar.lzma

and to extract the tar.lzma later:

$ tar --lzma -xvf sage-x.y.z...tar.lzma

Links