Random posts about coding

Mostly blogging about dart.

Dart: CSS3 Slider Carousel

| Comments

The slider carousel by html5rocks now comes with an example in dart. I may have loaded to many  images into the single page, might take a few seconds to load. The source code can be found on github. Dart provides a simpler way to deal with client side programming, cleaner syntax and simple access to the DOM. Go Dart!

screenshot

Dart: Updated Dartium Builds for Linux and Mac

| Comments

Following the similar posts as before, you can get the latest Dartium builds for Mac OSX and 32bit Linux here. My public is can be found on pgp.mit.edu. Please contact me if you have any issues, only providing these until Dartium hits the prime time. Keep in mind that nothing is guaranteed to work at this point… but some stuff does. [sourcecode lang=”bash”] wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz.sig wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz.md5 wget http://dl.dropbox.com/u/33138127/dartium_macosx/README.txt gpg –verify Chromium.app.tar.gz.sig Chromium.app.tar.gz md5sum -c Chromium.app.tar.gz.md5 [/sourcecode] [sourcecode lang=”bash”] wget http://gsdview.appspot.com/dart-editor-archive-continuous/latest/DartBuild-linux.gtk.x86.zip wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz.sig wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz.md5 wget http://dl.dropbox.com/u/33138127/dartium/README.txt gpg –verify dartium-linux-32bit-Release.tar.gz.sig dartium-linux-32bit-Release.tar.gz md5sum -c dartium-linux-32bit-Release.tar.gz.md5 [/sourcecode]

Dart: Web Terminal Sample

| Comments

I’ve always been impressed by the css/html5/javascript web terminals that show off the filesystem API. Now Dart has a sample web terminal with minimal implementation. webterminal Simply add your command implementations to the Terminal.dart by adding commands to the CMDS list and providing functions to the matching switch statement. cmds
switch With in the next day or so the dart-web-terminal should include an example with filesystem API in dart.

Dart: Dart:builtin

| Comments

dart:builtin are the runtime libraries available to the DartVM. They provide some of the more system level API you would expect such as streams I/O, filesystem I/O, basic TCP socket I/O, platform information, native process invocation.  Most of these class implementations do call “native”, which from the point of view of the DartVM means invoking native VM code. “native” tells the VM to look up in a list for the entry that maps to the following argument after “native”. _DirectoryNative nativedirectory.png While Dart is still Alpha these builtin may not be written in stone, so try not to depend on them too much. They can and do provide you with some neat access to native functionality you would commonly need when written shell/system applications. By including #import(‘dart:builtin’); you can view the builtin dart files from DartEditor. Currently the DartEditor might show  warnings when including this module but runtime should not be affected. The truth of the matter is, if you explicitly include ‘dart:builtin’ or not, it is still available to you from implicit inclusion in the DartVM. dartbuiltin The following should give an idea of what built in objects are accessible and how they may be used. The examples should not be considered best practices, just an idea of how you could use them and that they exist. The code is taken from a sample that can be found on Github Directory [sourcecode lang=”java”] Directory d; if (l.length >= 2) { d = new Directory(l[1]); } else { d = new Directory("."); } d.dirHandler = (var dir) { print("${dir}"); }; d.fileHandler = (var file) { print("${file}"); }; d.list(true); [/sourcecode] File [sourcecode lang=”java”] File f = new File(l[0]); if (!f.existsSync()) { print("Error: file does not exist"); return; } RandomAccessFile r = f.openSync(FileMode.READ); int length = r.lengthSync(); List buffer = new List(length); int readLength = r.readListSync(buffer, 0, length); r.close(); String s = new String.fromCharCodes(buffer); print(s); [/sourcecode] ChunkedInputStream [sourcecode lang=”java”] ChunkedInputStream chunkedInputStream = new ChunkedInputStream(f.openInputStream(), 16); List c = chunkedInputStream.read(); while(c!=null) { StringBuffer sb = new StringBuffer(); c.forEach((int b) { sb.add("0x"); if (b.toRadixString(16).length == 1) { sb.add("0"); } sb.add(b.toRadixString(16)); sb.add(" "); }); print(sb.toString()); c = chunkedInputStream.read(); } [/sourcecode] InputStream OutputStream [sourcecode lang=”java”] File src = new File(arg[1]); File dest = new File(arg[2]); var srcStream = src.openInputStream(); var destStream = dest.openOutputStream(); destStream.write(srcStream.read()); srcStream.close(); destStream.close(); [/sourcecode] StringInputStream DynamicListInputStream ListInputStream ListOutputStream Platform [sourcecode lang=”java”] Platform p = new Platform(); print(‘{"operatingSystem":${p.operatingSystem()},"numberOfProcessors":${p.numberOfProcessors()},"pathSeparator":${p.pathSeparator()}}’); [/sourcecode] Process [sourcecode lang=”java”] Process ps = new Process.start(‘ps’, []); StringBuffer messages = new StringBuffer(); ps.exitHandler = (int status) { ps.close(); print(messages.toString()); }; ps.stdout.dataHandler = () => _readAll(ps.stdout, messages); ps.stderr.dataHandler = () => _readAll(ps.stderr, messages); [/sourcecode] ServerSocket [sourcecode lang=”java”] // initialize the server serverSocket = new ServerSocket(host, 0, 5); if (serverSocket == null) { throw "can’t get server socket"; } serverSocket.connectionHandler = onConnect; print("accepting connections on ${host}:${serverSocket.port}"); [/sourcecode] Socket [sourcecode lang=”java”] sendSocket = new Socket(host, serverSocket.port); if (sendSocket == null) { throw "can’t get send socket"; } // send first 4 bytes immediately for (int i = 0; i < 4; i++) { sendByte(); } // send next 4 bytes slowly new Timer.repeating((Timer t) { sendByte(); if (bytesSent == bytesTotal) { sendSocket.close(); t.cancel(); print("finished sending"); } }, 500); [/sourcecode] SocketInputStream SocketOutputStream Timer [sourcecode lang=”java”] <pre> if (l.length >= 2) { try { milliSeconds = (Math.parseInt(l[1]).abs()*milliSeconds); } catch (BadNumberFormatException ex) {} } timer = new Timer((var t) { print("\nTime elapsed on Timer"); }, milliSeconds); [/sourcecode]

