Category Archives: Linguaggi

Linguaggi di programmazione

JavaScript 77 – Tutto sulla programmazione nel browser – 1

Continuo da qui.

Il progetto di un gioco nel browser
My initial fascination with computers, like that of many kids, originated with computer games. I was drawn into the tiny computer-simulated worlds that I could manipulate and in which stories (sort of) unfolded—more, I suppose, because of the way I could project my imagination into them than because of the possibilities they actually offered.

Comincia così il prossimo capitolo di Marijn 🚀 e continua dicendo:

This chapter will walk through the implementation of a simple platform game. Platform games (or “jump and run” games) are games that expect the player to move a figure through a world, which is often two-dimensional and viewed from the side, and do lots of jumping onto and over things.

E il gioco lo fa tutto e rockz 🚀 tutto da giocarci 😊 e studiarlo se si vuole approfondire JavaScript e diventare very über nerd 😊

Siccome è troppo specifico non lo copio, vedetelo di là.

Anche il capitolo successivo, disegnare sul canvas è specialistico; siccome riguarda solo il browser lo vedete di là, vero? 😎

Ebbene sì, sono giunto a qualcosa fuori dal mio mondo, anche se non si è interessati a programmare per il browser sono cose da leggere, perché si usano continuamente. E ormai i nuovi sono tutti sul Web (OK, quasi). Pausa, devo leggere anch’io 😯

:mrgreen:

Fahrenheit to Celsius

Ieri faceva così caldo che non vi dico; proprio da solstizio. In questi casi l’idea di viaggiare con il bus è pessima se capita che i finestrini non si possono aprire e l’impianto di condizionamento non funzioni. A peggiorare il tutto il mio giovane compagno di sventura legge le brekkiniuss sul telefono: in Arizona fa così caldo che gli aerei non possono decollare, 120 gradi Fahrenheit.

Uh! peggio di noi, forse; quanto fa? Velocissimo con una googlata, 48°C.

Ma mi sono preso la rivincita; o almeno ci ho provato. Come fai a passare da una scala all’altra, basta uno script per quella formula semplicissima… 😊

Ora sembra che io sia prevenuto su certe cose come Micro$oft, la scuola, lo zeitgeist tutto ma la soluzione che mi ha prontamente fornito —N.B.: quelli di una certa età deboli di cuore valutino se continuare a leggere, avvisati nèh!— non l’avrei mai immaginata: ha usato un foglio di calcolo, tipo Excel 😯

Io non ero attrezzato al momento ma appena giunti a destinazione l’ho indottrinato, come si deve fare, o si dovrebbe o –almeno– si potrebbe. Basta uno script Bash, con Linux, ovvio.

f2c

