Friday, August 23, 2024

Techniques: From code to data and back to code

Lets create a series of fields:

{
  container.add(new Field("name", "text"));
  container.add(new Field("surname", "text"));
  container.add(new Field("something", "text"));
}

But wait we can just collect all the actuall info and then have the data so the code 'is not repeating':

fields = [
  { title: "name", type: "text" },
  { title: "surname", type: "text" },
  { title: "something", type: "text" },
];

But wait we can use code so the data 'is not repeating':

fields = [
  ...[ "name", "surname", "something" ]
       .map(i => ({ title: i , type: "text" }))
];

But wait we can use data so the code 'is not repeating':

fields = [
  { titles: [ "name", "surname", "something" ], type: "text" },
  { titles: [ "birth", "death" ], type: "date" },
].flatMap(magic);

But if you really thing about it, and ignore any "non-programmers", who are those guys anyway, the first one is what actually what happens, and by definition has no limitations because it's actually the thing itself, like C. And then you add some sugar and you are also modern:

{
  container.add(
    field.text("name"),
    field.text("surname"),
    field.text("something"),
    field.date("birth"),
    field.date("death").optional,
  )
}



done_

Sunday, June 23, 2024

Decline of Thought: Tailwind CSS

Top "css library" of 2020s, tailwind css with the its message "Rapidly build modern websites without ever leaving your HTML" and with the sample code in the home page:

<figure class="md:flex bg-slate-100 rounded-xl p-8 md:p-0 dark:bg-slate-800">
  <img class="w-24 h-24 md:w-48 md:h-auto md:rounded-none rounded-full mx-auto" src="...">
  <div class="pt-6 md:p-8 text-center md:text-left space-y-4">
    <blockquote>
      <p class="text-lg font-medium">...</p>
    </blockquote>
    <figcaption class="font-medium">
      <div class="text-sky-500 dark:text-sky-400">...</div>
      <div class="text-slate-700 dark:text-slate-500">...</div>
    </figcaption>
  </div>
</figure>

This cannot be a real think, this is a joke. What is this mess that is presented as the example. The code does not even fit in the pre tag they have. This is a classic example of a taking a good idea that solves well a very specific problem in some specific situation and assuming that it can be expanded to solve the universe.

In our case this good idea is creating some small classes to describe a common css property that is not bound necessarily with the rest of the context and it is independent of the rest of the rules, eg. a class named center that just sets the text align to the center (and even this can be argued that has an effect in the around paddings and margins and if they have to be symmetric)

And the bad idea, the whole tailwind css main gimmick, that with infinite classes and dumping everything in the html file will solve everything. When in reality you solve nothing and contribute just in the reduction or readable code. Which is an other common insane idea, that you should be able to write code very fast even if it not readable. This is true only for prototyping, in the lifetime of a peace of code you have 1 write in the beginning and 1 read with a possible 1 write/change after that, so with very complex math we know that the the reads is always greater that the writes.

The irony is that the same web devs cults that support the idea of readability and use it to make fun of the old school c programmer, but when they find their own "c macros" (see. tailwind) they are all about that life. Fuck off losers.



done_

Thursday, June 20, 2024

Html: Write the tags of your dreams

Lets say we want to write some quick html and js thing to test something. We want a text field and a button to login with a username and if logged, some text with the username saying hello.

Ok, we skip all the html, head and body tags and we just write this:

<login>
    <input type="text">
    <button onclick="login()">Log in</button>
</login>

<hello>
    Hello <username>
</hello>

We add and a script tag in the end and we are done (and it works, this is not a joke)

It may not be obvious but we are not following the law of the "Valid custom element names" and if we then define some components with these name you are going to get the "Failed to execute 'define', 'hello' is not a valid custom element name".

Very important check, image this check not being there all the bad things that could happen. Like when you try to create a component "icon" but there is no hyphen there, so you spend all day trying to figure out if "a-icon" or "icon-" is the least ugly of the two, and then you are unable to sleep thinking that there must be some other way to cheat the system... there must be... Thank you whatwg.



done_

Techniques: Multiple localhost sessions

Lets assume you have an web app with some sort of login system, and you are testing things on a local web server bound to "localhost" and you want to test multiple logged in users at the same time.

We start by creating multiple "domains" pointing to the localhost via the /ets/hosts file:

127.0.0.1  localhost1
127.0.0.1  localhost2
127.0.0.1  localhost3
127.0.0.1  localhost4
127.0.0.1  localhost5
127.0.0.1  localhost6
127.0.0.1  localhost7
127.0.0.1  localhost8
127.0.0.1  localhost9

Because the session and local storage is instanced per domain name (or even the cookies for the old school) using the localhostX will each be isolated.

Then you fight with your web server that definitely will not like requesting http with something different than localhost, but you can win.

And then you fight with the OAuth callback redirect url and... you lose the fight... and you go back to the firefox containers.



