понедельник, 25 декабря 2017 г.

Prolog ideas

Here is my list of Prolog ideas:

  1. JSON parser
  2. HTTP requests parser
  3. Declarative UI
  4. Validation rules for UI
  5. Business logic in C\C++\Java
The idea of declarative UI I borrowed from the Turbo Prolog 2 User guide and Turbo Prolog Toolbox. It could be useful to have some intermediate UI form representation  in order to be able to translate it into different languages.

As for the last topic it turned out to be easy embed tuProlog in Java. And I had a prototype where I call java methods from Prolog.

The later topics need to be researched further.

Turbo Prolog 2.0. Changes from 1.x.

 Turbo Prolog 2.0 change list

- external database support with protected memory access

- BGI interface support

- improved text editor

- ability to save trace to file

- integers overflow check

- stack check

- error level

- ability to call prolog predicates from Turbo C

- conditional compilation support  (ifdef, ifndef, elsedef, enddef)

- standart trap predicate

- build with Turbo C 1.5

четверг, 21 декабря 2017 г.

W.F. Clocksin, C.S. Mellish. Programming in Prolog

Hi everyone.

I have just read "Programming in Prolog" and wonder why this book is recommended for beginners?

The most useful tip in this book is located at the end of it in appendix C:
This book describes Prolog version which is not related to any particular existing version. The idea was to create the description of "general" Prolog which applies to all systems at once.
 The best way to learn Prolog system you have -- is to read user documentation supplied with it.

Wow! Such a wonderful advise. Why I have to read all the book till the end in order to find out this?
Beginners  will suffer a lot and will complain about Prolog. This shouldn't be like this.

Please treat the book as an approach to explain ideas behind Prolog, not a tutorial.

пятница, 24 ноября 2017 г.

Adventure in Prolog

Ever wanted to learn logic programming?
Wanna know how to program in Prolog?

Wanna know how to integrate Java with Prolog?

A lot of questions arise when we face with a "new" language such as Prolog.
After Java, Prolog looks like a fresh air. It has simple syntax, small number of concepts comparing to the OOP. For me the main advantage that it is a declarative language, not imperative.

If you deal a lot with business rules in your programs you know how ugly imperative implementations look like. This could be the opportunity for Prolog and constantly changing business world.

A lot of information exist about Prolog. What to start with?
IMHO Adventure in Prolog could be a good introduction to Prolog. All concepts are introduced and presented with examples and small tasks.

Examples could be run on almost any Edinburgh compatible Prolog. I use tuProlog. It runs on top of the JVM. Also it has a simple IDE, so you can just move straight to executing your code.

I also started a new repo on https://github.com/chernykhalexander/PrologExperiments for Prolog experiments.

четверг, 5 октября 2017 г.

Blog promotion

Hi everyone!

It is been a while since I wrote here. But in order to give some excuse I would like to present you the blog of a programmer:  http://www.yegor256.com/.

Why do I post it here? Well, I like that this man has his own opinion and he express it. A lot of computer topics are described - not only programming techniques, but management also. What is more - his opinion could be against with what everyone silently agree on. I like it. The more different angles of view we have at the topic the faster we can improve ourselves.

The same thing could be applied to the project. I do not like when everyone is silently agreed on something in a project. If all the team is agreed on it means that either no one doesn't care about the project or there is no atmosphere where each member can express their opinion safely.

Let's improve our projects.

среда, 30 августа 2017 г.

My top Android applications



I was disappointed that Microsoft doesn't produce windows phones any more and Nokia was sold. I have bought recently an Android phone Motorola Moto G4 plus and discovered Android and Play market.

Android seems to be very attractive and positive. I use version 7. I like fingerprint authentication very much. But... Why by default a lot of settings are turned on considering information sharing and statistics gathering? I need to go through  the settings of Android and apps and turn off spy features.

Play contains a lot of apps but a lot of them are a crap. I have also a concern why actually some applications asks for a permissions not related with a purpose of application? That is why it is better not to install the application but instead use web site.

But anyway I decided to create my own top of applications I use.

Productivity and entertainment:

  1. Skype
  2. Whatsapp
  3. Google Chrome
  4. Google Gmail
  5. Google Maps
  6. Google YouTube
  7. Google Photos
  8. Google Calendar
  9. Google Translate
  10. RAR
  11. micro Mathematics
  12. TuneIn Radio 
  13. Aviasales
  14. Gazeta.ru
  15. Moto File Manager
  16. Pocketbook
  17. FM Radio