#!/bin/bash
if [[ $# -eq 0 ]]; then
    exit 2
fi
    
F=$1
let C="$((($F-32) * 5 / 9))"
echo $F"°F ->" $C"°C"

e per la conversione inversa

c2f

#!/bin/bash
if [[ $# -eq 0 ]]; then
    exit 2
fi
    
C=$1
let F="$(($C * 9 / 5 + 32))"
echo $C"°C ->" $F"°F"

Sì c’è un arrotondamento, si usano gli interi, troncando. Ma volendo essere più precisi ci sono tanti linguaggi –parte lasciata come esercizio 😜 Anche perché qui fa molto caldo 😊

Aggiornamento: l’amico Flavio, the Man from Mars cinguettaGuida per l’Utente del C64 pag. 35. Ai tempi del C64 la conversione °F/°C era già un classico. Il foglio di calcolo è un’esagerazione!
E sì, io sono più vecchio, allora ero alle prese con il Fortran per le stesse cose che adesso vedo e rivedo con Python. Niente C64 ma ho pasticciato con il Vic20 (in Forth).
Tutti d’accordo sull’esagerazione. Non serve Excel, basta VisiCalc 😉

Aggiornamento: lunga conversazione con il giovane amico; ha ragione lui, sono stato parziale, con il telefono mica puoi fare certe cose…
Vero anche che –ma non apriamo un’altra tirata 😊
CMQ (cit.) un modo veloce, disponibile per tutti, al volo:

js-repl
Ah! sembra che la notizia sia confermata.

:mrgreen:

SICP – cap. 2 – Sequenze come interfacce convenzionali – 47 – esercizi

Continuo da qui, copio qui.

Exercise 2.38: The accumulate procedure is also known as fold-right, because it combines the first element of the sequence with the result of combining all the elements to the right. There is also a fold-left, which is similar to fold-right, except that it combines elements working in the opposite direction:

(define (fold-left op initial sequence)
  (define (iter result rest)
    (if (null? rest)
        result
        (iter (op result (car rest))
              (cdr rest))))
  (iter initial sequence))

What are the values of

(fold-right / 1 (list 1 2 3))
(fold-left  / 1 (list 1 2 3))
(fold-right list nil (list 1 2 3))
(fold-left  list nil (list 1 2 3))

Give a property that op should satisfy to guarantee that fold-right and fold-left will produce the same values for any sequence.

Intanto ricopio la procedura accumuate rinominandola fold-right

(define (fold-right op initial sequence)
   (if (null? sequence)
       initial
       (op (car sequence)
           (fold-right op initial (cdr sequence)))))

inoltre in Racket non è definito nil ma null.

Ed ecco:

OK, le due procedure danno risultati diversi. Allora… op dev’essere … proprio come dice Bill the Lizard: The property that will guarantee that fold-right and fold-left will produce the same values for any sequence is commutativity. You may remember the commutative property of both addition and multiplication from algebra. It’s the law that says that: A + B = B + A and A x B = B x A.
Subtraction and division are not commutative operations. The AND and OR operations in Boolean algebra are commutative.


OK anche sicp-ex e Drewiki.

Ripensandoci 😜 Racket ha le due procedure, com’era logico supporre:

Ripensandoci ancora: l’esercizio non è sul Lisp, non è sulla programmazione ma per vedere se l’allievo si applica e ragiona. Cosa che onestamente —ahemmm…– ci sono arrivato solo dopo ore, in viaggio con un caldo da solstizio, afa, condizionatore che non funziona e non si possono abbassare i finestrini. Devo affrontare diversamente SICP, demitizzarlo ma impegnarmi di più; chissà come facevano gli studenti; chissà come fanno adesso 😯

:mrgreen:

JavaScript 76 – gestione degli eventi (nel browser)

Continuo da qui, copio qui.

Some programs work with direct user input, such as mouse and keyboard interaction. The timing and order of such input can’t be predicted in advance. This requires a different approach to control flow than the one we have used so far.

, quasi tutti i programmi funzionano così. Fanno eccezione i comandi da terminale e pochi altri. Qui, seguendo Marijn, qualche cenno, sempre relativo al browser.

Gestori di eventi
Imagine an interface where the only way to find out whether a key on the keyboard is being pressed is to read the current state of that key. To be able to react to keypresses, you would have to constantly read the key’s state so that you’d catch it before it’s released again. It would be dangerous to perform other time-intensive computations since you might miss a keypress.

That is how such input was handled on primitive machines. A step up would be for the hardware or operating system to notice the keypress and put it in a queue. A program can then periodically check the queue for new events and react to what it finds there.

Of course, it has to remember to look at the queue, and to do it often, because any time between the key being pressed and the program noticing the event will cause the software to feel unresponsive. This approach is called polling. Most programmers avoid it whenever possible.

A better mechanism is for the underlying system to give our code a chance to react to events as they occur. Browsers do this by allowing us to register functions as handlers for specific events.

The addEventListener function registers its second argument to be called whenever the event described by its first argument occurs.

Segue una lunga lezione, esaustiva, che non riporto. Al solito –mi ripeto– sto solo vedendo il linguaggio JavaScript per apprenderne le basi. Riporto solo le conclusioni di Marijn 🚀

Event handlers make it possible to detect and react to events we have no direct control over. The addEventListener method is used to register such a handler.

Each event has a type ("keydown", "focus", and so on) that identifies it. Most events are called on a specific DOM element and then propagate to that element’s ancestors, allowing handlers associated with those elements to handle them.

When an event handler is called, it is passed an event object with additional information about the event. This object also has methods that allow us to stop further propagation (stopPropagation) and prevent the browser’s default handling of the event (preventDefault).

Pressing a key fires "keydown", "keypress", and "keyup" events. Pressing a mouse button fires "mousedown", "mouseup", and "click" events. Moving the mouse fires “mousemove” and possibly "mouseenter" and "mouseout" events.

Scrolling can be detected with the "scroll" event, and focus changes can be detected with the "focus" and "blur" events. When the document finishes loading, a “load” event fires on the window.

Only one piece of JavaScript program can run at a time. Thus, event handlers and other scheduled scripts have to wait until other scripts finish before they get their turn.

:mrgreen:

SciPy – 8 – perché e per cosa SciPy

Continuo da qui, copio qui.

Dopo l’esame del corso della prof Karlijn 🚀 e qualche scambio di opinioni con un paio di nerds che usano queste cose (non voglio dire che è colpa|merito loro, nèh!) credo che sia utile un aproccio a SciPy simile a quello adottato per NumPy (&co.). Purtroppo manca Jake 🚀.

Credo che la documentazione ufficiale faccia al mio caso. Proprio dall’introduzione ecco:

SciPy is a collection of mathematical algorithms and convenience functions built on the Numpy extension of Python. It adds significant power to the interactive Python session by providing the user with high-level commands and classes for manipulating and visualizing data. With SciPy an interactive Python session becomes a data-processing and system-prototyping environment rivaling systems such as MATLAB, IDL, Octave, R-Lab, and SciLab.

Due cose da notare secondo me: 1) non è che siano cose che si usano tutti i giorni, anzi solo quando servono, cioè raramente; e 2) c’è MATLAB, si usa quello perché si sta usando da tempo, ci sono le cose già fatte (cioè conosciute) e quello lo conoscono (usano?) tutti. Poi va benissimo (quasi sempre) la versione free Octave. Ne ho parlato in passato, non condivido quest’opinione ma la capisco. Anche perché (non voglio entrare nel dettaglio, sarebbe un discorso lungo) si può usare interattivamente in una GUI davvero funzionale.

E Python sarà anche sexy ma è comunque una cosa da apprendere e certe cose sono nuove 😯

In ogni caso questi posts non sono per nessun altro che per me, per cui parto 😊

Una nota fin da subito, l’usuale convenzione: For brevity and convenience, we will often assume that the main packages (numpy, scipy, and matplotlib) have been imported as:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

L’organizzazione di SciPy
SciPy is organized into subpackages covering different scientific computing domains. These are summarized in the following table:

Subpackage  Description
cluster     Clustering algorithms
constants   Physical and mathematical constants
fftpack     Fast Fourier Transform routines
integrate   Integration and ordinary differential equation solvers
interpolate Interpolation and smoothing splines
io          Input and Output
linalg      Linear algebra
ndimage     N-dimensional image processing
odr         Orthogonal distance regression
optimize    Optimization and root-finding routines
signal      Signal processing
sparse      Sparse matrices and associated routines
spatial     Spatial data structures and algorithms
special     Special functions
stats       Statistical distributions and functions

Scipy sub-packages need to be imported separately, for example:

from scipy import linalg, optimize

Because of their ubiquitousness, some of the functions in these subpackages are also made available in the scipy namespace to ease their use in interactive sessions and programs. In addition, many basic array functions from numpy are also available at the top-level of the scipy package. Before looking at the sub-packages individually, we will first look at some of these common functions.

Trovare documentazione
SciPy and NumPy have documentation versions in both HTML and PDF format available [here], that cover nearly all available functionality. However, this documentation is still work-in-progress and some parts may be incomplete or sparse. As we are a volunteer organization and depend on the community for growth, your participation – everything from providing feedback to improving the documentation and code – is welcome and actively encouraged.

Python’s documentation strings are used in SciPy for on-line documentation. There are two methods for reading them and getting help. One is Python’s command help in the pydoc module. Entering this command with no arguments (i.e. help) launches an interactive help session that allows searching through the keywords and modules available to all of Python. Secondly, running the command help(obj) with an object as the argument displays that object’s calling signature, and documentation string.

The pydoc method of help is sophisticated but uses a pager to display the text. Sometimes this can interfere with the terminal you are running the interactive session within. A numpy/scipy-specific help system is also available under the command numpy.info. The signature and documentation string for the object passed to the help command are printed to standard output (or to a writeable object passed as the third argument). The second keyword argument of numpy.info defines the maximum width of the line for printing. If a module is passed as the argument to help then a list of the functions and classes defined in that module is printed. For example: *** no non sono riuscito a fare l’esempio *** ma c’è la reference guide; per optimize è questa.

:mrgreen:

JavaScript 75 – DOM – Document Object Model

Continuo da qui, copio qui.

When you open a web page in your browser, the browser retrieves the page’s HTML text and parses it. The browser builds up a model of the document’s structure and then uses this model to draw the page on the screen.

This representation of the document is one of the toys that a JavaScript program has available in its sandbox. You can read from the model and also change it. It acts as a live data structure: when it is modified, the page on the screen is updated to reflect the changes.

E di qui Marijn parte a raccontarci tutto (davvero tutto) sulla pagina HTML. Ottimo, da leggere ma non pertinente con questa serie (introduttiva) di JavaScirpt.

Per cui salto dopo riportando solo il

Riepilogo
JavaScript programs may inspect and interfere with the current document that a browser is displaying through a data structure called the DOM. This data structure represents the browser’s model of the document, and a JavaScript program can modify it to change the visible document.

The DOM is organized like a tree, in which elements are arranged hierarchically according to the structure of the document. The objects representing elements have properties such as parentNode and childNodes, which can be used to navigate through this tree.

The way a document is displayed can be influenced by styling, both by attaching styles to nodes directly and by defining rules that match certain nodes. There are many different style properties, such as color or display. JavaScript can manipulate an element’s style directly through its style property.

:mrgreen:

SICP – cap. 2 – Sequenze come interfacce convenzionali – 46 – esercizi

Continuo da qui, copio qui.

Exercise 2.37: Suppose we represent vectors v = (v_i) as sequences of numbers, and matrices m = (m_i j) as sequences of vectors (the rows of the matrix). For example, the matrix

is represented as the sequence ((1 2 3 4) (4 5 6 6) (6 7 8 9)). With this representation, we can use sequence operations to concisely express the basic matrix and vector operations. These operations (which are described in any book on matrix algebra) are the following:

We can define the dot product as

(define (dot-product v w)
  (accumulate + 0 (map * v w)))

Fill in the missing expressions in the following procedures for computing the other matrix operations. (The procedure accumulate-n is defined in Exercise 2.36 [post precedente]):

(define (matrix-*-vector m v)
  (map ⟨??⟩ m))

(define (transpose mat)
  (accumulate-n ⟨??⟩ ⟨??⟩ mat))

(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map ⟨??⟩ m)))