Dartium Mac OSX Build Rev 117836

| Comments

For those interested in trying Dartium on MacOSX, here is a build of Dartium from Dart’s bleeding_edge. I have just tested it enough to run hello world at the moment. I’d like to get feed back on how it runs for others if possible. 
NewImage

[sourcecode lang=”bash”]wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz wget http://dl.dropbox.com/u/33138127/dartium_macosx/Chromium.app.tar.gz.md5 wget http://dl.dropbox.com/u/33138127/dartium_macosx/README.txt md5sum -c Chromium.app.tar.gz.md5 [/sourcecode]

It might be best to refer to this previous post for any additional information.

Dart: Throwing Darts From CouchDB

| Comments

CouchDB provides an excellent NOSQL database with simple REST API. Continuing on with the odds and ends in Dart, I’d like to show how one could interface with CouchDB in Dart. Following the “Getting started with Python” I was able to stub out a simple wrapper implementation in no time. At some point a full wrapper should be done, I’ll possible look into it in the coming months.
CouchBase provides full standalone community build, best option if you don’t want to deal with building and deploying on your Mac. Pairing that up with XAMPP and you’ll be able to write the client side that communicates to the apache web server which then proxies to CouchDB. After installing XAMPP two files need to be edited to ease the local deployment.
[sourcecode] XAMPP/etc/http.conf - Add the ProxyPass configuration. XAMPP/etc/extra/httpd-userdir.conf - Add the user directory to point to the default dart folder location. [/sourcecode]
Httpconf
Fire up CouchDB and Apache, then open chrome http://127.0.0.1/couchdb and you should see the following.
Localhost
From here we can use XMLHttpRequest provided in the dart:html library to make requests to the Apache web server which proxy to CouchDB. One issue I ran into was DOMException INVALID_STATE_ERR when trying to set the headers. You must call open() before your able to call setRequestHeader().
[sourcecode lang=”java”] // Basic http methods getHttp(var uri) { XMLHttpRequest c = connect(); c.open(‘GET’, uri, false); c.setRequestHeader(‘Accept’, ‘application/json’); c.send(); return c.responseText; } postHttp(var uri, var body) { XMLHttpRequest c = connect(); c.open(‘POST’, uri, false); c.setRequestHeader(‘Content-type’, ‘application/json’); c.send(body); return c.responseText; } putHttp(var uri, [var body]) { XMLHttpRequest c = connect(); c.open(‘PUT’, uri, false); if (body is String && body.length > 0) { c.setRequestHeader(‘Content-type’, ‘application/json’); c.send(body); } else { c.send(); } return c.responseText; } deleteHttp(var uri) { XMLHttpRequest c = connect(); c.open(‘DELETE’, uri, false); c.send(); return c.responseText; } [/sourcecode]
Domexception
From there stubbing out a simple interface for dart with default implementation was easy.
Couchdb
The CouchDBWrapperImpl does wrapping for calling to the CouchDB using the default keyword helps to hide the implementation from the interface in a factory type way.
Couchdbimpl
Opening up chrome to http://127.0.0.1/<username> provides access into the users dart directory.
Fileview
Clicking on CouchDBExample.html should run the sample code.
Demo
The interfacing with CouchDB was simple and quick, a more elegant solution would be a full client implementation that lets you modify objects more indirectly.  Sample code on github.

