Blog

My thoughts and experiments.

© 2016. Dmitry Dolgov All rights reserved.

Use an exception instead of the NaN

This is a small notice about a very useful trick. I often have to deal with computations, because the CFD is the part of my activity. And one of the annoying problem in this kind of research is when after many hours of computations you got a Not A Number result, caused by a stupid mistake. It would be nice, if a computation was interrupted by the NaN.

And there is the solution:

#define _GNU_SOURCE
#include <fenv.h>
#include <stdio.h>

int main(void) {
    double x, y, z;
    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);

    x = 0.0;
    y = 0.0;
    z = x / y; /* should cause an FPE */
    printf("result is %f\n", z);
    return 0;
}

The fenv.h header declares a set of functions and macros to access the floating-point environment, along with specific types. According to man:

The feenableexcept() function enable traps for each of the exceptions represented by excepts and return the previous set of enabled exceptions when successful, and -1 otherwise.

Now, what we have without feenableexcept:

$ ./test_no_fenv 
> result is -nan

And with:

$ ./test_fenv 
> fish: Job 1, './test' terminated by signal SIGFPE (Floating point exception)

From bash to fish

I’m doing a small revolution in my environment from time to time. I think “hey, a cool stuff”, take a deep breath and doing something new. And this is story about my migration from the bash to the fish shell.

Let’s see, what says the official tutorial:

fish is a fully-equipped command line shell (like bash or zsh) that is smart and user-friendly. fish supports powerful features like syntax highlighting, autosuggestions, and tab completions that just work, with nothing to learn or configure. If you want to make your command line more productive, more useful, and more fun, without learning a bunch of arcane syntax and configuration options, then fish might be just what you’re looking for!

And this is almost true =) But there is another concrete reason, why I like fish shell:

  • Search by history (as an autocomplete by tab)
  • More intuitive and clean configuration files
  • Vim mode support

I would to avoid unnecessary lyrics, and pay more attention to the configuration and gotchas (from the bash point of view).

First of all - use . command instead source for the inclusion of the script.

. /some-install-path/fish-shell/share/fish/functions/fish_vi_mode.fish
. /some-install-path/.config/fish/themes/fish_right_prompt.fish
. /some-install-path/.config/fish/themes/fish_prompt.fish
. /etc/profile.d/autojump.fish
fish_vi_key_bindings

I’ve used some-install-path because I’m a Vim hacker (an extra pathos), and I want a fresh version for the Vim support, so the manual compilation from github is my way. Then I’ve turned on Vim mode (fish_vi_mode.fish is necessary for this). fish_prompt.fish and fish_right_prompt.fish contain a description for the shell prompt and will be discussed later. If you use autojump, you should also include autojump.fish (if this file doesn’t exist, download it from repo).

set fish_greeting ""

This greeting is very distracting, so disable it. No comments =)

set -x EDITOR vim
set PATH /home/erthalion/.local/bin /usr/local/bin /opt/bin $PATH

We should set environment variables in this format. Pay attention to the PATH variable - don’t forget about /usr/local/bin and /opt/bin (looks like fish shell doesn’t include them by default).

alias goutshow='git fetch; git show origin/master..'

One more observation - we should replace && by the ; or and commands.

Now get closer to the prompt. It described by the two functions - fish_prompt and fish_right_prompt (your C.O.). I have no advices for this section. Really. You can use your imagination and do what you want =) There are my examples - left and right. Only one comment - you may want to show virtualenv name in the prompt. In that case you should disable original by the variable set -x VIRTUAL_ENV_DISABLE_PROMPT 1.

But unfortunately, Vim support isn’t very well in the fish shell. For example, there is no replace (r) command, or undo (u). Actually it’s a horrible problem for me, especially the first one =) And here is my solution of this problem.

I think, fish shell is available for a lot of improvements. All, that described above, is only a base for a convenient environment, and I hope, it will be useful.

Little guide about the gnuchess

I’m at the beginning of my journey into the world of gnuchess. Its interface is a slightly tricky, than I’ve expected, but I was interested. So I’ve decided to make some notes about this.

GNU Chess performs at the senior master/weak international master strength of 2500+ on the Elo rating system

I don’t know, what does this mean really, but sounds cool =)

It is often used in conjunction with a GUI program such as XBoard or glChess

No, it’s not our way. Let’s try to use original teminal-based client (more terminal for the terminal god, mwuahahahaha =).

$ gnuchess

GNU Chess 6.1.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
White (1) : e2e4
TimeLimit[0] = 0
TimeLimit[1] = 0
1. e2e4

black  KQkq  e3
r n b q k b n r 
p p p p p p p p 
. . . . . . . . 
. . . . . . . . 
. . . . P . . . 
. . . . . . . . 
P P P P . P P P 
R N B Q K B N R 
 
Thinking...