Ricopio le procedure accumulate e accumulate-n

(define (accumulate op initial sequence)
   (if (null? sequence)
       initial
       (op (car sequence)
           (accumulate op initial (cdr sequence)))))

(define (accumulate-n op init seqs)
   (if (null? (car seqs))
       null
       (cons (accumulate op init (map car seqs))
             (accumulate-n op init (map cdr seqs)))))

Applicando accumulate-n ottengo

(define (matrix-*-vector m v)
   (map (lambda (row) (dot-product row v)) m))

transpose è un po’ da pensarci su, vedi Bill (a breve)

(define (transpose mat)
   (accumulate-n cons null mat))

Ancora peggio la moltiplicazione, lo schema dalla Wiki

e –OK, copio Bill– la procedura

(define (matrix-*-matrix m n)
   (let ((cols (transpose n)))
     (map (lambda (row) (matrix-*-vector cols row)) m)))

Raccolgo i codici nel file m2-37.rkt ed ecco

Ho utilizzato il codice di Bill the Lizard, migliore –secondo me– ma OK anche sicp-ex e Drewiki.

:mrgreen:

JavaScript 74 – il browser

Continuo da qui, copio qui.

The browser is a really hostile programming environment.
Douglas Crockford.

The next part of this book will talk about web browsers. Without web browsers, there would be no JavaScript. And even if there were, no one would ever have paid any attention to it.