Dart: Using Prefix for #import

| Comments

Using “prefix” is great for managing how your application references libraries in Dart. At the moment Dart is still in alpha so this exact method or style may change at some later date. From the Language Specification (0.06) Libraries have a very simple definition.
A library consists of (a possibly empty) set of imports, and a set of top level declarations. A top level declaration is either a class (7), an interface (8), a type declaration, a function (6) or a variable declaration (5).
Lets dive in and create one main application and one cipher application that will be a library. Now if we #import CipherLib from filesystem path into our MainApplication both main functions should conflict. Why this happens is clearly defined in the specification.
Imports assume a global namespace of libraries (at least per isolate). They also assume the library is in control, rather than the other way around. It is a compile-time error if a name N is introduced into the library scope of a library A, and either: N is declared by A, OR Another import introduces N into the scope of A. This implies that it is a load-time error for a library to import itself, as the names of its members will be duplicated.
The MainAppication can be adjusted by adding the prefix parameter to the #import declaration. Now from the prefixed name we can call the main method. From this point lets add another library, will call it XORCipher which will call its library “CipherLib”. The XORCipher and CaesarCipher will have libraries named “CipherLib”, both have functions that have the same name but take different parameters. Now we shall run into a problem that could be presented when using others libraries or code, we have conflicting names in the global namespace of our main application. The way we resolve this is by adding prefix to one or both libraries and call them from the fully qualified names.[sourcecode lang=”java”] #import(‘../CaesarCipher/CaesarCipher.dart’, prefix:"Caesar"); #import(‘../XORCipher/XORCipher.dart’, prefix:"XOR"); void main() { String s = "HELLOWORLD"; print("${s}"); s = XOR.EncryptDecrypt(s); print("After encrypt XOR ${s}"); s = XOR.EncryptDecrypt(s); print("After decrypt XOR ${s}"); s = Caesar.EncryptDecrypt(s, true); print("After encrypt Caesar ${s}"); s = Caesar.EncryptDecrypt(s, false); print("After decrypt Caesar ${s}"); } [/sourcecode] Another way to encapsulate source code using libraries is to use the #source declaration in a #library and then to #import the library into your application. From the language specifications:
An include directive specifics a URI where a Dart compilation unit that should be incorporated into the current library may be found. A compilation unit is a sequence of top level declarations. Compiling an include directive of the form #source(s); causes the Dart system to attempt to compile the contents of the URI that is the value of s. The top level declarations at that URI are then compiled by the Dart compiler in the scope of the current library. It is a compile-time error if the contents of the URI are not a valid compilation unit. It is a compile-time error if s is not a compile-time constant.
An example of this type of library can be seen in HashLib/hashlib.dart:[sourcecode lang=”java”] #library(‘hashlib’); #source(‘hasher.dart’); #source(‘hasherimpl.dart’); #source(‘aphash.dart’); #source(‘bkdrhash.dart’); #source(‘dekhash.dart’); #source(‘djbhash.dart’); #source(‘elfhash.dart’); #source(‘jshash.dart’); #source(‘pjwhash.dart’); #source(‘rshash.dart’); #source(‘sdbmhash.dart’); #source(‘nullhash.dart’); #source(‘bphash.dart’); #source(‘fnvhash.dart’); [/sourcecode] Another great example of this can be seen in John Evans LUCA UI Framework unit test code. He needed access to some internal dom objects but wanted to preserve the ability to use the elegantly designed html library. [sourcecode lang=”java”] #import(‘dart:html’); #import(‘dart:dom’, prefix:’dom’); #import(‘../unit_test_framework/UnitTestFramework.dart’); #import(‘../core/LUCA_UI_Framework.dart’); [/sourcecode] Its not uncommon to run into instances where two libraries or source files may define classes, interfaces, functions, type definitions that have similar names in other libraries or source files. The best way to work in these types of situations is to add a prefix where your #import are. A very common one that people run into is with “html”, Node and Element class. So individuals wanting to create some type of search or sorting might also want to use the Node name, best answer would be to prefix “html” or your own library code. After your able to reference the library by its fully qualified name, instead of assuming it was globally included. This does feel similar to the using alias in C#, but with a feeling of inversion of control to the library. References: Sample code dart-using-prefix-example Language specification

Dart: Exploring the DartVM From a Debugger on Mac OSX

| Comments