done_

Wednesday, May 1, 2024

Techniques: Patch files

Create a patch file:

  • Locate the file we want to change, eg. path/file.json
  • Create a copy of the file and edit it in the same directory, eg. path/file.new.json
  • Create the diff file by running the program diff, eg.
    diff -u path/file.json path/file.new.json > file.json.diff
  • Ensure or change the first lines of the diff file in order to point to the desired files, eg. path/file.json to build/path/file.json
  • Apply the patch by running the program patch, eg.
    patch -p0 < file.json.diff

Notes:

  • Both programs, diff and patch, should be part of the core programs on any linux distribution
  • The -u option specifies that the created file is of unified type
  • The -p0 options specifies that the full paths inside the first lines of the diff file should be used



done_

Friday, November 10, 2023

JavaScript: Generic selector proxied object

Lets create a thing to replace the very simple selector calls for id and classes.

First lets have simple selector for both the id and single class.

return document.getElementById(name) || 
    [...document.getElementsByClassName(name)]

Here we also return a single value when you pass an id and an array (expanding the default HTMLCollection) when a class is passed.

Now, if we want the make the whole thing more elegant like this:

elements.footer // == document.querySelector('#footer')
elements.button // == document.querySelectorAll('.button') 

We can use the a proxy handler to catch the selector like text that we defined above and return the elements.

const elements = new Proxy({}, {
    get(target, name) {
        return document.getElementById(name) || 
        	[...document.getElementsByClassName(name)];
    }
})

Where every time a property of elements must be deference the name of the property will end up in the get method in the name argument. 



_done

Saturday, September 16, 2023

Review: Oppenheimer

This is a review of the film Oppenheimer (2013), the depiction of Oppenheimer's life and his actual life based on the same depiction.

  • Opening scene, "Prometheus stole fire from the gods and gave it to man. For this he was chained to a rock and tortured for eternity.": so we understand from this insert that the film's core is about... nope, this is totally irrelevant and misleads the audience in every single way about the nature of the film and attempts to insert state of mind for the following scene because it fails to do so there. Also the comparison is just wrong and the motivations of Prometheus and his actions and his punishment and its reasons do not match.
  • Visual of "hidden universe", is this a joke?
  • 'Oh you didn't let me attend a lecture before I cleaned up the mess I did, ok... I will kill you then.' you are not "emotionally immature" my friend you are fucked up and should arrested for attempted murder, put in prison and the end of the film.
  • Regrets the attempted murder because of a vision of 'A horse being fed an apple', surely there is a point for the horse... nope, none.
  • "You asked the only good question" but we will keep it a secret because this is how you tell a story be being secretive about the referenced things.
  • "Worm hole", no reaction, continue discussion, yes totally normal interaction.
  • "Can you hear music. Yes I can", then visual has more music, this is the level of storytelling that we have here?
  • Sightseeing, random visual, routine, other random visual, madness; Iron man trying to glaze Oppenheimer; Name dropping Albert Einstein; Oppenheimer playing hard to get; Oppenheimer had the ability to learn Dutch; Teasing us about Heisenberg.
  • "Can't you see it everywhere else? Picasso, Stravinsky, Freud, Marx." what the fuck are talking about
  • Wrong visual
  • "I'm Jean" Oppenheimer face, yes make it more obvious because this is how people work
  • "And you sound uncommitted" yes he is
  • Sex! he is easy, she is easy, pointless one night stand for no reason other than to show some boobs and also more languages. So far he is more of a linguistician than a physicist.
  • But wait why does he likes her, is it just because of her gender, are we going to learn something about that or respectively from her side… nope
  • "And now I am become Death... destroyer of worlds" wtf? what the actual fuck is this? he just said that his work is abstract, so its just a cool phrase with nothing of substance.
  • "It's like a kind of hole in space" worst visual of the whole movie.
  • Oh she was not a one night stand... "I didn't expect to see you today." why was she even in the scene? (101)
  • "Well, you say that, and then you call. Well, don't answer." red flag, crazy detected, abort my friend. So (101) was there to show time passing of the relation by using 3 seconds of an unrelated scene, yes that sounds very clever
  • "For a year or two during a previous marriage, my wife Kitty had been a Communist Party member."
  • Now we skipped to the next woman.
  • Lifestory dump, "Now here I am" to fuck you because I am bored.
  • Oh the other one is still here, why? "We both know I'm not what you want, Jean." we dont know, can you tell us so we know what the fuck is happening?
  • So are all the black and white scenes there to just state things in order to fill the missing story parts from the future of the current color-having part of the movie. And why we are learning the start and the end of the story in parallel, why. What is the point. Why are we also learning the end of the story from some other perspective. Why not learn the start from some other perspective. Probably because the collapse/collision (81) of the two perspectives will lead to something better... nope, is just there to make the movie less boring by jumping between the two time instances.
  • Baby alert! Drunk mama, disassociate father. Let's dump the kid, fuck that, who cares.
  • "Selfish, awful people, they don't know they're selfish and awful." just a false generalized statement and in this case there are obviously selfish and awful and other things.
  • Kid dumped, we are free, let's go horse riding!
  • "Having a child was always going to change..." 'bro fuck the child, who cares, I'm over it' the mom said.
  • Dumbest pitch of an idea, dumbest montage of... recruiting scientist.
  • Random military uniform out of nowhere.
  • Doctor Octopus laying the facts nobody else seems to care about: bombs kill people.
  • Older baby alert! what the fuck happened, I guess we dont care, it's only his child how important can it be.
  • Can somebody explain to me why the head of the thing does not have security clearance before he starts to run the thing that needs security clearance. Why is a thing that we should care about, is there a reason for the whole thing, what, why, how...
  • Yo, this is just weird at this point, we did not need that. We don't care about his wife, it's more possible to hate her, then why would we care if he cheated on her with another woman that gives the most weird messages and usually is naked.
  • "But you have other priorities now. I have a wife and child." no you don't, you just have a bomb, keep it real bro.
  • The "Incedent" waste of the word, hope its a setup for later, because else... (44)
  • Reference back to Prometheus with a new wrong interpretation, nice.
  • So we are now in the black and white meeting but now with color. But what is the difference, oh the percepctive in which we observe the meeting which is implemented the camera now following Oppie... and nothing else. So for the director percepctive is camera focus and color, good job.
  • Oh never mind, the camera work is the same in both, so just color then.
  • Ok, now it starts to get interesting, about the bomb, politics and science, "A pillar of fire, 10,000 feet tall" lets test this thing.
  • "And now I am become Death... the destroyer of worlds." no you are not death, you are more like the scythe of dead, or actually the guy that made the scythe of dead, calm down.
  • "Bring in the sheets" nobody cares about you, we dont know who you are, we cannot care about you, even your husband doesn't really care about you, a waste of The Angel of Verdun. Btw he has more children.
  • After all this time, he now realized what a bomb is, who could have thought that people would end up dying...
  • "Crybaby" indeed.
  • And then starts a predictable wrap up for far too long
  • "Nobody knows what you believe. Do you? Hmm?" neither do we mye friend, go make the H-Bomb, good luck and we appreciate that the only interesting thing of this film came from you, the fact that the bomb would "ignite the atmosphere".
  • Iron man is smart, he did everything for revenge still not qualifying for the (81).
  • I'm bored, why are we still watching this, there is no way that Oppie will win this.
  • What is this, why is being pressed by the lawyer, why is he losing his compulsion when asked the same questions and why are at the same time Iron Man is also losing his compulsion and also just drama dumping. What is this, what is happening, this an empty raise of the volume from moments of high feelings in order to end on a high messy note. Please stop it.
  • This scene with the annoying lawyer has more intensity and visual effects than the bomb explosion
  • And of course the closing scene "We thought we might start a chain reaction that would destroy the entire world." ... "I believe we did." no you didn't, you just did faster than the others, the others also did, it wasn't even your idea, you didn't even make the bomb, you were the project manager.

