Thursday, February 20, 2020

C: Have fun compiling

When I write some small C program I usually put everything in a single main.c file and to compile I just:

gcc -O3 main.c -o program_name_here

I will use the catimage program which reads an image and prints it in the terminal.

Now lets be civil and put the compile command into a Makefile:

catimage:
    gcc -O3 -lm main.c -o catimage

I also like to run a recompile on file change loop:

echo main.c | entr make

Now, a dependency. To read the images I use the stb_image, which is an awesome lib so they only I need is a single "header" file stb_image.h and two # lines to include it.

Simpler solution: Download a copy of the stb_image.h and handle it as the rest of the source code. This is a very good solution, however lets have some fun.

To compile we need the file, so lets just download it:

stb_image.h:
    wget https://raw.githubusercontent.com/nothings/stb/master/stb_image.h

catimage: stb_image.h
    gcc -O3 -lm main.c -o catimage

The stb_image.h takes some seconds to compile... the loop is too slow... I will not touch the library so lets wrap it in a image.c file and compile it once:

image.o: stb_image.h
    gcc -O3 -c image.c

stb_image.h:
    wget https://raw.githubusercontent.com/nothings/stb/master/stb_image.h

Where the image.c:

// image.c

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

unsigned char* read_image(FILE* file, ...) {
    return call_to_the_lib(...) 
}

Now we need a header image.h to use it in the main.c. No we don't, its just one function:

// main.c

// #include "image.c"
unsigned char* read_image(FILE*, ...);

Put all together:

catimage: image.o
    gcc -O3 -lm image.o main.c -o catimage

First build: download stb_image.h (slow), compile image.c (slow), compile and link main.c (instant)
Rest of the builds: compile and link main.c (instant)



done_

Tuesday, February 18, 2020

Java: Let's serialize with a map

Lets just use a map. So we have a timer like thing:

public class Time implements Serializable {

    private long duration;
    private long start;

    // crazy things

}

Now lets put everything in a map:

    private void writeObject(java.io.ObjectOutputStream out) throws ... {
        Map map = new HashMap<>();

        map.put("duration", duration);
        map.put("start", start);
        out.writeObject(map);
    }

Now lets get everything back from the map:

    private void readObject(java.io.ObjectInputStream in) throws ... {
        Map map = (java.util.Map) in.readObject();

        duration = (long) map.get("duration");
        start = (long) map.get("start");
    }

Lets also put this because we are handling the versioning:

    public static final long serialVersionUID = 1L;

However this is too much stuff to write, so lets make a script to write it for us: https://maanoo.com/testing/JavagenSerialMap.html

Now lets add a new thing to see how to handle versioning

    private TimeUnit unit;  // v.2

So we have to update the things: (our script that is)

    private void writeObject(java.io.ObjectOutputStream out) throws ... {
        Map map = new HashMap<>();

        map.put("duration", duration);
        map.put("start", start);
        map.put("unit", unit);
        out.writeObject(map);
    }

    private void readObject(java.io.ObjectInputStream in) throws ... {
        Map map = (Map) in.readObject();

        duration = (long) map.get("duration");
        start = (long) map.get("start");
        if (map.containsKey("unit")) {
            unit = (TimeUnit) map.get("unit");
        } else {
            // TODO unit
        }
    }

And we replace the TODO by setting the default value of the unit:

    unit = TimeUnit.Milliseconds

Also, if or when we are sure that there is none of the old version left, we can remove the check of the key and remove the setting of the default value.

Except the full control that this system provides, the actual data that are stored are serialized primitives and collections, making possible to be access and/or debug the saved data by external program.



done_


Saturday, January 18, 2020

Android: Lets use android.R.string

I was writing a confirm dialog on android, and there was it:

    android.R.string.yes

So lets use it, why not. However my extreme imagination, for some reason, had the actual value of it being 'Yes'.
Build, run, test, boom! There was it, on the screen, a 'OK' laughing at my face.

So turns out there is a comment:

    <!-- Preference framework strings. -->
    <string name="yes">OK</string>

And they say comments are overrated...

PS: Just look at this, look deep:
    <string name="yes">OK</string>


done_

Wednesday, October 9, 2019

Java: Optional or just null

So I was making a simple game on the weekend, as we do, and there was a simple (again) player class:

public class Player {
    public final String name;
    private Team team;
    ....
    public boolean friendly(Player other) {
        return team.has(other);
    }
}

But the obvious thing is, can it be null? Yes it can, in cases where the player does not have a team. So I said 'Let's try Optional, why not`.

    private Optional<Team> team;

Then the possibilities for the return statement where limitless from the most straight forward to the most elegant:

    return team.isPresent() && team.get().has(other)

    return team.map(i -> i.has(other)).orElse(false);

    return team.filter(i -> i.has(other)).isPresent();

    return team.orElse(Team.EMPTY).has(other);
    
Or I could remove the Optional again and have just the old thing:

    return team != null && team.has(other);

But 'How will you remember that it can be null in other places?' said the guy. Its a private field, how many places are there really. Also it is logical to null so I would probably check it anyhow.


done_

Saturday, August 31, 2019

Security: Just remove everything -Boss

Let's consider for a fact that we have a very pseudo secure environment. Pseudo referring to something that has been purified of everything that can be a source of vulnerability. So we have no compilers, no runtimes and of course no internet. Also we have some physical security, the whole thing is locked in a box with only the cables for monitor, keyboard etc. and a wire with a button on it to start the machine.

Boss asks, is there any way for someone to harm this system.

YES! SO MANY WAYS!
Just ctrl-A and delete, dude.

PS: My task is too keep the antivirus up to date....


done_

Sunday, July 21, 2019

Javascript: Do it like php!

So, I just wanted a simple thing... I had a static html page where I wanted to put some things in dynamically: a simple date at the start and an extended date in the middle of the text. (Also what is server side?)

Pure elegant javascript:

.... <span data-value="simple"></span> ....

<script>

var data = {
    simple: gen_simple(),
    ....
}

for (var i of document.querySelectorAll('[data-value]')) {
    i.innerHTML = data[i.getAttribute('data-value')];
}

<script>

Php infected javascript:

.... <script>document.write(gen_simple())</script> ....

plus if in 'I was never here' mode:

....
<script>
for (var i of document.querySelectorAll('script')) i.parentNode.removeChild(i);
</script>



done_

Thursday, January 10, 2019

Java: Iterable iterator

We all have been in a position with an Iterator in our hands and trying to pass it to a for each loop. And then for some reason that is totally crazy for a second an error pops up:

"Can only iterate over an array or an instance of java.lang.Iterable"

What... a ok... and then what? You could just fix your logic in order or just google for "java iterator to iterable". But could you just make the iterator also an iterable somehow.

Step one, obviously, add the Iterable interface to your iterator:

public class SuperIterator<T> implements Iterator<T>, Iterable<T> {

Step two, add the missing method by return itself as its iterator:

@Override
public Iterator<Character> iterator() {
    return this;
}


done_