This may be useless to many, obvious to some and complete wrong for others, but I would like to comment for the wondering dart on how to debug the VM. Goal of this post is to provide a quick and reproducible way to explore the DartVM at runtime on Mac OSX. I personally enjoy watching code from a debugger, so this was helpful to explore what is going on under the hood. We currently have two projects to debug from. dartruntime and dart.googlecode.com. Get this version of Eclipse Mac OSX 32bit cocoa. I typically use the cmake branch cause I’m working with dart on Mac OSX and I dont want to touch xcode. The main dart project generates xcode projects for builds, you could use xcode to edit the c++ code. Having to choose between eclipse or xcode, I personally pick eclipse. Using the cmake project is a little cleaner/simpiler/complete to import from as Makefile project. (I could be wrong, but didn’t want to invest more time into importing stuff I’m not interested in). Setting up DartVM the song and dance from googlecode goes like this. For using the cmake branch provided by Peter Kümmel is as follows:[sourcecode lang=”bash”]git clone git@github.com:syntheticpp/dartruntime.git cd dartruntime git checkout -b cmake origin/cmake cd .. mkdir build cd build cmake ../dartruntime/cmake/ make -j4 echo "main() { print(\"Hello World\!\"); }" > hello.dart ./bin/dart ./hello.dart[/sourcecode] After having a debug build on either branch you can target the executable directly by choosing to importing C/C++ Executable. Next select the executable you want to target from either build. The debug builds will provide all the symbols and source code mapping. Name the project and debug launch target as you need. Set the arguments to pass to the dartvm, here we are setting a hello world sample based on an Actor Model. The debugger will break on the main entry point. [gallery] It is proabably possible that the dart runtime envionment setup is similar to what chrome is used too, so the instructions on how to setup eclipse for chrome may also apply. I have not tried it out my self. A follow up post will show how to import the c++ code to eclipse and build from generated Makefiles.

Dart: Build and Edit DartVM From Eclipse

| Comments

In previous post I mentioned how to get eclipse debugger hooked up to DartVM. Here I’d like to comment how one could generate Makefiles from the cmake branch and import the C/C++/Dart code into eclipse to edit and build. Here we start off by having the built environment: [sourcecode lang=”bash”]git clone git@github.com:syntheticpp/dartruntime.git cd dartruntime git checkout -b cmake origin/cmake cd .. mkdir build cd build cmake ../dartruntime/cmake/ make -j4 echo "main() { print(\"Hello World\!\"); }" > hello.dart ./bin/dart ./hello.dart[/sourcecode] Then import the build directory as a “Existing Code as Makefile Project”. We can now build from eclipse by clicking on the build button in the eclipse editor. We would like to import the dart runtime into eclipse so we can get the ability to edit from an IDE and build from an IDE. Import an “Existing Code as Makefile Project” and choosing the runtime directory. Chose the GNU autotools toolchain when selecting the “Toolchain Indexer Settings”. This should now provide better ability to navigate the code and build from the IDE. Note that the build output will be sent to the build folder and if the Makefiles get wiped out from the build folder you would have to regenerate them from cmake. [gallery]

Dartium Build Rev 116980 in 4 Easy Steps

| Comments

At the moment Dartium builds are not available on Googles continuous integration server. So I decided to distribute a release build for Linux 32bit . Based on the wiki directions its simple enough for anyone to generate, I felt the need to distribute a build for those who don’t have the time to invest in downloading/configuring/building. An important tip testing dart code in Dartium is to include the additional script call that executes the entry into main(). This is done by adding an additional <script>{}</script> following the line where the dart code is loaded.

The build of Dartium provide is from Rev: 116980

  • Get the latest version of DartEditor and Dartium

wget http://gsdview.appspot.com/dart-editor-archive-continuous/latest/DartBuild-linux.gtk.x86.zip
wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz
wget http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz.md5
wget http://dl.dropbox.com/u/33138127/dartium/README.txt
md5sum -c dartium-linux-32bit-Release.tar.gz.md5
  • Register Dartium on Ubuntu as a registered application so DartEditor can pick it up. Modify dartium-browser.desktop to the chrome-wrapper where Dartium was unzipped.
wget http://dl.dropbox.com/u/33138127/dartium/dartium-browser.desktop
vim dartium-browser.desktop
wget http://dl.dropbox.com/u/33138127/dartium/dartium-browser.desktop.ubuntu.install.sh
sudo ./dartium-browser.desktop.ubuntu.install.sh
  • Register Dartium as the browser to launch in DartEditor

  • Create a famous HelloWorld.

Adjust the html to properly execute dart.

Watch dart in its metal state.

Links:
http://dl.dropbox.com/u/33138127/dartium/dartium-browser.desktop
http://dl.dropbox.com/u/33138127/dartium/dartium-browser.desktop.ubuntu.install.sh
http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz
http://dl.dropbox.com/u/33138127/dartium/dartium-linux-32bit-Release.tar.gz.md5
http://dl.dropbox.com/u/33138127/dartium/README.txt