Wednesday, May 1st, 2024 build techniques utils • 210w

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_

Tuesday, July 19th, 2022 code 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_

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_

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_ 

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_
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_


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, 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_
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_
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_
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_