So lets overview Oppenheimer: love life was a standard ignore family and some cheating here and there, scientist life was just ok lets do this - there are 3-4 ways to do it lets try the them and choose the best, political life of I don't commit to anything, core of his life was making the bomb and then regretting it.



next_ 

Wednesday, August 2, 2023

Windows: Single click to open

So while I was traveling through the menus to change the 'Show hidden files' options in a new Windows system I was cursed to used, I saw once more the the 'Single-click to open an item'.

I had seen it plenty of times, but for some reason it hit me this time. Why do we double click to open a file? Obviously because you don't want to open a file when you just click it. But why do we need to single click a file? for what?

But there must be reason... no there is no reason. 

And of course, if we check some web based file explorers like Google Drive, in the web were all the links are single click, we see that... it uses... double click... Never mind.

So lets try it, some other issue may pop up. [after 1 week] Some double opened files but we will get used to it. [after 1 month] Forgot even I switched to single click, everything is fine with half the clicks.

Making the world more optimized place.



done_

Wednesday, November 9, 2022

LibGDX: Blending in html gwt web

If you use OpenGl blending functions, you probably are doing something with the alpha buffer (or not). By default the alpha buffer is disabled on the html / gwt / web config.

So you need to go to the HtmlLauncher and set the alpha boolean to true:

public GwtApplicationConfiguration getConfig() {
	final GwtApplicationConfiguration config = new ...;
	config.alpha = true;
	return config;
}

A side effect by enabling the alpha buffer is the actual background will become pseudo transparent. At the end of the drawing the alpha buffer will be handled as the alpha channel of the whole canvas. So if there is no need for some transparency, at the end of drawing the whole alpha buffer should be filled with 1s. 



done_

