I just wanted to write out loud that CsvHelper in C# to read and write CSV file is absolutely awesome, it is a must to have. This library just saved me countless of times. Many thanks to its author Josh Close.
mardi 1 novembre 2022
dimanche 18 avril 2021
ANTLR parser for simple expression
Hello,
Yes this is a very long time that I did not post anything... I recently had to make an interpreter (in swift) of quite simple expression. I thought of reusing it in some C# programs. My first thought were immediately to ANTLR (which I used in Java few years ago). My second thought was to use Lemon, in C, it would have worked with swift because of Objective-C but I could not have used it in C# (please no interop).
I really advise the plugin in Intellij, it was so easy to use: right click on the rule you want to test...
expr: '(' e=expr ')' # paren
| name=KEYWORD '(' expr (',' expr)* ')' # fun
| left=expr op=('*' | '/') right=expr # mul
| left=expr op=('+' | '-') right=expr # add
| VARIABLE # variable
| DECIMAL # decimal
| INT # int
| STRING # string
| # empty
;
fragment LETTER: [a-zA-Z];
fragment DIGIT: [0-9];
VARIABLE: '[' LETTER+(LETTER | DIGIT)* '.' LETTER+(LETTER | DIGIT)* ']';
STRING : '"' ~('"')* '"';
INT : DIGIT+;
DECIMAL : DIGIT*'.'DIGIT+;
KEYWORD : LETTER+(LETTER | DIGIT)*;
and the program to parse a string would be (in kotlin):
val expression = "=coucou(12,23,34,56)"
val stream: CharStream = CharStreams.fromString(expression)
val lexer = MobiExprLexer(stream)
val tokenStream: TokenStream = CommonTokenStream(lexer)
val parser = MyExprParser(tokenStream)
val tree: ParseTree = parser.prog()
val result: Int = MyInterpreter().visit(tree)
println(result)
An interesting thing is that we use a visitor to interpret the AST
and here below how we can retrieve all parameters of a function:
here the rule as reminder: | name=KEYWORD '(' expr (',' expr)* ')' # fun
class MyInterpreter : MyExprBaseVisitor<Int>() {
override fun visitFun(ctx: FunContext): Int {
// expr() will be a list of all expr nodes, meaning all parameters
val params = ctx.expr().map { visit(it) }
// once we visit each of them, we now have the values to interpret the function
...
}
}
For those who were wondering, I now think that it is better to discouple the grammar from the implementation, it is allowing the grammar to be reused in multiple languages.
I personally also enjoyed doing some kotlin again :-)
Hope it was useful for you.
See you
samedi 12 mai 2018
Scala - try with resources
I started from this code and I enhanced it to look like my previous post for Kotlin.
find this code in https://github.com/spointeau/scala-using-autoClose/blob/master/MainUsing.scala
I also did re-implement the .use{} that I generally use in Kotlin when I deal with only 1 or 2 resources max. The implementation was so simple by reusing the autoClose. You can find the code in the same github file.
test1
Close test2
May 13, 2018 1:04:27 AM arm$using$ $anonfun$apply$1
WARNING: Close Exception test2
Close test1
java.lang.Exception: Close Exception test1
at TestToClose.close(MainUsing.scala:166)
at arm$using$.$anonfun$apply$1(MainUsing.scala:119)
at arm$using$.$anonfun$apply$1$adapted(MainUsing.scala:117)
at scala.collection.immutable.List.foreach(List.scala:389)
at arm$using$.apply(MainUsing.scala:117)
at MainUsing$.delayedEndpoint$MainUsing$1(MainUsing.scala:177)
at MainUsing$delayedInit$body.apply(MainUsing.scala:173)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:389)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at MainUsing$.main(MainUsing.scala:173)
at MainUsing.main(MainUsing.scala)
test3
Close test3
test4
Close test4
java.lang.Exception: Close Exception test4
at TestToClose.close(MainUsing.scala:166)
at arm$using$.$anonfun$apply$1(MainUsing.scala:119)
at arm$using$.$anonfun$apply$1$adapted(MainUsing.scala:117)
at scala.collection.immutable.List.foreach(List.scala:389)
at arm$using$.apply(MainUsing.scala:117)
at arm$AutoCloseResource$.use$extension1(MainUsing.scala:152)
at arm$AutoCloseResource$.use$extension0(MainUsing.scala:150)
at MainUsing$.delayedEndpoint$MainUsing$1(MainUsing.scala:193)
at MainUsing$delayedInit$body.apply(MainUsing.scala:173)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:389)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at MainUsing$.main(MainUsing.scala:173)
at MainUsing.main(MainUsing.scala)
did it help you?
jeudi 10 mai 2018
kotlin - try with resources
I recently tried Scala and during my learning of Scala, I immediately wondered how to close properly the resource like the try-with-resources from Java. I was really hoping that it was built-in but it is not unfortunately.
Then I thought about Kotlin, which has now the .use {} pattern. However I know by experience that it can be cumbersome if we have multiple resources, ending with a lot of nested . use{ .use{ .use{} } }
Did you think how the kotlin .use{} or the java try-with-resources works if the close raises an exception? it just raises.
what if we don't want the close to raise?
In java, the best approach I have see is to wrap the resource as explained here https://stackoverflow.com/questions/6889697/close-resource-quietly-using-try-with-resources
basically to wrap the resource like
try(QuietResourceqr = new QuietResource<>(new MyResource())){
MyResource r = qr.get();
r.read();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
While we can use the same approach for kotlin and wrap the resource and apply the .use{} on this wrapper, I would like to avoid all the nested use{} when we have multiple resources.
Inspired by the "using" block proposed by one member of the JetBrains team
https://discuss.kotlinlang.org/t/kotlin-needs-try-with-resources/214
I started from there and improved it for the exception handling. I wanted to be able also to control if the close must raise or at least the exception must appear in the log.
IMO the standard behaviour must be kept to raise if the close raises an exception but we should be able to make it closing quietly without exception and log it to keep an eye on it. Of course, all resources must be closed even so some raised an exception.
My proposed code is
class UsingResourceHolder { data class Resource(val x: AutoCloseable, val canThrow: Boolean, val doLog: Boolean) internal val resources = LinkedList() var logger: Logger? = Logger.getLogger("global") fun <T : AutoCloseable> T.autoClose(canThrow:Boolean = true, log:Boolean = false): T { resources.addFirst(Resource(this, canThrow = canThrow, doLog = log)) return this } fun <T : AutoCloseable> T.autoCloseQuietly(log:Boolean = false): T { return this.autoClose(canThrow=false,log=log) } } fun <R> using(block: UsingResourceHolder.() -> R): R { val holder = UsingResourceHolder() var globalException: Throwable? = null var exceptionOnClose: Throwable? = null try { return holder.block() } catch(t: Throwable) { globalException = t throw t } finally { holder.resources.forEach { r -> try { r.x.close() } catch (e: Exception) { if( globalException == null ) { if( r.canThrow ) { if (exceptionOnClose == null) exceptionOnClose = e else exceptionOnClose!!.addSuppressed(e) } else if(r.doLog) { holder.logger?.warning(e.message) } } else { if( r.canThrow ) globalException!!.addSuppressed(e) } } } if (exceptionOnClose != null) throw exceptionOnClose!! } }
and how to use it:

and the output is:
May 12, 2018 8:01:25 PM TryWithResourceKt using
WARNING: exception from ExceptionMaker.ex3
Exception in thread "main" java.lang.Exception: exception from ExceptionMaker.ex2
at ExceptionMaker.close(TryWithResource.kt:69)
at TryWithResourceKt.using(TryWithResource.kt:39)
at TryWithResourceKt.main(TryWithResource.kt:75)
Suppressed: java.lang.Exception: exception from ExceptionMaker.ex1
... 3 more
In case the using block is raising an exception, the exceptions from the close are then suppressed by this main exception:

Exception in thread "main" java.lang.Exception: Code failure
at TryWithResourceKt$main$1.invoke(TryWithResource.kt:81)
at TryWithResourceKt$main$1.invoke(TryWithResource.kt)
at TryWithResourceKt.using(TryWithResource.kt:30)
at TryWithResourceKt.main(TryWithResource.kt:75)
Suppressed: java.lang.Exception: exception from ExceptionMaker.ex2
at ExceptionMaker.close(TryWithResource.kt:69)
at TryWithResourceKt.using(TryWithResource.kt:39)
... 1 more
Suppressed: java.lang.Exception: exception from ExceptionMaker.ex1
at ExceptionMaker.close(TryWithResource.kt:69)
at TryWithResourceKt.using(TryWithResource.kt:39)
... 1 more
What do you think?
dimanche 13 mars 2016
magic mouse 2 and mighty mouse
Yesterday I bought a magic mouse 2 because I had a mighty mouse but the scroll was not functioning anymore...
the new mouse is great, but it is not working anymore on my mousepad... The best I found is the put a sheet of paper white on top of my mousepad. Actually it worked great! and it still feels nice.
Furthermore I repaired my mighty mouse by putting few drop of alcool 70°... amazing isn't it?
Cheers,
Sylvain
jeudi 21 janvier 2016
Kotlin
It is a long time I did not blog.... HAPPY NEW YEAR!!! BEST WISHES FOR 2016!
Recently I met Kotlin, a new language running on the JVM.
This new language is just fantastic, I love the extension functions and the not checked exception.
I like Java very much but I found more pleasure with Kotlin.
EDIT: note to JetBrains, please add Kotlin support for JavaFX, and fix the slowness issue with jOOQ, these are the 2 only points holding me to switch completely to kotlin. Actually I have a 3rd point: the try with closable objects, I use for now a kotlin construct "using" that I would prefer to see in the language or in the std lib.
EDIT2: all the points above have been fixed, we can now make controllers in kotlin for javafx, jooq is not longer that slow and the "use{}" is in the standard lib. However I propose another method (in one of my next post) that is more convenient if we have a lot of resources to close in order to avoid many nested .use{}
Cheers,
Sylvain
jeudi 7 août 2014
Create a parser using Lemon with re2c for the lexer
Last time, I explained how to use re2c to create a lexer, now I will present how to combine it with Lemon for the parser.
I wanted first to show it with a more concrete example than a calculator (the famous one), but I swear I tried, but the result is too big and it is not easy to write an simple article, focused on Lemon.
I decided then to continue showing Lemon for a calculator but then writing other article focusing on how to use it especially for more complex grammar like PLSQL.
I encourage you first to read the documentation (short enough) of Lemon... and read it again, and again ... Actually it is well explained but I had personally to read it multiple times. In fact, you need to try a concrete example to understand it (no I didn't say fully :-)).
http://www.hwaci.com/sw/lemon/lemon.html
Lemon is just a C file to compile. very simple, just download lemon.c and lempar.c
http://www.hwaci.com/sw/lemon/
compile lemon simply by:
> clang lemon.c -o lemon
I personally put lemon and lempar.c in my /usr/local/bin, you can actually put it everywhere you want.
see the grammar of the calculator (calc_parser.y):
Lemon is really better than bison or yacc on how to handle variables, I really like to not reference $1 but named variable.
Look at the syntax error, it will show which token was expected if the parsing fails.
(I would have liked a default one like that)
Now, we have to generate the .c and the .h files.
> lemon -m -l calc_parser.y
calc_parser.h:
Also something to know about lemon is that it is a push parser, it will never call the lexer.
lundi 28 juillet 2014
Writing a lexer in C++ using re2c
For the past 2 weeks, during my holidays, I wanted to learn how to write a good parser in C++ but not using flex/bison (they were not generating c++ last time I did look at it, with global variables etc. It might have changed since then).
Anyway, let's go first with the re2c part. The fact that PHP is using it is giving confidence. However as it was not updated since a long time, I just sent an email to the mailing list and I just got a nice answer from a maintainer. 1 week later, the new release went out (0.13.7.3) with UTF-8 and UTF-16 support, just excellent!
I will just focus on using re2c on a string (C null terminated), so I won't show the buffer refill method. It will be probably a topic for another article.
let's now try to make a lexer that identify a number, and some token like +, - and *.
(yes, the famous calculator! but it is just this article, I will go deeper into PL/SQL in the next ones)
so just below our class definition:
#include <iostream>
giving the output:
See you soon!
lundi 12 mai 2014
DBLite has been updated
Today is a big update for DBLite.
I added the savepoint,
fixed a bug in the transaction in the destructor,
introduced the objective c type NSString wherever it made sense (for ios, you need to compile the cpp as objective c++ source file),
added the flags to control the session (readonly, create, readwrite) when opening the database,
and the most important, DBLite is now fully unit tested. I used xcode and it is not yet publicly available but it will be in the next few days.
here the wiki (still not complete, just show the basic, to start)
https://gitorious.org/sylisa-dblite/pages/Home
I wonder if I won't migrate to github, as there is at least a basic issue tracker...
also don't hesitate if you have any feedback, I am all attentive to you.
See you,
Sylvain
vendredi 27 décembre 2013
OpenGL with Eigen: re-implementing perspective and lookat
You can find them in GLM (as functions perspective and lookat)
but I am using Eigen, and after a long reflexion with myself, I decided to stay with Eigen.
I made a version of perspective and lookat for Eigen:
if you are using OpenGL 2.1 then you can use them as:
glLoadMatrixf( projectionMatrix.data() );
Hope it will be useful for you as well, let me know if it was.
:-)
samedi 28 septembre 2013
python install without admin rights
I started recently some programming in python but I needed to install it first on a windows machine without admin rights.... but how to do it, many forums came to the "portable python" and it works, it is just outdated 3.2.x, and as a good programmer (sigh) I wanted to have the latest of course.
The procedure is actually very simple, just download the msi installer from http://www.python.org/getit/ and type the command:
> C:\development\apps>msiexec /a python-3.3.2.msi /qb TARGETDIR=C:\development\apps\python33
then python will be in the directory specified by TARGETDIR.
enjoy python!
but hold on a minute ... what about an editor? komodo-edit for instance?
download http://www.activestate.com/komodo-edit/downloads and type:
> msiexec /a Komodo-Edit-8.5.0-13638.msi /qb TARGETDIR=C:\development\Apps\Komodo-Edit
enjoy python even more!
(as usual, let me know if it has been useful for you.)
dimanche 8 septembre 2013
Apex and CSS
I am working with Oracle / Apex and I had the css using images on a different server. As these links were http and we had to work on https, IE 8 didn't stop to display security message (https security compromised by http calls), so we had to fix the css...
but how? the images should become local in the workspace images but how to reference them?
#WORKSPACE_IMAGES#my_image.jpg
Unfortunately it doesn't work because Apex doesn't make the substitution, but then are we .... stuck?
java -jar cssembed-x.y.z.jar -o output_filename.css input_filename.cssand my css has now the images inlined. just wonderful.
Thanks Nicholas C. Zakas for this great product.
Happy coding.
samedi 8 septembre 2012
using Eigen
Today I took some time to replace my own (vector) math library by Eigen.
This library is great and fast. I could replace my own lib in my software (3d opengl and math calculation) in few hours only.
(I still use the "double" type because it provides better precision and I didn't see any speed improvement using float)
PS: if you see a linkage issue with Eigen and you are using cross or dot, then just include the geometry header: #include <Eigen/Geometry>
Hope it will be useful for you.
Happy coding.
dimanche 12 août 2012
compiling boost with clang mac os x
> ./bootstrap.sh
> ./b2 toolset=clang cxxflags="-stdlib=libc++" linkflags="-stdlib=libc++"
however boost 1.50 has issue with the signal lib,
I downloaded trunk, everything ok so far.
and to install:
> ./b2 toolset=clang cxxflags="-stdlib=libc++" linkflags="-stdlib=libc++" install
enjoy boost.
dimanche 5 août 2012
fastcgi with apache on mac os x lion
First of all, I had many issues with apache to make it running. It does not start well from the preferences. Google it to find some workarounds, but none of them really worked for me.
Even sometimes, it indicates as not running but it is :-/
just few tips about apache on max os x (lion):
> sudo apachectl stop
to stop apache
> sudo apachectl start
to start apache
> sudo apachectl -t
to check what was wrong
> cat /var/log/apache2/error_log
to check the error log
1. First we would need to get the fastcgi library:
http://www.fastcgi.com/dist/fcgi.tar.gz
unzip it somewhere and go the the unzipped folder.
> ./configureas an alternative for clang++ with c++11 and libc++ (with c++11 support)
> make
> sudo make install
> CC="clang" CXX="clang++" CFLAGS="-stdlib=libc++" CXXFLAGS="-stdlib=libc++" ./configure
... easy for now :-)
2. Now we would need the apache module
http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
unzip it somewhere and go the the unzipped folder.
> sudo apxs -n mod_fastcgi -i -a -c mod_fastcgi.c fcgi_buf.c fcgi_config.c fcgi_pm.c fcgi_protocol.c fcgi_util.c
it will compile and install the mod_fastcgi for apache.
3. To Configure apache, let's edit the config file:
> sudo nano /private/etc/apache2/httpd.conf
add the line:
LoadModule fastcgi_module libexec/apache2/mod_fastcgi.so
<IfModule mod_fastcgi.c>
FastCgiIpcDir /tmp/fcgi_ipc/
AddHandler fastcgi-script .fcgi
</IfModule>
> sudo mkdir /tmp/fcgi_ipc
> sudo chmod 777 /tmp/fcgi_ipc
> gcc echo.c -lfcgi -o echo.fcgi
> sudo cp echo.fcgi /Library/WebServer/CGI-Executables/
http://127.0.0.1/cgi-bin/echo.fcgi
lundi 30 juillet 2012
OpenCV and CLang / C++ 2011 on mac os x
OpenCV cannot be used in a project using C++11.
I am on mac os x and the new default compiler is CLang.
The issue is that the stdlib for c++11 is "libc++ with c++11 support" but this is not the default one.
solution: compiling OpenCV with CLang and libc++
so how to do it?
cmake ../ -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_CXX_FLAGS="-stdlib=libc++"
but there is one (small) issue:
OpenCV-2.4.2/modules/ts/include/opencv2/ts/ts_gtest.h uses std:tr1:tuple and it will generate an compiler error.
solution: edit this file and add on the first line:
#define GTEST_USE_OWN_TR1_TUPLE 1
then it will work ! you should be able to use C++2011 in your project using OpenCV on mac os x
BTW my opencv version is 2.4.2
dimanche 18 mars 2012
IE9 slow to startup
I recently installed Win7 64 bits...
and I also upgraded IE8 to IE9.
IE9 was very slow to startup, almost 7 seconds, displaying a blank page.
If you face this case, you just have to "reset" it and then it is fast again!
simple but not quite easy to think about it!
dimanche 29 janvier 2012
webkit Qt or cocoa?
I recently started the native development on mac os x, using objective-C and webkit.
I changed from using QtWebkit for the reason they have deprecated webkit1, moving to webkit2 with a totally different API, also only using QML. QML is still not mature for desktop application, and QtWidget is abandoned. QML is surely great but it is not really proven technology, which makes me reluctant to jump into it. I am then observing where they are going. I hope the best for Qt in general!
Back to Cocoa, I really enjoyed using objective-c and I was amazed how simple and how fast we can progress with webkit, making a bridge with javascript in few seconds. Just amazing!
I also initially thought that Apple missed a language like .NET but I was all wrong! they have objective-C and this is full speed native with C and C++, being also dynamic, what could we ask for more?
just amazing!
Best regards,
Sylvain
mardi 26 juillet 2011
MacOS X Lion and the restore function
I don't know you but I don't like my browser to restore the last opened tabs...
same for preview!
good news, you can revert it.
open the terminal and type:
defaults write com.apple.Safari ApplePersistenceIgnoreState YES
defaults write com.apple.Preview ApplePersistenceIgnoreState YES
and that's like before, the "good old time" :-)