Technical apps:
  1. Speedtest
  2. CPU-Z
What are your favorite apps on Android?

понедельник, 17 июля 2017 г.

How to generate Sprint Boot project

Each time you need to create the Spring Boot project you start to search for your previous projects and copy paste the needed files. This is tiresome and error prone. Here is the solution: https://start.spring.io/. On this site one can just choose the necessary Spring Boot modules and generate the project with a click of a button. You then can just open up the generated project in IDE and start coding. :-)

суббота, 15 июля 2017 г.

Vsevolod Dyomkin. Lisp Hackers. Interviews with 100x More Productive Programmers.

Fantastic book. Can be found online at http://leanpub.com/lisphackers. It is a collection of interviews with 14 developers who use Lisp in real life.
After reading this book I have a new look into Lisp. I need to look at it more closely. :-)
It's disadvantages:
  1. lack of static typing
  2. difficult to work with in a big projects code bases (around 500 kloc)
Advantages:
  1. DSL support
  2. protocols
  3. ability to run partial programs
  4. Having fun
  5. extend your mind 
  6. can be used in projects where customer doesn't care about the tools but getting job done.
Productivity tips:
  1. Start from minimal running code and move forward in a long series of very small steps.
  2. Learn new languages  to meet new people, to think in a new way.

четверг, 1 июня 2017 г.

Java 8 WatchService. Windows Implementation note.

WatchService in java is service that allows to monitor the directory for changes. Here is the important notice from javadoc:
"For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted. "

But what if you need to know  which file was actually renamed. What is the old name of a file and what is the new name?

On windows there is a native support from the OS to monitor such changes. Well, take a look how this possibilities were mapped in Java. For jdk8 see the link http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/classes/sun/nio/fs/WindowsWatchService.java#l464. For lazy ones here is the method:
<code>
// Translate file change action into watch event
        private WatchEvent.Kind<?> translateActionToEvent(int action)
        {
            switch (action) {
                case FILE_ACTION_MODIFIED :
                    return StandardWatchEventKinds.ENTRY_MODIFY;

                case FILE_ACTION_ADDED :
                case FILE_ACTION_RENAMED_NEW_NAME :
                    return StandardWatchEventKinds.ENTRY_CREATE;

                case FILE_ACTION_REMOVED :
                case FILE_ACTION_RENAMED_OLD_NAME :
                    return StandardWatchEventKinds.ENTRY_DELETE;

                default :
                    return null;  // action not recognized
            }
        }
</code>

You see, renamed and new file events mapped to ENTRY_CREATE event. The only question comes to my mind is -- why? Why it was done like this?
I think they were trying to make a universal solution, but.. why they didn't make it extensible?

суббота, 13 мая 2017 г.

n queens puzzle

Hi! I was getting bored and started to think about algorithms.
Here is a solution to the 8 queen problem. Code is on github: https://github.com/chernykhalexander/puzzles/blob/master/src/test/java/ru/chernykh/queen/QueenTest.java.

Thanks!

среда, 10 мая 2017 г.

VirtualBox. Mount Windows shared folder in Linux guest

Small snippet how to mount a windows shared folder in linux guest in VirtualBox:
mount -t vboxsf share ~/host

where host is the mount point in linux guest and share is the name of the shared folder defined in VirtualBox.

суббота, 4 марта 2017 г.

Make screenshot with Java

It turns out that making screenshot of the monitor is very easy task.
It even works with dual monitor configurations.
Code is on github: https://github.com/chernykhalexander/screenshot.

вторник, 28 февраля 2017 г.

Java 8. Object.hashCode default implementation

Usually it is considered that default Object.hashCode and System.identityHashCode are calculated as value converted of object address to int. But this is not a strict rule. In fact in JVM8 there are possibilities to choose the implementation of Object.hashCode with option -XX:hashCode=0..5. The list of functions can be found at http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/tip/src/share/vm/runtime/synchronizer.cpp in method get_next_hash. Here is the list of possible values:

0 - unguarded global Park-Miller RNG;
1 - function on bits;
2 - constant 1;
3 - sequence number;
4 - object address;
5 - Marsaglia's xor-shift scheme with thread-specific state.

In JVM 8  by default is used Margalia's xor-shift option. See http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/share/vm/runtime/globals.hpp and line:
product(intx, hashCode, 5,"(Unstable) select hashCode generation algorithm").       


суббота, 18 февраля 2017 г.

Java 8: Integer