Tuesday, July 19, 2022

Html: Enter handler on input text field

Every single time you have a input text field and submit-like button next to it, at some point, you would like to bind the same action of the submit button to the press of the enter key.

It's trivial, but also it's simply better to just copy-paste it. So here its is:

function onenter(ele, f) {
	ele.addEventListener('keydown', function (e) {
		if (e.keyCode === 13) { f(e); e.preventDefault(); }
	})
}

And also while we are here, instead of using the-not-be-named lib, just use these:

function q(x) { return document.querySelector(x); }
function qa(x) { return [...document.querySelectorAll(x)]; }
function range(x) { return Array.from({length: x}, (v, i) => i); }

For more just go here.



done_

Sunday, June 26, 2022

Html: Unwanted cached resources

So as you write a simple a html file with one or two resources, lets say one css and one js file, and you then deploy it (= copy paste) to a sever, and then you make some changes (= fix a bug), and then you redeploy (= copy paste, overwrite popup, press yes), and then nothing changes.

The browser, like always, remembers the old 'main.js' from before and then you pres Ctrl+F5. But your tester in the other side, has no clue what a Ctrl is. So you have to do something.

The first thing is to add a simple '?1' at the end of 'main.js' and every other resource, the browser thinks it may be a different file and deletes the cached version.

So now lets make a script to automate the replacement of the '?1' with '?2':

sed 's/"\(.*\)?.*"/"\1?2"||/' -i index.html

But we may want the browser to actually keep some cached files, the files that have not changed. Only if, instead of '?2', we could generate a number that only changes if the actual file changes and also does not repeat it self.

Hash functions? Checksums? Yes.

Lets use 'md5sum' to freak out the people who don't know. A single sed will not make it, lets write a sed to generate multiple seds and pipe it into a sh.

First we find checksums:

find -regex '.*\(js\|css\)$' -exec md5sum {} \+

Then we pipe that to our first sed:

sed 's/\(.*\)  \(.*\)/ ... \2 ... \1 ... /'

where in the place '...' we reconstruct version of our original sed (gets very unreadable). And finally we pipe it to a sh to actually do the substitution.

The whole thing if placed in Makefile would look like this:

index.html: *.css *.js
    find *.css *.js -exec md5sum {} \+ | \
        sed 's/\(.*\)  \(.*\)/sed \"s|\\"\2?[^\\"]*|\\"\2?\1|\" -i index.html/' | sh



_done

Saturday, September 18, 2021

Python: Easy help print

As a follow up of the "Bash: Easy help print", lets do the same thing. So I will just copy the whole text and replace what needs replacing...

Ok, lets create a single line of python that will handle the -h option and print something.

First, what to print? I usually add some comments on the start of the file, so lets print that. Example script:

#!/bin/env python3
#
#  This is the doc of the script
#

the line that we will add

code of script

Lets go step by step. We need to print the file it self:

h = open(args[0], 'r').read()
print(h)

Skip the first line (lets skip the read):

print(h[h.index('\n')+1:])	

Go until you find the first empty line:

print(h[h.index('\n')+1:h.index('\n\n')]

Remove the # fro the start of the line:

.replace('#','')

Finally, we check if the -h is the first argument, print the thing and exit:

if '-h' in args: h = open(args[0], 'r').read(); print(h[h.index('\n')+1:h.index('\n\n')].replace('#','')); exit()



done_

Wednesday, June 16, 2021

Javascript: Self call re-call interval set

 So we have the requestAnimationFrame, you pass a function and it called after a very specific while (irrelevant to the following).

Now lets see the basic structure:

function loop() {
    update()
    requestAnimationFrame(loop)
}
loop()

Ok now lets wrap the function and call it without calling it by name:

(function loop() {
    update()
    requestAnimationFrame(loop)
})()

Is there any way to remove the name of function and still pass it? There is a magical object called arguments which appears out of nothing every time a function is executed. And the member that we need is arguments.callee which is self reference to the function being executed. So we get rid of the name:

(function () {
    update()
    requestAnimationFrame(arguments.callee)
})()

And of course to maximize the coolness we put in a single line:

(function() { update(); requestAnimationFrame(arguments.callee) })()

Ok, this very cool, but is it worth it? Let's analyze what this code succeeds to do:

1. Confuses the next reader of the code.
2. Confuses also the 2nd reader.
3. Confuses also the 3rd reader.
...
N. Confuses also the N-th reader.

So you have to choose what is cooler: confusing no people or confusing up to infinite people? Comment below, like and subscribe.



done_



Techniques: Build-time pre-package capture

 Usually when things/files are packaged from simple files to single monstrosity, you no longer have the ability to ls/dir to lookup what things/files exist.

An example is a Java jar, where to list for example all the packaged files you either cannot or you need to open a zip stream and figure out yourself.

Also in Java and other languages with limited introspection you cannot for example list all the classes that implement the interface X.

So:

Create a script than generates all the information you want.

Put that script in the build/compile process.

Include the file in the project.

Write some code to parse the file.


Example of listing all the inheritance properties by finding all the extends keyword:

grep -hr extends | sed -E 's/.*class (\w+) extends (\w+) .*/\2 -> \1/'
Parent -> Child1
Parent -> Child2
...

No need to say again and again "This is not supported, I cannot do it", supported yourself, you are a damn programmer! 



done_ 

Friday, June 11, 2021

Html: Input tag drop-down list

The classic way to have a drop-down list in html is the select tag.

However there are two main problems/inconvenient. The select tag will only allow to select one item and you cannot type for a not included option or just to filter the list options. Also sometimes just have all the input fields under the same tag name <input> is just niter.

An other way is the <datalist>, that for some reason I learned about it lately (sad).

The classic example:

<input list="hashes">
<datalist id="hashes">
  <option value="sha1">
  <option value="sha256">
  <option value="sha512">
</datalist>


done_ 

Friday, March 5, 2021

Email: Why are you tracking me in "secret"

So Aege@n (airline) has been spamming me with emails after a took a single flight with them.

One day they actually sent an email with the subject that made me believe that it was interested in it, so I opened it, turns out it was a click bait, but:

I had 22 (unread) emails from them in a span of one year and after I opened that click bait I got 7 in the following month. So they knew, I opened it ... But how did they know?

There was no "Return receipt" request, so they have done something sneaky.

Lets look at the email.. ok, its just html

Lets load the images.. ok, some images from http://static.cdn... were loaded.

Wait what is that? All images are from a cdn except one:

https://news.aegeanair.com/pub/as?_ri_=X0Gzc2X%3DAQpglLjHJlTQGmafAoKGsenIJ7EBMdskH5TyfUpyNwKkXSeDbmwPrIMgdr9IPNDpYNzfLdOGMwzcGVXHkMX%3Dw&_ei_=EolaGGF4SNMvxFF7KucKuWPnzljXYMJZUMmgkkIvbZe171NV_sKNU-8XjLVsBtAWB1ASqm8piDcfWdATMJx3XCt5nps.

Lets open that image... ok its a 1x1 gif image.

A 1x1 pixels gif image.

A 1 pixel by 1 pixel gif image.

A 1 pixel width by 1 pixel height gif image.

A 1 pixel width by 1 pixel height graphics interchange format image.

So they masked a http request to there sever with a unique identifier as an image download request.

Is this ok? Hello?

...

I guess I manually clicked "Load all images" (even 1x1 gifs), so it must be ok... 

Wait, so this is why the there is the load all images button... cool.



done_

Wednesday, February 24, 2021

Python: Easy line plots

Need to just plot a file with numbers? Stop using matl@b or excl.

All we need is a couple lines of Python code:

import matplotlib.pyplot as p

p.plot(values)
p.show()

And for the values (if you have the number with new-line separating them) with either a file as an argument of just the stdin couple more lines:

import sys

stream = sys.stdin
if len(sys.argv) > 1:
    stream = open(sys.argv[1], 'r')

values = [float(line) for line in stream]



done_

Sunday, February 7, 2021

Bash: Easy help print

Ok, lets create a single line of bash that will handle the -h option and print something.

First, what to print? I usually add some comments on the start of the file, so lets print that. Example script:

#!/bin/bash
#
#  This is the doc of the script
#

the line that we will add

code of script

Lets go step by step. We need to print the file it self:

cat "$0"

Skip the first line (lets switch to sed):

sed -n '2,$ p' "$0"

Go until you find the first empty line:

sed -n '2,/^$/ p' "$0"

Remove the # fro the start of the line:

sed '2,/^$/ s/#// p' "$0"

Finally, we check if the -h is the first argument, print the thing and exit:

[ "$1" = '-h' ] && sed -n '2,/^$/ s/#// p' "$0" && exit



done_

Thursday, February 4, 2021

Android: Send preset SMS with with one tap

For all of you that need to sent a simple preset SMS without copy pasting all the time (covid-era).

For some reason on the play store most of the app that provide this kind of operation instead of sending the SMS they just open the messages app...

Ok, lets do it:

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phone_number", null, "message", null, null);

And because this android we need to haggle with the permissions:

<uses-permission android:name="android.permission.SEND_SMS" />
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) 
		!= PackageManager.PERMISSION_GRANTED) {
	ActivityCompat.requestPermissions(this, new String[] {
    		Manifest.permission.SEND_SMS}, 0);
}

And we are done, that's it.



done_

Thursday, May 7, 2020

Java: Return enum instead of boolean

We have a game where you place down buildings. So there is always a method that looks like that:

public boolean validPlace(BuildingType type, Location location) {

    for (int ix = 0; ix < type.w; ix++) {
        for (int iy = 0; iy < type.h; iy++) {
            
            if (/* check if overlapping */) {
                return false;
            } else if (/* check if road missing */) {
                return false;
            }
        }
    }
    return true;
}