Vero. Ma vero anche che a me interessa poco la visualizzazione nel browser, questa serie di posts sono introduttivi a JavaScript come linguaggio. Quindi riassumerò il post di Marijn.

Di là trovate una breve sintesi sulle reti, Internet, il TCP, il Web e infine il protocollo HTML.

Dentro il codice HTML ci possono essere script JavaScript, per esempio:

che eseguito nel browser produce:

Such a script will run as soon as its <script> tag is encountered as the browser reads the HTML.

Including large programs directly in HTML documents is often impractical. The <script> tag can be given an src attribute in order to fetch a script file (a text file containing a JavaScript program) from a URL.


The code/hello.js file included here contains the same simple program, alert("hello!"). When an HTML page references other URLs as part of itself, for example an image file or a script—web browsers will retrieve them immediately and include them in the page.

:mrgreen:

SciPy – 7 – autovalori e autovettori

Continuo da qui, copio qui.
Davvero, quella del titolo è la traduzione di eigenvalues and eigenvectors; o almeno credo 😎

The first topic that you will tackle are the eigenvalues and eigenvectors.

Eigenvalues are a new way to see into the heart of a matrix. But before you go more into that, let’s explain first what eigenvectors are. Almost all vectors change direction, when they are multiplied by a matrix. However, certain exceptional, resulting vectors are in the same direction as the vectors that are the result of the multiplication. These are the eigenvectors.