Everyone knows that Java has boxing functionality:
 Integer one = 4;
 Integer two = 4;
 Assert.assertTrue(one==two);

 Integer $600 = 600;
 Integer also600 = 600;
 Assert.assertTrue($600 != also600);


It works as written in JLS (http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7).
This is due to the caching functionality inside the Integer class and the method Integer.valueOf which is used by boxing.

What's more we can make the second test pass. Cache inside Integer can be tuned by passing  system property -Djava.lang.Integer.IntegerCache.high=600 to the JVM. The bad thing is that low bound of Integer cache cannot be tuned.

Another example is:
 Integer $4 = new Integer(4);
 Integer $anotherInstance = 4;
 Assert.assertTrue($anotherInstance!=$4);

This is because new Integer(4) bypasses the cache.  Why? Is it a good design?
Is it the premature optimization evil?
Interesting case that other wrapper classes also contain the caching functionality, but only Integer class has the possibility to tune the size of the cache.

One more thing: do we actually need Integer constructor which accepts String if the same goal can be achieved with Integer.valueOf method?

вторник, 14 февраля 2017 г.

Java StringBuilder and StringBuffer

As to know more about the implementation of the JVM I started to look at the java source code. StringBuilder and StringBuffer are two pretty often used classes.
Documentation says that it is recommended to use StringBuilder class as it will be faster under most implementations. But.. documentation does not say about possible performance gains.
I wrote a quick check for appending String and char for both classes.
For the tests I used Oracle JDK 1.8.0b51.  Here is the sample code:
    @Test
    public void stringBufferTest(){
        Eap.execute(()->{
            StringBuffer stringBuffer = new StringBuffer();
            String a = "a";
            for (int i = 0; i< $256_MEGABYTES; i++){
                stringBuffer.append(a);
            }
        });
    }
    @Test
    public void stringBuilderTest(){
        Eap.execute(()->{
            StringBuilder stringBuilder = new StringBuilder();
            String b = "b";
            for (int i = 0; i< $256_MEGABYTES; i++){
                stringBuilder.append(b);
            }

        });
    }

And results:
Time is: 9,105000 seconds
Time is: 3,220000 seconds

Absolute numbers tell nothing, so StringBuilder is almost 2.8 faster then StringBuffer. 

For chars I just substitute String a = "a" to char a = 'a' and String b = "b" to char b = 'b'.

In case of char appending we get following results:
Time is: 8,623000 seconds
Time is: 1,221000 seconds
So StringBuilder is almost 7 times faster then StringBuffer. 

Although these results were obtained on relatively long strings it is much more clear now which class to use in your application (depending on the requirements of course). Interesting fact is that both StringBuffer and StringBuilder extend from AbstractStringBuilder.

A couple of questions to the internal design of these classes:
1) both of them expose internal capacity, which is 16 by default. Why it is 16? What is this magic number for?
2) Overloaded constructors with different semantics. So, one constructor accepts capacity and another one accepts string.
3) Both classes provide methods capacity() and length(). Both of them return data. Why didn't they call them with get prefix like getCapacity() and getLength()?

воскресенье, 12 февраля 2017 г.

Validate XML by XSD with includes from classpath

Validation of XML files is usually a standard task.
It is very convenient to store XSDs in classpath and validate XML in a such way.
Problems starts when XSD contains imports of other schemas. Schema parser doesn't know how to resolve the location of imports. There is no out of box solution to this problem.

I created a sample project that solves this task: 
https://github.com/chernykhalexander/xsdValidator

среда, 25 января 2017 г.

Java 8. Execute Around Method pattern.

After reading Venkat Subramaniam book on Java 8 I was impressed with Execute Around Method pattern.
Execute Around Method pattern is useful when the pre- and post-operations have to be guaranteed and the usage of the instance has to be rather narrow and enforced.
Here is the example:
package ru.chernykh.java8;

import java.util.function.Consumer;
public class UsefulResource {
    private UsefulResource() {
        System.out.println("Instantiate resource");
    }
    private void close() {
        System.out.println("close resource");
    }
    public void operator(){
        System.out.println("execute logic");
    }
    public static void process(Consumer<UsefulResource> block) {
        UsefulResource usefulResource = new UsefulResource();
        try {
            block.accept(usefulResource);
        } finally {
            usefulResource.close();
        }
    }

    public static void main(String[] args) {
        UsefulResource.process(usefulResource -> {
            usefulResource.operator();
        });
    }
}


And the output is:
Instantiate resource
execute logic
close resource


Also, more information can be found in his publication at http://www.oracle.com/technetwork/articles/java/architect-10things-2266262.html.