Tuesday, July 19th, 2022 html javascript utils • 158w

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 26th, 2022 code html techniques • 367w

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 18th, 2021 code easy python utils • 246w

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 16th, 2021 code javascript techniques • 252w

 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_



Wednesday, June 16th, 2021 build techniques • 218w

 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 11th, 2021 code html utils • 146w

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 5th, 2021 email life • 311w

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 24th, 2021 code easy python utils • 128w

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 7th, 2021 bash code easy utils • 182w

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 4th, 2021 android code utils • 172w
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 7th, 2020 code enum java techniques • 271w
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 5th, 2020 c code make makefile techniques • 267w
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 24th, 2020 build c code make makefile • 284w
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 20th, 2020 build c code make makefile • 438w
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 18th, 2020 code java techniques utils • 436w
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 18th, 2020 android code it is known • 134w
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 9th, 2019 code java techniques • 256w
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 31st, 2019 life security • 134w
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 21st, 2019 code javascript techniques • 158w
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 10th, 2019 code java techniques utils • 170w
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 14th, 2018 life windows • 301w
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 28th, 2018 greek life regex • 55w
This is the most greek a proggrammer can be.


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

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


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


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

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

`227 results found`

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

`0 results found`



whatever_
Thursday, July 26th, 2018 code enum java techniques • 263w

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 16th, 2017 c++ code techniques • 285w

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 4th, 2016 c++ code techniques • 56w
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 12th, 2016 utils windows • 49w
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 12th, 2016 code java utils • 38w
Open a link with the default browser:

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


done_
Friday, November 20th, 2015 techniques • 406w
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 18th, 2015 code javascript utils • 145w
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 16th, 2015 code css html javascript • 136w
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 13th, 2015 android code utils • 194w
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 11th, 2015 code javascript utils • 121w
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 9th, 2015 code javascript utils • 75w
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 6th, 2015 code php utils • 86w
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 4th, 2015 code css utils • 69w
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 2nd, 2015 code techniques • 395w
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 30th, 2015 code techniques • 277w
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 28th, 2015 code utils • 153w
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 26th, 2015 code java utils • 61w
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_