The problem: While writing the game logic everything is fine, but then comes the UI. A can palce / cannot place is not enough for a good UI, you need the reason. And you usually have another method that finds out the reason. But can we use the same method?

First we need an enum with all the possible problems:

public enum PlacementValidity {
    Ok,
    Overlapping,
    RoadMissing;

    public boolean ok() {
        return this == Ok;
    }
}

Then we just return the enum instead of the boolean:

public PlacementValidity validPlace(BuildingType type, Location location) {

    for (int ix = 0; ix < type.w; ix++) {
        for (int iy = 0; iy < type.h; iy++) {
                
            if (/* check if overlapping */) {
                return PlacementValidity.Overlapping;
            } else if (/* check if road missing */) {
                return PlacementValidity.RoadMissing;
            }
        }
    }
    return PlacementValidity.Ok;
}

The helper function ok() method can also be used to reduce verbosity on the game logic side of the code.

if (validPlace(/* ... */).ok()) {




done_

Thursday, March 5, 2020

C: Autogen headers

It is known that I don't like writing header files and forward declarations. The keyword is writing, I like what you can do with header files, however I would also like to have an option, some times, to just autogen the headers. Also it could be nice to have a header file even in a single file program just to avoid forward declarations.

Lets thing about it... ok you need a C parser because C can be crazy some times. You can have macros and also you can have all kinds of whitespace in a function declaration. So you either write a program witch handles everything or you write a one-line bash thingy to handle only your style of code.

Lets do the second one (obviously). I write functions like this:

int send(cost char* text) {

So we grep all the lines which start with a character and end with a open bracket and then we replace the bracket with a semicolon:

grep '^\w.* {$' | sed 's/ {/;/'

Ok, lets put it in the Makefile:

%.h: %.c
    cat $< | grep '^\w.* {$$' | sed 's/ {/;/' > $@

What about the structs? Done, already handled.
What about typedefs? Nope... next post?

And a bonus effect is that if you include the header of the source file in its self you no longer need forward declarations.



done_

Monday, February 24, 2020

C: Have (more) fun compiling

And here we are:

...
} else {
    // TODO print the --help text
}
...

On ho... where to start... Lets start by making a simple plain text file and write all the things there. Now we have a help.txt.

The easiest solution would be to just read the help.txt file and print it at runtime, but then we need to package the extra help.txt file and also is "slow".

Could we somehow just pasted in? Yes but then we have to add quotes and handle special characters and half of our main.c file will be strings.

xxd. Oh! What is that? If you run:

xxd -i help.txt

We get this very readable c-string

unsigned char help[] = {
  0x63, 0x61, 0x74, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x3a, 0x20, 0x75, 0x6e,
  0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x20, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e,
  0x3a, 0x20, 0x25, 0x63, 0x0a, 0x0a, 0x55, 0x73, 0x61, 0x67, 0x65, 0x3a,
...

Seems good. Does it matter that is so readable, not really its just a build intermediate file. Lets add it to the Makefile with all the other build intermediate files:

help.c:
    xxd -i help > help.c

Now, how about a include in the middle of nowhere:

...
} else {
    #include "help.c"
    printf(help);
}
...

EDIT: xxd does not add a null character at the end...




done_

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_

Wednesday, November 14, 2018

Windows: Uninstalling programs

Time to clean up the old windows machine a bit (Linux user here).

So I go looking for the good old control panel, but I find the "Settings" so I go there. Let me skip the whole design and usability comments.

The thing is that when you click tap the Uninstall button there is some times a huge delay until the admin confirm thing pops up. I don't know why this is, if its a security thing or just a bug.

So I thought I could open the whole "Settings" as an admin and then the confirm thing would not pop up.

Long story short, the only relevant thing I could find was to open with admin the command prompt. And from there you can start the control.exe which is actually the old classic control panel. 

But nope, your are still in user mode.

After some googling research I found out that this is a fake cmd admin (the one in the start menu), you need to run `runas /u:administrator cmd` to get the actual admin cmd. And before you do that you need to kill the exploer.exe that already runs. 

Then to restore the explorer you need to open admin task manager to kill the admin exploer and open non-admin cmd and ....


PS: In this process I had the pleasure to uninstall the microsoft silverlight


done_

Friday, September 28, 2018

Regex: Final v

This is the most greek a proggrammer can be.


Ακολουθεί μία από τις χρήσιμες regex που έχουν γράψει στην ζωή μου.

Εντοπίζει λάθος χρήση του τελικού ν και το αφαιρεί.


/ (τη|αυτή|δε|μη|στη)ν (([βδφθχλρσζ]|(μ[^π])|(ν[^τ])|(γ[^κ]))[^ ]*)/ $1 $2/


πχ. `στην ζωή μου` > `στη ζωή μου`

Οπότε το τρέχω στην πτυχιακή μου:

`227 results found`

Και σκέφτομαι: οι υπόλοιποι άνθρωποι τι κάνουν. Οπότε το τρέχω στην πτυχιακή της Χριστίνας:

`0 results found`



whatever_

Thursday, July 26, 2018

Java: enum or boolean for two value properties


The is always that tip that floats around that you should always use enums instead of booleans, even when there is only two values.

Of course the point is that it will be much easier to read and mainly to extend in the future.

So from a simple

 public void setVisible(boolean value) { ...

you go to

 public enum Visibility { Visible, Gone }

 public void setVisible(Visibility value) { ...

And in the future you could add eg. the Invisible value.

But you miss the simplicity of a boolean and you also get the verbosity of an enum

 setVisible(Visibility.Visible)

and this happens

 setVisible(value ? Visibility.Visible : Visibility.Gone)

The classic solution is to add methods like show() or hide() to avoid the use of the enum

However a simply solution to collect the benefits of both world:

 public void setVisible(boolean value) {
     setVisible(value ? Visibility.Visible : Visibility.Gone)
 }

 public void setVisible(Visibility value) { ...

where the two boolean values will correspond to the two most used values of the enum

And why not add and some methods for the most used values

 public void show() {
     setVisible(Visibility.Visible)
 }

So in the end you have everything

 show()
 setVisible(true)
 setVisible(Visibility.Visible)


done_

Tuesday, May 16, 2017

C++: Euclidean distance variations


So how about this new std::hypot?


 float dx = x1 - x2;
 float dy = y1 - y2;
 return std::hypot(dx, dy);


Time: 12139783 ticks

How about the old one std::sqrt?


 float dx = x1 - x2;
 float dy = y1 - y2;
 return std::sqrt(dx*dx + dy*dy);


Time: 7026125 ticks (1.7 times faster)

Oh, the std::hypot performs an overflow check, so if you don't care about that just use std::sqrt

And of course the very old std:: nothing


 float dx = x1 - x2;
 float dy = y1 - y2;
 return dx*dx + dy*dy;


Time: 5667812 ticks (2.1 and 1.2 times faster)

Wait, can I just do


 return (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);


and let the optimizer fix it. Lets check

Time: 5592648 ticks (seems the same)


Source


done_

Friday, November 4, 2016

C++: New keyword exceptions

When new is used, a bad_alloc can be thrown. To return null pointer on error instead of the exception a second format can be used:

Site *maanoo = new (std::nothrow) Site("maanoo.com");


done_

Wednesday, October 12, 2016

Windows: Copy only what's new or changed

Copy all files (/H /G) and directories (/E) that are either new or changed (/D /Y)

xcopy C:\From C:\To /D /E /I /H /Y /G


done_

Monday, September 12, 2016

Java: Open link in browser

Open a link with the default browser:

Desktop.getDesktop().browse(new URL("http://maanoo.com").toURI());


done_

Friday, November 20, 2015

Techniques: Random art with symmetry

So lets add many circles together:



Thats ok but what if we add some symmetry.

Lets add symmetry from one axis:



From two axis:



Those examples are random but the point is that have something not random, they have structure.

I like the more complex symmetry from the center point (not the math definition):





continue_

Wednesday, November 18, 2015

Javascript: Canvas circles

So we always start:

var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");

and we have the basic:

c.fillRect
c.fillText
c.strokeRect
c.strokeText

and for all other shapes we use paths

I use a lot of circles so why not add:

c.fillCircle
c.strokeCircle

We can do that by adding some functions to the prototype of the c with is the CanvasRenderingContext2D:

CanvasRenderingContext2D.prototype.fillCircle = function(x, y, r) {
  this.beginPath();
  this.arc(x, y, r, 0, 2 * Math.PI);
  this.fill();
};

CanvasRenderingContext2D.prototype.strokeCircle = function(x, y, r) {
  this.beginPath();
  this.arc(x, y, r, 0, 2 * Math.PI);
  this.stroke();
};


done_

Monday, November 16, 2015

HTML: Canvas background

To have a canvas as a html page background we need:

HTML:

<body onload="load()">
  <canvas id="canvas_back"></canvas>
  ...
</body>

CSS:

#canvas_back {
  position: fixed;
  top: 0px;
  left: 0px;
  z-index: -1;
}

JavaScript:

var c, w, h;

function load() {
  var canvas = document.getElementById("canvas_back");
  c = canvas.getContext("2d");

  window.addEventListener('resize', resize, false);
  resize();
}

function resize() {
  w = canvas.width = window.innerWidth;
  h = canvas.height = window.innerHeight;
  draw();
}

function draw() {
  // use c, w and h to draw the canvas
  ...
  requestAnimationFrame(draw);
}


Demo 1


done_

Friday, November 13, 2015

Android: Store values

We can save and load values, permanently, using Shared Preferences.

The shared preferences framework provides an easy way to store values, not only preference related but any kind of values. It's a file based so keep that in mind.

To get the SharedPreferences object we need:

private static final String NAME = "...";
public static SharedPreferences getPreferences(Activity a) {
  return a.getSharedPreferences(NAME , Context.MODE_PRIVATE);
}

To save a values we:

public static void save(Activity a) {
  SharedPreferences.Editor sp = getPreferences(a).edit();

  sp.putString("name1", value1);
  sp.putInt("name2", value2);

  sp.commit();
}

And to load a values we:

public static void load(Activity a) {
  SharedPreferences sp = getPreferences(a);

  value1 = sp.getString("name1", default1);
  value2 = sp.getInt("name2", default2);
}

We can also get a single Preferences for each activity with:

getPreferences(Context.MODE_PRIVATE)

Except MODE_PRIVATE we have MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE which are deprecated, so don't use them.


done_

Wednesday, November 11, 2015

JavaScript: Local and Session storage

To store values to a browser we can use localStorage and sessionStorage just by:

localStorage["name"] = value;

and to get the values we just:

value = localStorage["name"];

The localStorage keeps the values for ever (probably).
The sessionStorage keeps the values until the page session ends.

For each domain our browser has a pair of these objects and not for each page.

To store objects without functions we use JSON:

localStorage["name"] = JSON.stringify(object);
object = JSON.parse(localStorage["name"]);


done_

Monday, November 9, 2015

JavaScript: jQuery selector

If we want to use JQuery ONLY for selecting elements like:

$(".item")

Why use a whole library, just:

document.querySelectorAll(".item")

or

function q(query) {
  return document.querySelectorAll(query);
}

q(".item")

Note: The only thing we gain from this is self-something.


continue_

Friday, November 6, 2015

PHP: Simple counter

A simple counter using a text file.

The php code:

<?php
  $path = "./counter.txt";
  $count = intval(file_get_contents($path));
  if(isset($_GET["add"])) {
    $count++;
    file_put_contents($path, $count);
  }
  echo $count;
?>

To add one to the counter must be called with GET parameter add.

To get the counter value must be called with no parameters.


done_

Wednesday, November 4, 2015

CSS: Transition all

In CSS if we define transitions, every time a value changes an animation-transition is created and executed.

So if we want to use transitions for all elements and for all values (which is wrong in many ways), we can just write:

*{
  transition: all 0.7s ease-in-out;
}


done_

Monday, November 2, 2015

Techniques: Base64

Base64: make anything to a "simple" text and reverse.

Where "simple" means that contains only the 'A'–'Z', 'a'–'z', '0'–'9', '+', '/' and '=' characters.

It's not in any way something to use for encryptions its just for converting raw data to text.

It's most used when the data contain small bytes (control characters) which are trick to send handle in some environments.




continue_

Friday, October 30, 2015

Techniques: Generating colors with HSL and HSV/HSB

Some definitions first:

HSL: Hue Saturation Lightness
HSV: Hue Saturation Value
HSB: Hue Saturation Brightness

HSL != HSV
HSV = HSB (so forget all about the name HSB)

The difference between the two is how the represent the black and white, but they have in common how the represent the actual color referred as hue.

So the colors HSL(h, s1, l) and HSV(h, s2, v) have the same base color in a amount defined by the s1 and s2 and some amount of black or white defined by the l and v.

The point is that these representations can be used in scenarios where classic RGB can't do the work.
  • Imagine a layout (for a site, an application or even a poster) where all elements are darker and brighter versions of the base color.

    All these colors will be HS?(h, a, b) where h shared constant and a, b some values.

    So if h is a variable of some kind, we can change the whole color scheme by adjusting a single value.

  • Imagine a need for a array of colors which have the same saturation - lightness - brightness and change smoothly (for animations, transitions or fractal coloring).

    We can gererate these colors using the formula HS?(i*step, a, b) where i the index of the items in the array and step, a, b some values.


done_

Wednesday, October 28, 2015

Code: Normalize overflowing values

To normalize values like degrees where the main range is [0, 360) but all other values are accepted too the obvious is:

value = value % 360

Which  in case of a [min, max) range is:

value = (value - min) % (max - min) + min

But when the value is a negative number or even smaller than the min we get wrong result.
What we can do is "overflow" the value one more time:

value = ((value % 360) + 360) % 360

Which  in case of our generic [min, max) range is:

value = ((value - min) % (max - min) + max - min) % (max - min) + min

In an extended form:

len = max - min
value = ((value - min) % len + len) % len + min


done_

Monday, October 26, 2015

Java: Set the Clipboard

The easiest way to make the Clipboard contain a string is:

public void setClipboard(String text) {
  Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
  StringSelection selection = new StringSelection(text);
  c.setContents(selection, selection);
}


done_