Sunday, November 08, 2015

Scrolling terrain map with wrap around

I started to work on a clone of the classic game Lunar Lander (see my GitHub repo). The reason I work on games is not that I want to be a game programmer but because there are lots of challenges that help becoming a better software developer and it is more fun coding games, i.e. it is more probable that I will keep my motivation and have a working prototype in the end.

Friday, October 09, 2015

Exception handling in Thread and SwingWorker

Exception handling in SwingWorker differs from Thread. When using a Thread if an exception is thrown inside run(), it is propagated up the chain and you can handle it outside if you want. When an exception occurs in SwingWorker.doInBackground(), you have to handle it in the done() method. The following code demonstrates this. If you delete the done() method, it will run but the exception will be lost.
/**
 * Demonstrates difference of SwingWorker and Thread when an exception occurs. In SwingWorker, if you don't catch the exception in done(), it gets lost.
 */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Thread.run");
            throw new IllegalArgumentException();
        }
    }).start();

    new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("SwingWorker.doInBackground");
            if (true) {
                throw new IllegalArgumentException();
            }
            return null;
        }
        @Override
        protected void done() {
            try {
                get();
            } catch (InterruptedException e) {
                System.out.println("Caught exception: " + e);
            } catch (ExecutionException e) {
                System.out.println("Caught exception: " + e);
            }
        }
    }.execute();
}

Output:
For more information see How should I handle exceptions when using SwingWorker?

Tuesday, October 06, 2015

Less Medicine, More Health

Less Medicine, More Health was especially relevant to me because my mother (65 years old) underwent colonoscopy as part of a routine control in which the doctor removed a few polyps and one of them had cancer cells close to the colon wall. Three out of four doctors said that she must have an operation which would remove a quarter of her colon (without saying anything about the risks of the operation). Only one doctor pointed out that may be all the cancer cells were taken out during the polyp removal, the risks and probability of success of the operation (which were horrible numbers). In the end my mother reasoned that the operation was not worth it. This was 6 months ago. Today she is alive and well, tending her garden.

Almost everybody has some sort of abnormality that won't hurt him but becomes a problem due to early diagnosis, i.e. you would be better of if did not perform the checks in the first place. Lesson: Don't do full checkups, only deal with things that you have symptoms of.

It shows the importance of randomization and biases that can be overlooked when performing medical trials, for example a trial based on volunteers can be biased because health conscious individuals are healthier than the average.

Thursday, September 17, 2015

Scrolling vs. Navigating in JTabbedPane

It is possible to programatically move between the tabs of a JTabbedPane:

There are two mechanisms: Navigating and scrolling. Their difference is that navigation changes the selected tab while scrolling shifts the view but does not change the selected tab.

Monday, August 31, 2015

Working with a junior developer

When I (a senior developer) have to supervise someone new (a junior developer) - who can be a new employee or an intern - I use the following steps to get the junior up to speed without taking too much of my time:

Note how it starts with an informal discussion of the problem to be solved. I sit down with the junior, tell him what I know about the problem, draw some sketches on a white board. The critical step is to let him write a problem definition document that repeats what we have talked about. When I review the document, I can verify that the junior has understood the problem well. This pattern repeats with design and test documents. It reduces my burden of supervision (I don't have to write anything) and helps the senior to really understand - not just "hear" - the problem. And last but not least, we get good documentation. Win-win...

Monday, August 24, 2015

Strategy pattern for modularization

When your software exceeds a certain size, it's a good idea to separate it into modules that can be compiled and tested independently (for example, it is easier to isolate memory leak causes). Some modules might also have value as standalone components.


Wednesday, August 12, 2015

The International Bank of Bob

The International Bank of Bob explains how the microlending platform Kiva works by visiting the recipients of such lends around the world.

I find Kiva convenient for two reasons: It makes it very easy to find someone who could really use financial help and it is as transparent as it gets.

Before thinking about the details of microlending and Kiva you have to ask yourself "do I really care about the plight of others so much that I can part with my $25?" You have to give an honest "yes" before coming up with questions about how reliable/efficient Kiva is. I suspect most of such questions stem from not being that committed to helping others but being ashamed to admit it and instead formulating more rational sounding questions. After you gave that first "Yes", read this book. In the words of Bob, "Pretty much the only things we do get to choose are how we treat others and conduct ourselves in the world. Are we honest? Are we caring? That’s who we are."

Kiva team: Friends of Bob Harris

Kiva fellows blog

Tuesday, August 11, 2015

Thinking Fast and Slow

Thinking Fast and Slow shows how hard it is to think and how often people avoid it and makes me wonder if anything I know is truly correct. "Considering how little we know, the confidence we have in our beliefs is preposterous".

It is depressing to realize the difficulty of changing our own faulty ideas, let alone changing others. To help myself, I read books like this one. When arguing with stubborn people who are not interested in the truth, I don't bother with being fair because they never return the favor. I just silence them with a few simple tactics so that they don't think that what they present is irrefutable brilliance. Schopenhauer's "Die Kunst, Recht zu behalten" has good techniques.

Thinking as correctly as possible is not some academic detail. I recently had to confront two important, life-changing challenges: One was which house to buy and the other was whether my mother should have a risky operation. With rationality and luck, both turned out very well (We bought the best house possible and my mother rejected the operation which in hindsight was a good decision).

Another application of this book might be using it when raising a child (I have a 3 year old son). The hard way is to use rationality and correctness of argument. The easy way would be to appeal to the inherent weaknesses present in every human being [as politicians and marketers do].

The moral of the story is: be aware of your limitations (this book is for that) and think... a lot!

Saturday, August 08, 2015

The Honest Truth About Dishonesty

The Honest Truth About Dishonesty shows how people rationalize their dishonest actions and what factors increase or decrease dishonesty. Why should you read it? In the words of the author "recognizing our shortcomings is a crucial first step on the path to making better decisions, creating better societies, and fixing our institutions."

Wednesday, August 05, 2015

The Making of the Atomic Bomb

The Making of the Atomic Bomb provides the background of scientific progress and WWII thinking that lead to nuclear weapons.

The 1986 edition that I read has a nice epilogue (40 pages long) which is missing in 2012. That's a huge loss in content because the epilogue has interesting content.

The book is
  • Fun: Example: comparing Chadwick's temperament with the properties of the neutron he discovered.
  • Informative: How much thought and hard work is invested into and how many small and large difficulties have to be surmounted before a scientific discovery, how good theory is needed to both design a proper experiment and correctly interpret its results (How the Curies were not able to discover the neutron even though they did the experiment first). How scientific openness in the early 1900s led to rapid progress.
  • Inspiring: Kindled my interest in Chemistry (Otto Hahn, discoverer of nuclear fission was a chemist). How scientific openness could be a model for government of humanity (Niels Bohr's hope). For me, the book shows what good science and engineering is, with nuclear weapon development as a case study. Any technically inclined person would enjoy this book a lot and be motivated to do some science (hopefully for peaceful purposes).
  • Horrifying: Effects of a nuclear weapon on its victims is described in graphic detail. The risk of an accidental or terrorist nuclear war is unacceptably large and the results of a wide scale war would be the end of intelligent life on Earth.

Monday, August 03, 2015

iWoz: Computer Geek to Cult Icon

"iWoz: Computer Geek to Cult Icon", by Steve Wozniak with Gina Smith, is the autobiography of Steve Wozniak. I only knew little about him, like he was the other Steve who got Apple started. After reading this book, I admire him as a person and can relate to him a lot (I myself am a software developer), especially the portions about having an open mind, not trusting authorities and trying to build a better/just world. It also gave me ideas about how to spark interest in my 3 year old son.

Tuesday, July 28, 2015

The Fall of the Ottomans

The Fall of the Ottomans by Eugene Rogan details the events on the Ottoman front during the First World War. I came to realize how complex the events were and that it would be very difficult to behave in any other way. It is a saddening and sobering read that helps in getting rid of the propagandist tales simplifying history to such a degree that the only explanations left are treason, stupidity and barbarism of the enemy.

Wednesday, July 15, 2015

Model-View-Controller

When applying the MVC pattern, I make the graphical components in the View class private so that there is no possibility of using them directly from the Controller. This enhances information hiding/encapsulation (i.e. knowing only the minimum about another class) and modularity.

Let's say that you have a View with an input text field, a button to add 10 to the input value and an output text field to display the result:

The Controller should not directly access the text field to get the value. Instead, the View class should have a get method which the controller should call. The same applies for output. After the model has finished calculations, Controller should get the output from Model and set it to the view using a set method without directly accessing a graphical component.
public class Controller {
    public static void start() {
        Model model = new Model();
        View view = new View();
        ActionListener add10ActionListener = (ActionEvent evt) -> {
            int input = view.getInput();
            int output = model.add10(input);
            view.setOutput(output);
        };
        view.setAdd10Action(add10ActionListener);
        view.setVisible(true);
    }
    
    public static void main(String[] args) {
        Controller.start();
    }
}
public class View extends javax.swing.JFrame {
    public int getInput() {
        return Integer.parseInt(jtfInput.getText());
    }
    
    void setOutput(int output) {
        jtfOutput.setText(String.valueOf(output));
    }

    void setAdd10Action(ActionListener add10ActionListener) {
        jbAdd10.addActionListener(add10ActionListener);
    }
...
public class Model {
    public int add10(int input) {
        return input + 10;
    }
}
I think of the Controller as the boss, i.e. the class that assigns event handlers and knows the order of steps. The Model contains algorithm implementations and the View is reponsible for graphical input/output.

When you must access the view over the network (e.g. view is on a different machine), then you obviously cannot call methods of view from controller which means taht you cannot set listeners. In that case you send all state data (e.g. mouse up/down, mouse position) as JSON from view to controller, you parse the data in controller and perform appropriate actions and send data back to view.

Friday, May 08, 2015

Self learning update for May 2015

See my autodidact post for an introduction of what this is about.

04 May 2015: Took one week off to port my Java game to Android (50% of my time), hobby electronics (25% of my time) and German improvement (25% of my time). I started with Developing Android Apps course but made no progress due to technical difficulties:
  • Android Studio is painfully slow on my laptop, Samsung ATIV Book 9 Lite (NP905S3G). Specs: Windows 8.1, Quad Core 1GHz, 4GB RAM, 40GB free disk space.
  • When I tried to use the emulator, I got "ERROR: x86 emulation currently requires hardware acceleration". Tried to install Intel HAXM, got "Computer does not support Intel Virtualization Technology (VT-x)". Checked BIOS, VT-x was enabled. 
  • Plugged in my Nexus 10, Android Studio did not recognize it.
  • I don't know what else to do.
05 May 2015: Tried my luck again with Android Studio, still no progress. Started watching  Android Development for Beginners which explains MIT App Inventor 2.

06 May 2015: Started using KanbanFlow.
Android: Android Studio emulator still not working, still not recognizing Nexus 10. Tried to build unsigned apk, success! Realized that my laptop does not recognize my Nexus 10. Installed universal adb driver, disabled USB debugging on Nexus, success. Copied apk to Nexus via USB, install, success. I still cannot see my real Nexus 10 on Android Studio. I might need a better computer. Main source of video lectures: Android Studio Tutorial by Derek Banas.
German: Two practices on Duolingo (20XP)
Electronics: Managed to control a DC motor.

07 May 2015:
Android: Wrote an app that counts from 0 to 9 with 500ms delay. I first tried Thread (which is usual for desktop Java apps), but Nexus said "the application stopped". Then I used postDelayed and finally it worked. This means that my existing Java library knowledge is not of much use, I have to learn new libraries. My tiring workflow was (without any debugging capability):
  1. Work in 25 minute blocks.
  2. Build app (~2min the first time, ~30s afterwards)
  3. Copy apk_debug.apk to Nexus.
  4. On Nexus install apk_debug.apk.
  5. Run apk_debug.apk.
  6. Repeat until you get what you want. 
German: 20 XP
Electronics: Get data from two photoresistors, drive servo motor. Problem: Humming in servo motor, sounds like instability.
Book review: Started working on Capital.

08 May 2015:
Book review: Finished Capital. Total pomodoros: 5
German: 30 XP
Electronics: Investigate servo humming

Book: Capital in the Twenty-First Century

"Capital in the Twenty-First Century", Thomas Piketty

This is a 500+ pages book. The first 200 pages were full of very similar looking data and tables. It became interesting after page 200, and riveting after page 300. I like books that show how ignorant I am and this is definitely one of them.

Read it if the following questions are of interest to you:
  • What is the source of income inequality and how does it harm society?
  • How should the income from production be divided between labor and capital?
  • Why is it so difficult to tax the super rich and multinational corporations?
  • Is publicly available financial information enough to form a healthy opinion about financial matters?
Update, January 11th 2016: Paul Graham says that we should not attack inequality (which is an indirect effect), but directly poverty and the questionable ways of getting rich:

Tuesday, May 05, 2015

WinDirStat

WinDirStat is a disk usage statistics viewer and cleanup tool for various versions of Microsoft Windows. I used it to clean up my laptop.

Sunday, April 19, 2015

Book: How The World Works

"How The World Works" - Noam Chomsky, 2011, 335 pages

The book contains collections of interviews with Noam Chomsky. It is a good summary and I would strongly advise it to anyone interested in why the world is as it is and wants to lift the curtain of lies. An essential guide in search of the truth...

Friday, April 17, 2015

İnternet alışverişinde durum

Uzun zamandır aklımda olan hobi elektroniğine başladım ve bu hafta direnc.net'ten ilk siparişimi verdim. Bu yazıda siparişle ilgili tecrübelerimi aktaracağım.

Önce iyiden başlayalım: Memlekette online elektronik bileşen alabileceğim bir site olması büyük lütuf, Ulus'a gitmem gerekmiyor.

Sorunlar:
  1. Sitede parçalar hakkında çok az bilgi var, genellikle düşük çözünürlüklü fotoğraftan başka bir şey yok (Örnek: Zener Diyot Paketi). Ben ayrıntılı bilgi içeren yabancı sitelerden neye ihtiyacım olduğunu tespit edip öyle sipariş veriyorum.
  2. Pek çok irili ufaklı parçadan oluşan siparişimi P.tesi verdim, kargoya Perşembe günü verdiler. Kargoya verdiklerinde mail atmadılar. Kendi sayfalarındaki hesabıma girince görebildim. Kargo firması olarak Yurtiçi Kargo yazılıydı, takip numarası yoktu.
  3. Cuma günü MNG kargodan aradılar, paketim olduğunu, "şubeden alınacak" olarak işaretlendiğini söylediler. Önce yanlış aradıklarını düşündüm çünkü siparişimde firma olarak Yurtiçi Kargo'yu işaretlemiştim. Sonra paketi kimin yolladığını sordum, İnt-El (direnc.net'in şirketi) olduğunu öğrenince paketi iş yerine yollamalarını söyledim.
  4. Güncelleme 24 Nisan 2015: İkinci siparişimi verdim, siparişimde orjinal Arduino Starter Kit olduğu halde klonunu koymuşlar, neyse ki telefonla arayıp bilgi verdiler, ben de en azından içindeki işlemci kartını orjinal Arduino ile değiştirmelerini istedim.
  5. Güncelleme 27 Nisan 2015: MNG kargodan "kargonuz şubemize ulaşmıştır" diye SMS mesajı geldi, şubeyi aradım, "şubeden alınacak" olarak işaretlendiğini söylediler, iş yerine yollamalarını istedim. Bu artık bardağı taşıran son damla oldu, direnc.net ile işim bitti, bu yazıyı okuyanlara da uzak durmalarını tavsiye ediyorum. Bir dahaki sefere Robotistan vb. alternatifleri deneyeceğim.
Basit adımların bir türlü tam olarak yapılamadığı örneklerle dolu yurdum internet alışveriş/bankacılık siteleri. İş kurmak isteyenlerin öyle orjinal fikirler peşinde koşmasına gerek yok, mevcut işlerin hepsinde ciddi sorunlar var. Steve Yegge abimizin de dediği gibi:
It's easy to come up with new product ideas if you start with the understanding that everything sucks. Everything can stand improvement. Just think about what you'd change if you were doing it for yourself, and everything should start falling into place.
Kritik husus gerekli bağlantılara sahip olmak, o da sosyal becerileri geliştirmekle ilgili ve uzun zaman alıyor. Teknik insanlar için sosyal beceri ipuçları içeren faydalı bir site: simple programmer.

Friday, February 13, 2015

Book: The E-Myth Revisited

The E-Myth Revisited, Gerber, E. Michael.

It is a too verbose text for my tastes, so I will summarize it for you:

People usually start a business with a technician mindset but a successful business requires balanced entrepreneur, manager and technician roles.
  • Entrepreneur: What do people need? How much would they pay for it? How will they know about my product (marketing)? What is my future vision for the company and myself?
  • Manager: Provide structure (processes, manuals etc.) to the organization.
  • Technician: Check technical feasibility of product ideas, build products.
Each role requires the same amount of time and attention. The main reason for business failures is that their founder is not aware of this and is stuck in one (usually technician) role.

Tuesday, February 10, 2015

Notes about A*

A* (AStar) is a relatively easy to implement pathfinding algorithm. There are good resources that explain the algorithm, so I won't go into detail here:
I find the following particulary interesting:
  • Closed list does not mean pure path list. It contains the path nodes and all the nodes that were considered as path nodes some of which not being on final path.
  • Once the end node is reached, path is constructed by starting from end node and going backwards to parent nodes until start node is reached, i.e. until parent node == null.
  • If open list becomes empty (i.e. no more nodes left to consider) before end node is reached, it means there is no path from start to end.
  • Switch parent according to G cost.
  • If h is admissable (i.e. if h >= hOptimal), A* will find shortest path.

Saturday, January 31, 2015

Book: The Inner Game of Tennis

The Inner Game of Tennis by W. Timothy Gallwey argues that success can result only if you don't try too hard which sounds counter intuitive. Trying too hard means becoming emotionally attached and being judgmental. He gives practical tips on how to achieve relaxation while practicing. First and foremost, you have to be interested in what you are doing.

A very good book for anyone who wants to be a better person by using tennis (or any other practice) as a means to achieve inner peace and perfection.

Thursday, January 15, 2015

Minimal Software Design

A minimal software design effort should include the following:
  • What problem are you trying to solve? Is the problem specified clearly?
  • Comprehensibility: What will you do to help others (or yourself one year later) understand your code/design. Hint: Wiki, coding conventions, KISS.
  • Modularity/dependency: What approach will you take to make your modules independent? Hint: Encapsulation, MVC pattern.
  • Testability: How will you make sure that your implentation will be as unit testable as possible? Hint: Keep methods short. Whenever you can, make objects/methods static.
  • Error handling and logging: What error cases do you foresee and what mechanisms will you have in place to log and recover from errors? Hint: Exceptions.