white  KQkq
r n b q k b . r 
p p p p p p p p 
. . . . . n . . 
. . . . . . . . 
. . . . P . . . 
. . . . . . . . 
P P P P . P P P 
R N B Q K B N R

Gnuchess uses the standard algebraic notation (SAN) required by FIDE, so we can type something like this to play:

Nf3
g1f3
O-O
e1g1

Ok. But what is it? Gnuchess uses the most of the CPU all time, even at the player’s move. It’s super, but it would be more convenient to limit the thinking time for gnuchess engine. In the documentation we can see, that the --easy options is responsible for this.

–easy, -e: Disable thinking in opponent’s time. By default, the program runs in hard mode, i.e. it thinks opponent’s time to think too.

Now better. But how we can pause the game and continue later? There are an obvious commands for this: save and load, which save the game position into EPD format

White (2) : save game_file
TimeLimit[0] = 0
TimeLimit[1] = 0
White (2) : load game_file
TimeLimit[0] = 0
TimeLimit[1] = 0

 : Best move = 1

white  KQkq
r n b q k b . r 
p p p p p p p p 
. . . . . n . . 
. . . . . . . . 
. . . . P . . . 
. . . . . . . . 
P P P P . P P P 
R N B Q K B N R 
 
White (1) : 

And little bit about usability - we can use the pseudo graphical mode (a unicode symbols will be used for output), but … it looks ugly. Classical mode provides convenient enouth game, except the board’s coordinates. To avoid this inconvenience, we can use the patch below:

$ gnuchess -e
GNU Chess 6.1.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
White (1) : e2e4
TimeLimit[0] = 0
TimeLimit[1] = 0
1. e2e4

black  KQkq  e3

8  r n b q k b n r 
7  p p p p p p p p 
6  . . . . . . . . 
5  . . . . . . . . 
4  . . . . P . . . 
3  . . . . . . . . 
2  P P P P . P P P 
1  R N B Q K B N R 
  
   a b c d e f g h 

Thinking...

white  KQkq

8  r n b q k b . r 
7  p p p p p p p p 
6  . . . . . n . . 
5  . . . . . . . . 
4  . . . . P . . . 
3  . . . . . . . . 
2  P P P P . P P P 
1  R N B Q K B N R 
  
   a b c d e f g h 


My move is : Nf6
White (2) : 

Have a nice game!

Another strange thing - an endless paginator

A little bit about my new program-frankenstein. Now it is an endless Paginator for Django. It sounds crazy, isn’t?

Standart Django Paginator uses the count() function for the verification of page number. It is converted to the SELECT COUNT(*) ... query, of course. But as I was explained (I really don’t know, maybe it’s just an exaggeration - you can post your opinion in the commentaries), this is not a such lightweight query, as we want for the paginated rest api, because of the MVCC in PostgreSQL.

How we can avoid the extra COUNT(*) query? Don’t panic, we can trick the Django.

First of all we need to disable count parameter from the api response. We can introduce a custom pagination serializer:

# serializers.py
class CustomPaginationSerializer(BasePaginationSerializer):
    next = NextPageField(source='*')
    previous = PreviousPageField(source='*')

# api.py
class SomeListView(generics.ListAPIView):
    model = SomeModel
    serializer_class = SomeSerializerClass
    pagination_serializer_class = CustomPaginationSerializer

The next our move - disable the page number verification. This can be done by the custom paginator class:

class CustomPaginator(Paginator):
    """ HACK: To avoid unneseccary `SELECT COUNT(*) ...`
        paginator has an infinity page number and a count of elements.
    """
    def _get_num_pages(self):
        """
        Returns the total number of pages.
        """
        return float('inf')

    num_pages = property(_get_num_pages)

    def _get_count(self):
        """
        Returns the total number of objects, across all pages.
        """
        return float('inf')

    count = property(_get_count)

    def _get_page(self, *args, **kwargs):
        return CustomPage(*args, **kwargs)


class SomeListView(generics.ListAPIView):
    model = SomeModel
    serializer_class = SomeSerializerClass
    pagination_serializer_class = CustomPaginationSerializer
    paginator_class = CustomPaginator

Oh, goodness - we introduced the infinity number of the pages and the infinity number of elements… But we want also the correct next/prev links, so one more detail:

class CustomPage(Page):
    def has_next(self):
        """ HACK: Select object_list + 1 element
            to verify next page existense.
        """
        low = self.object_list.query.__dict__['low_mark']
        high = self.object_list.query.__dict__['high_mark']
        self.object_list.query.clear_limits()
        self.object_list.query.set_limits(low=low, high=high+1)

        try:
            # len is used only for small portions of data (one page)
            if len(self.object_list) <= self.paginator.per_page:
                return False

            return True
        finally:
            # restore initial object_list count
            self.object_list = self.object_list[:(high-low)]

This solution looks very questionable, but exciting for me. If you have something to say about this - welcome! =)