In other words, multiply an eigenvector by a matrix, and the resulting vector of that multiplication is equal to a multiplication of the original eigenvector with λ, the eigenvalue: Ax=λx.

This means that the eigenvalue gives you very valuable information: it tells you whether one of the eigenvectors is stretched, shrunk, reversed, or left unchanged—when it is multiplied by a matrix.

e

You use the eig() function from the linalg SciPy module to solve ordinary or generalized eigenvalue problems for square matrices.

Note that the eigvals() function is another way of unpacking the eigenvalues of a matrix.

When you’re working with sparse matrices, you can fall back on the module scipy.sparse to provide you with the correct functions to find the eigenvalues and eigenvectors: la, v = sparse.linalg.eigs(myMatrix,1).

Note that the code above specifies the number of eigenvalues and eigenvectors that has to be retrieved, namely, 1.

The eigenvalues and eigenvectors are important concepts in many computer vision and machine learning techniques, such as Principal Component Analysis (PCA) for dimensionality reduction and EigenFaces for face recognition.

Singular Value Decomposition (SVD)
Next, you need to know about SVD if you want to really learn data science. The singular value decomposition of a matrix A is the decomposition or facorization of A into the product of three matrices:

The size of the individual matrices is as follows if you know that matrix A is of size M x N:

  • Matrix U is of size M x M
  • Matrix V is of size N x N
  • Matrix Σ is of size M x N

The indicates that the matrices are multiplied and the t that you see in Vt means that the matrix is transposed, which means that the rows and columns are interchanged.

Simply stated, singular value decomposition provides a way to break a matrix into simpler, meaningful pieces. These pieces may contain some data we are interested in.

Al solito, il risultato non è quello atteso 😡

Note that for sparse matrices, you can use the sparse.linalg.svds() function to perform the decomposition.

If you’re new to data science, the matrix decomposition will be quite opaque for you. Ecco, come pure l’esempio che segue per cui non sono attrezzato. Forse il tutorial di Karlijn (rockz) è troppo specialistico per me. Pausa, poi si continua 😊

:mrgreen:

JavaScript 73 – progetto di un linguaggio di programmazione – 8

Continuo da qui, copio qui.

Aggiustare lo scope
Scope si potrebbe tradurre vita o visibilità o chissà come; io sono di una ‘gnuransa encyclopedica, si sa 😡

Currently, the only way to assign a variable a value is define. This construct acts as a way both to define new variables and to give existing ones a new value.

This ambiguity causes a problem. When you try to give a nonlocal variable a new value, you will end up defining a local one with the same name instead. (Some languages work like this by design, but I’ve always found it a silly way to handle scope.)

Add a special form set, similar to define, which gives a variable a new value, updating the variable in an outer scope if it doesn’t already exist in the inner scope. If the variable is not defined at all, throw a ReferenceError (which is another standard error type).

The technique of representing scopes as simple objects, which has made things convenient so far, will get in your way a little at this point. You might want to use the Object.getPrototypeOf function, which returns the prototype of an object. Also remember that scopes do not derive from Object.prototype, so if you want to call hasOwnProperty on them, you have to use this clumsy expression:

Object.prototype.hasOwnProperty.call(scope, name);

This fetches the hasOwnProperty method from the Object prototype and then calls it on a scope object.

Non ci sono riuscito (forse non mi sono applicato abbastanza); ho copiato qui
aggiungendo al file p-egg.js dei post precedenti il seguente codice:

specialForms["set"] = function(args, env) {
  if (args.length != 2 || args[0].type != "word")
    throw new SyntaxError("Bad use of set");
  var varName = args[0].name;
  var value = evaluate(args[1], env);

  for (var scope = env; scope; scope = Object.getPrototypeOf(scope)) {
    if (Object.prototype.hasOwnProperty.call(scope, varName)) {
      scope[varName] = value;
      return value;
    }
  }
  throw new ReferenceError("Setting undefined variable " + varName);
};

dopo l’ultima specialForms.
Ho poi creato il file scope.js:

require("./load.js") ("/p-egg.js");

run("do(define(x, 4),",
    "   define(setx, fun(val, set(x, val))),",
    "   setx(50),",
    "   print(x))");

run("set(quux, true)");

Eseguendolo però non ottengo quanto previsto, ecco il mio risultato

e quello atteso, di Marijn:

:mrgreen: