What’s the cloud? An elegant abstraction!

For example, do you remember the old times of complex caching techniques? Look at the solution for containers, where modern apps live.

stages:          # List of stages for jobs, and their order of execution
  - build
  - test
  - deploy

build-job:       # This job runs in the build stage, which runs first.
  stage: build
  cache:
    key: build-cache
    paths:
        - cache
  script:
    - echo "Compiling the code..." >> cache/my.txt
    - cat cache/my.txt
    - echo "Compile complete."

If you don’t recognize how cool it is, there’s something you are missing! Really.

A question to check: what happens when you run the second pipeline? What’s the output?

Successfully extracted cache
Executing "step_script" stage of the job script 00:01
Using docker image sha256:27d0... for ruby:2.5 with digest ruby@sha256:ecc3e...4b ...
$ echo "Compiling the code..." >> cache/my.txt
$ cat cache/my.txt
Compiling the code...
Compiling the code...

Yeah, the above, exactly: the line’s doubled since it’s cached.

Ok, fine, but you’ll object: it doesn’t work for me, because you may want to separate the upload and the download phases in possibly different pipelines.

No worries: e.g. you can use azure blob upload or download, again the main idea is that you’ll simply define the corresponding microsoft image in a cool yaml to enable your client sdk.

And that’s all folks

Bypass same origin frame

Let’s say you want to execute JavaScript code after a redirect

If you use document href you won’t be able to that.

If you try with a frame the same origin will block you

Here below a practical solution!

document.getElementById("idButton").onclick=async ()=>{ 
  var myUrl = document.getElementById("myUrl").value;
  console.log(myUrl);
  var frame = document.getElementById("frame"); 
  var x = await fetch(myUrl);
  var html = await x.text(); 
  
  document.write(html);
  console.log("document written ");
 
  
  console.log('DOM is ready.');
  document.querySelector("[subscriptions-section='content']").removeAttribute("subscriptions-section");
};


Of course this is a practical solution for a specific goal and it is valid in the context of those requirements. There is no “one fits all” way to do things.

The fetch request could be blocked by cors on server in same cases, so one can resort to proxy like that

 myUrl = "https://api.codetabs.com/v1/proxy?quest=" + myUrl; 

Another free option with cloudflare for the fetch is a serverless worker.

Load WPF from memory

There are two steps.

A launcher

[STAThread]
static void Main(string[] args)
{

    string pathMain =

that is loading the WPF in memory

byte[] bytes = File.ReadAllBytes(pathMain);
Assembly assembly = Assembly.Load(bytes);

var app = typeof(Application);

var field = app.GetField("_resourceAssembly", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, assembly);

var helper = typeof(BaseUriHelper);
var property = helper.GetProperty("ResourceAssembly", BindingFlags.NonPublic | BindingFlags.Static);
property.SetValue(null, assembly, null);


try
{
    assembly.EntryPoint.Invoke(null, new object[0]);
} catch(Exception ex)
{
    Debug.WriteLine(ex);
}

and a modified WPF with the following App.xaml.cs in order to resolve the dependencies

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        base.OnStartup(e);
    }
    private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        string dir = @"C:\your\path\to\WPF\exe\folder\";
        string fileExtension = "*.dll";
        string needed = args.Name.Split(',')[0];
        if (needed.EndsWith(".resources"))
        {
            return null;
        }
        foreach (String file in Directory.GetFiles(dir, fileExtension, SearchOption.TopDirectoryOnly))
        {
            string name = System.IO.Path.GetFileNameWithoutExtension(file);
            if (args.Name.StartsWith(name))
            {
                byte[] bytes = File.ReadAllBytes(file);
                Assembly assembly = Assembly.Load(bytes);
                return assembly;
            }
        }
        Debug.WriteLine(args.Name);

        return null;
    }
}

Signing your assemblies

All this goes very well with an encrypted signature for your assemblies!

Remember: to verify your signature they only need the public key.

Both in the launcher for the exe

using (var crypt = RSACryptoServiceProvider.Create())
{
    using (StreamReader sr = new StreamReader(@"C:\path\to\publickey.xml"))
    {
        string publickkey = sr.ReadToEnd();
        crypt.FromXmlString(publickkey);
    }
    string outdir = @"C:\path\to\Signatures";
    byte[] signed = File.ReadAllBytes(Path.Combine(outdir, "YourExe.signed"));
    bool verified = crypt.VerifyData(bytes, signed, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
    if (!verified)
    {
        return;
    }
}

As well as for the dll files, with a simple helper:

private bool VerifySigned(byte[] bytes, string name)
{
    using (var crypt = RSACryptoServiceProvider.Create())
    {
        using (StreamReader sr = new StreamReader(@"C:\path\to\publickey.xml"))
        {
            string publickkey = sr.ReadToEnd();
            crypt.FromXmlString(publickkey);
        }
        string outdir = @"C:\path\to\Signatures";
        byte[] signed = File.ReadAllBytes(Path.Combine(outdir, name + ".signed"));
        bool verified = crypt.VerifyData(bytes, signed, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
        return verified;
    }
}

your code is very neat

byte[] bytes = File.ReadAllBytes(file);
bool verify = VerifySigned(bytes, name);
Debug.WriteLine(name + " verified: " + (verify ? "yes" : "no"));
if (!verify)
{
    return null;
}
Assembly assembly = Assembly.Load(bytes);
return assembly;

Perfect! But how do you save your private and public keys, first of all? Here it is:

void ProduceXML()
{
    using (var crypt = RSACryptoServiceProvider.Create())
    {
        string secretkey = crypt.ToXmlString(true);
        Console.WriteLine("secretkey");
        Console.WriteLine(secretkey);
        using (StreamWriter sw = new StreamWriter(@"C:\path\to\secretkey.xml"))
        {
            sw.WriteLine(secretkey);
        }
        string publickey = crypt.ToXmlString(false);
        Console.WriteLine("publickey");
        Console.WriteLine(publickey);
        using (StreamWriter sw = new StreamWriter(@"C:\path\to\publickey.xml"))
        {
            sw.WriteLine(publickey);
        }
    }
}

So now you’re able to sign your code so that it won’t be tampered with: enjoy it!

using (var crypt = RSACryptoServiceProvider.Create())
{
    using (StreamReader sr = new StreamReader(@"C:\path\to\secretkey.xml"))
    {
        string secret = sr.ReadToEnd();
        crypt.FromXmlString(secret);
    }
    string dir = @"C:\path\to\bin\Release\";
    string fileExtension = "*.dll";
    byte[] exe = File.ReadAllBytes(Path.Combine(dir, "YourApp.exe"));
    byte[] crypto_exe = crypt.SignData(exe, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
    string outdir = @"C:\path\to\Signatures";
    File.WriteAllBytes(Path.Combine(outdir, "YourApp.signed"), crypto_exe);
    foreach (String file in Directory.GetFiles(dir, fileExtension, SearchOption.TopDirectoryOnly))
    {
        string name = Path.GetFileNameWithoutExtension(file);
        byte[] bytes = File.ReadAllBytes(file);
        byte[] crypto_dll = crypt.SignData(bytes, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
        File.WriteAllBytes(Path.Combine(outdir, name + ".signed"), crypto_dll);
    }
}

Node.JS Express SQLite for Angular REST API

Here is my REST API implementation for Angular angular-tour-of-heroes-example !

const sqlite3 = require('sqlite3');
const express = require("express");
const cors = require('cors');

var bodyParser = require('body-parser');

var app = express();
app.use(cors())
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded


const HTTP_PORT = 8000
app.listen(HTTP_PORT, () => {
    console.log("Server is listening on port " + HTTP_PORT);
});

process.on('SIGINT', function() {
    console.log('Do not shut down the app on user log-off');
    //server.close();
  });

const db = new sqlite3.Database('./emp_database.db', (err) => {
    if (err) {
        console.error("Erro opening database " + err.message);
    } else {

        db.run('CREATE TABLE heroes( \
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
            name NVARCHAR(20)  NOT NULL\
        )', (err) => {
            if (err) {
                console.log("Table already exists.");
                return;
            }
            let insert = 'INSERT INTO heroes (name) VALUES (?)';
            db.run(insert, ['Dr Nice']);
            db.run(insert, ['Narco']);
            db.run(insert, ['Bombasto']);
            db.run(insert, ['Celeritas']);
            db.run(insert, ['Magneta']);
            db.run(insert, ['RubberMan']);
        });
    }
});

app.get("/heroes/:id", (req, res, next) => {
    var params = [req.params.id]
    db.get("SELECT * FROM heroes where id = ?", [req.params.id], (err, row) => {
        if (err) {
            res.status(400).json({ "error": err.message });
            return;
        }
        res.status(200).json(row);
    });
});

app.get("/heroes/", (req, res, next) => {
    console.log('get params',req.query);
    if (req.query && req.query.name) {
        search = '%' + req.query.name + '%';
    } else {
        search = '%';
    }
    db.all("SELECT * FROM heroes where name like ?", [search], (err, rows) => {
        if (err) {
            console.log(err.message);
            res.status(400).json({ "error": "sql error" });
            return;
        }
        res.status(200).json(rows);
    });
});

app.post("/heroes/", (req, res, next) => {
    var reqBody = req.body;
    console.log(reqBody);
    db.run("INSERT INTO heroes (name) VALUES (?)",
        [reqBody.name],
        function (err, result) {
            if (err) {
                res.status(400).json({ "error": err.message })
                return;
            }
            res.status(201).json({
                "id": this.lastID, "name": reqBody.name
            })
        });
});

app.put("/heroes", (req, res, next) => {
    var reqBody = req.body;
    var hero = [reqBody.name, reqBody.id]
    db.run(`UPDATE heroes set name = ? WHERE id = ?`,
        hero,
        function (err, result) {
            if (err) {
                res.status(400).json({ "error": res.message })
                return;
            }
            res.status(200).json({ updatedID: this.changes });
        });
});

app.delete("/heroes/:id", (req, res, next) => {
    db.run(`DELETE FROM heroes WHERE id = ?`,
        req.params.id,
        function (err, result) {
            if (err) {
                res.status(400).json({ "error": res.message })
                return;
            }
            res.status(200).json({ deletedID: this.changes })
        });
});

Circularity: philosophical types and real-world python

Already from a philosophical standpoint, the second-order or polymorphic λ-calculus presents circularity, but we can immediately note that

We are used to circularities in definitions of recursive functions and types, so we should not abandon hope about the system.

from chapter 9 of Type Theory & Functional Programming of Simon Thompson

In math topology we study cut points to define the connected spaces and homeomorphisms and that is the theoretical basis for the solution I’m proposing here in python

But what is the correct practical approach? They usually say you need modularity and many trendy buzzwords follow like microservices, but I present you a simpler, more effective way of programming.

Well, the 3 files circle1.py, circle2.py and circle3.py are

# circle1.py
A = 1

# circle2.py
from circle1 import A
B = A + 1
from circle3 import C
print(C)

# circle3.py
from circle2 import B
C = B + 1
D = 'imported!'

Now, if you try importing circle3 you get a worrying circular import error. But which is the solution? Ask a philosopher or a mathematician. That is simply a disconnection due to a cut point, it is the philosophical fact that

lines are not homeomorphic to circles

From Wikipedia: Cut-point

Programmer’s solution: cut “and paste“: you simply need to import circle2 before circle3! Easy like that!

Socket.io: no authentication no party🎉🎊🎈

My objection to latest tutorial from YouTube about socket.io, python and javascript.

There might be something I’m missing but passing a username under an insecure channel is equivalent to a simple data input not a real world authentication. Thank you very much for clarifying this matter, but if ws protocol doesn’t provide headers for authentication imho it’s much better staying with the classic web services under https. At this point I fail to see the motivation for socket.io: implementing a web service is more secure, simple as well and offers the same features, doesn’t it?

You can follow the discussion on YouTube. My fears are described for example under the paragraph No authentication during the handshake process from https://www.neuralegion.com/blog/websocket-security-top-vulnerabilities/

See the need of counterchecking the ticket against an IP, just an example, but it scares me because I don’t think it is practical.

Why are mathematics and physics no longer useful to mankind?

They have really been in the past centuries, but they are almost dead now and it is no longer worth investing in them, let me explain why.

First of all, this is especially evident for physics: last expensive experiment at CERN by looking for supersymmetries, strings and anything beyond the standard model has definitely shown that theoretical and experimental physics projects have reached the maximum extent and the limit of the knowledge they could bring.

But this is also true about math, in a more subtle way. Its capacity of abstraction is also at the boundary of its capabilities. Researchers are just reinventing new languages to artificially rediscover the same theorems in a more obscure, cryptic way. Examples? (Co)Homology/Homotopy, Category theory and similar variations.

The best wishes for new year is that young people forget this madness and lend themselves to medicine, engineering, non-profit organisation of social utility and honest professions.

Happy New Year ! ! !

Code Challenge

I know that there are many false code challenges and that those guys know the probems in advance.

However I have a simple proof of truth.

On a decided date, I will publish a problem here and on my github and will wait for the first source code – in comments here or in pull requests – that will solve the problem by correctly implementing the specifications.

Any of the following langauges: Python, F#, C#, C, C++, Java, Haskell, Ruby, Go, Perl, Rust, Kotlin, OCaml, JavaScript (do you need more?).

Let me know if you are willing to accept the challenge.

Whenever you want.

Use more languages, not only one

In math we select the best notation to disentangle the problem in different parts and solve them, this is the correct way to interpret the separation of concerns in software too, it’s not a formal, static approach, but a problem specific, always new discovery. For example, the interesting part is that Bayes formula has a false positive rate that, even if low, can become prevalent when the prior probability is also low! 3blue1brown’s decoupling of the medical test paradox via odds is also cool.

Same concept in my work as programmer:

The users want the ability to select one or more regions and see the results over last n days…
The solution is not haskell but just “normal” stacking charts, the real-world business version of the monoid category, by highcharts javascript.

Now, that’s true in any environment: mobile, web server and desktop apps, see the following single example that includes all them (android open source app for mobile, nginx as web server for rtmp protocol and obs as qt desktop app!) let’s say you want to use your mobile camera as a pc webcam: don’t go with dangerous, expensive, proprietary apps, having high risks for security and privacy.

A free open-source RTMP client for Android on github, Yasea.
It works, I’ve cloned the repo, built it in my Android Studio and tested it for you on my mobile.
How to Setup OBS with NGINX on Windows for RTMP Streaming on Ryan Zehm’s channel.
OBS main tutorial here!