AWK, grep e oltre: ack

rr1

Continuo da qui la serie di post su AWK. Cioè dovrei ma oggi esco leggermente fuori tema e parlo di ack di cui ignoravo colpevolmente e completamente l’esistenza. Poi –OK, vi racconto.

I file di visto nel Web li conservo in una directory (cartella) perché non si sa mai. Ma cercare qualcosa lì dentro è come cercare il famoso ago nel pagliaio (ma se ti va bene ti può capitare di trovare la figlia del contadino, dice J.H.Comroe).

Ecco io ero alla ricerca di qualcosa che ricordo benissimo di aver citato –forse– ma esaminare tutti i file non è facile. Anche grep si lamenta, scrive righe non pertinenti, esempio:

sre-7

Eppure… possibile che non ci sia un’opzione giusta? Per fortuna c’è Google. E quando hai un problema c’è una probabilità altissima che lo stesso problema l’abbia già avuto qualcun altro più smart di me. Così sono finito su ack.
Può sostituire grep nel 99% dei casi dice il suo autore Andy Lester.
La home di ack non mi è nuova vuoi vedere che… (da verificare).

Insomma, a farla breve l’ho installato con sudo apt install ack-grep ed ecco

s-re8

OK, da scriptare prima di subito (~/bin/sivw):

#!/bin/bash

ack -iR "$1" ~/lab/OKp/visto\ nel\ web/

abilitarlo con con chmod +x e

s-re9

ricordavo perfettamente (kwasy), e pensa te che

s-re10

aprile 2012, ero giovane allora.

Intanto sono in ritardo, ci sono tante altre novità, per esempio adesso si sta svolgendo #RacketCon, tante cose, da raccontare, per adesso un’immagine

emina-torlak

:mrgreen:

Octave – Input e output – VII – 64

nm3

Oggi, proseguendo da qui, concludo il capitolo, copiando qui.

I/O binario
Octave can read and write binary data using the functions fread and fwrite, which are patterned after the standard C functions with the same names. They are able to automatically swap the byte order of integer data and convert among the supported floating point formats as the data are read.

Built-in Function: val = fread (fid)
Built-in Function: val = fread (fid, size)
Built-in Function: val = fread (fid, size, precision)
Built-in Function: val = fread (fid, size, precision, skip)
Built-in Function: val = fread (fid, size, precision, skip, arch)
Built-in Function: [val, count] = fread (...)

Read binary data from the file specified by the file descriptor fid.
The optional argument size specifies the amount of data to read and may be one of
Qui c’è una tabella che definire panicante è riduttivo. Non la riporto; è qui.

Built-in Function: fwrite (fid, data)
Built-in Function: fwrite (fid, data, precision)
Built-in Function: fwrite (fid, data, precision, skip)
Built-in Function: fwrite (fid, data, precision, skip, arch)
Built-in Function: count = fwrite (...)

Write data in binary form to the file specified by the file descriptor fid, returning the number of values count successfully written to the file.
The argument data is a matrix of values that are to be written to the file. The values are extracted in column-major order.
The remaining arguments precision, skip, and arch are optional, and are interpreted as described for fread.
The behavior of fwrite is undefined if the values in data are too large to fit in the specified precision.

o285

Passo qui.

Files temporanei
Sometimes one needs to write data to a file that is only temporary. This is most commonly used when an external program launched from within Octave needs to access data. When Octave exits all temporary files will be deleted, so this step need not be executed manually.

Built-in Function: [fid, name, msg] = mkstemp ("template")
Built-in Function: [fid, name, msg] = mkstemp ("template", delete)

Return the file descriptor fid corresponding to a new temporary file with a unique name created from template.
The last six characters of template must be “XXXXXX” and these are replaced with a string that makes the filename unique. The file is then created with mode read/write and permissions that are system dependent (on GNU/Linux systems, the permissions will be 0600 for versions of glibc 2.0.7 and later). The file is opened in binary mode and with the O_EXCL flag.
If the optional argument delete is supplied and is true, the file will be deleted automatically when Octave exits.
If successful, fid is a valid file ID, name is the name of the file, and msg is an empty string. Otherwise, fid is -1, name is empty, and msg contains a system-dependent error message.

Built-in Function: [fid, msg] = tmpfile ()
Return the file ID corresponding to a new temporary file with a unique name.
The file is opened in binary read/write (“w+b“) mode and will be deleted automatically when it is closed or when Octave exits.
If successful, fid is a valid file ID and msg is an empty string. Otherwise, fid is -1 and msg contains a system-dependent error message.

Built-in Function: fname = tempname ()
Built-in Function: fname = tempname (dir)
Built-in Function: fname = tempname (dir, prefix)

Return a unique temporary file name as a string.
If prefix is omitted, a value of “oct-” is used.
If dir is also omitted, the default directory for temporary files (P_tmpdir) is used. If dir is provided, it must exist, otherwise the default directory for temporary files is used.
Programming Note: Because the named file is not opened by tempname, it is possible, though relatively unlikely, that it will not be available by the time your program attempts to open it. If this is a concern, see tmpfile.

Function File: dir = tempdir ()
Return the name of the host system’s directory for temporary files.
The directory name is taken first from the environment variable TMPDIR. If that does not exist the system default returned by P_tmpdir is used.

Built-in Function: P_tmpdir ()
Return the name of the host system’s default directory for temporary files.
Programming Note: The value returned by P_tmpdir is always the default location. This value may not agree with that returned from tempdir if the user has overridden the default with the TMPDIR environment variable.

Avanti, qui.

End of file ed errori
Once a file has been opened its status can be acquired. As an example the feof functions determines if the end of the file has been reached. This can be very useful when reading small parts of a file at a time. The following example shows how to read one line at a time from a file until the end has been reached.

o286.png

notare l’errore: fid cessa di esistere alla chiusura del file.

Note that in some situations it is more efficient to read the entire contents of a file and then process it, than it is to read it line by line. This has the potential advantage of removing the loop in the above code.

Built-in Function: status = feof (fid)
Return 1 if an end-of-file condition has been encountered for the file specified by file descriptor fid and 0 otherwise.
Note that feof will only return 1 if the end of the file has already been encountered, not if the next read operation will result in an end-of-file condition.

Built-in Function: msg = ferror (fid)
Built-in Function: [msg, err] = ferror (fid)
Built-in Function: [dots] = ferror (fid, "clear")

Query the error status of the stream specified by file descriptor fid.
If an error condition exists then return a string msg describing the error. Otherwise, return an empty string “”.
The second input "clear" is optional. If supplied, the error state on the stream will be cleared.
The optional second output is a numeric indication of the error status. err is 1 if an error condition has been encountered and 0 otherwise.
Note that ferror indicates if an error has already occurred, not whether the next operation will result in an error condition.

Built-in Function: fclear (fid)
Clear the stream state for the file specified by the file descriptor fid.

Built-in Function: freport ()
Print a list of which files have been opened, and whether they are open for reading, writing, or both.

o287

Avanti ancora, qui.

Posizione nel file
Three functions are available for setting and determining the position of the file pointer for a given file.

Built-in Function: pos = ftell (fid)
Return the position of the file pointer as the number of characters from the beginning of the file specified by file descriptor fid.

Built-in Function: fseek (fid, offset)
Built-in Function: fseek (fid, offset, origin)
Built-in Function: status = fseek (...)

Set the file pointer to the location offset within the file fid.
The pointer is positioned offset characters from the origin, which may be one of the predefined variables SEEK_CUR (current position), SEEK_SET (beginning), or SEEK_END (end of file) or strings "cof", "bof" or "eof". If origin is omitted, SEEK_SET is assumed. offset may be positive, negative, or zero but not all combinations of origin and offset can be realized.

Built-in Function: SEEK_SET ()
Built-in Function: SEEK_CUR ()
Built-in Function: SEEK_END ()

Return the numerical value to pass to fseek to perform one of the following actions:

  • SEEK_SET Position file relative to the beginning.
  • SEEK_CUR Position file relative to the current position.
  • SEEK_END Position file relative to the end.

Built-in Function: frewind (fid)
Built-in Function: status = frewind (fid)
Move the file pointer to the beginning of the file specified by file descriptor fid.
frewind returns 0 for success, and -1 if an error is encountered. It is equivalent to fseek (fid, 0, SEEK_SET).

The following example stores the current file position in the variable marker, moves the pointer to the beginning of the file, reads four characters, and then returns to the original position.

o288

:mrgreen:

SICP – cap. 1 – costruire procedure usando lambda – 41

sittingbull

Continuo da qui a copiare, qui.

In using sum as in section 1.3.1 [qui], it seems terribly awkward to have to define trivial procedures such as pi-term and pi-next just so we can use them as arguments to our higher-order procedure. Rather than define pi-next and pi-term, it would be more convenient to have a way to directly specify “the procedure that returns its input incremented by 4” and “the procedure that returns the reciprocal of its input times its input plus 2.” We can do this by introducing the special form lambda, which creates procedures. Using lambda we can describe what we want as

(lambda (x) (+ x 4))

and

(lambda (x) (/ 1.0 (* x (+ x 2))))

Then our pi-sum procedure can be expressed without defining any auxiliary procedures as

(define (pi-sum a b)
  (sum (lambda (x) (/ 1.0 (* x (+ x 2))))
       a
       (lambda (x) (+ x 4))
       b))

Again using lambda, we can write the integral procedure without having to define the auxiliary procedure add-dx:

(define (integral f a b dx)
  (* (sum f
          (+ a (/ dx 2.0))
          (lambda (x) (+ x dx))
          b)
     dx))

In general, lambda is used to create procedures in the same way as define, except that no name is specified for the procedure:

(lambda (<formal-parameters>) <body>)

The resulting procedure is just as much a procedure as one that is created using define. The only difference is that it has not been associated with any name in the environment. In fact,

(define (plus4 x) (+ x 4))

is equivalent to

(define plus4 (lambda (x) (+ x 4)))

We can read a lambda expression as follows:

    (lambda             (x)             (+    x     4))
 the procedure   of an argument x  that adds  x and 4

Like any expression that has a procedure as its value, a lambda expression can be used as the operator in a combination such as

s85

or, more generally, in any context where we would normally use a procedure name.

Note: It would be clearer and less intimidating to people learning Lisp if a name more obvious than lambda, such as make-procedure, were used. But the convention is firmly entrenched. The notation is adopted from the λ calculus, a mathematical formalism introduced by the mathematical logician Alonzo Church (1941). Church developed the calculus to provide a rigorous foundation for studying the notions of function and function application. The calculus has become a basic tool for mathematical investigations of the semantics of programming languages.

Cosa che può generare lollismi come questo: ecco come indicare il doppio di x

doppio

:mrgreen:

Visto nel Web – 253

Quasi autunno, pioviggina me c’è il sole, sono in ritardo ma ecco un’altra puntata di cosa ho visto nel Web.

image_003

IoT proliferation and unchecked data collection may lead to a storm of class action lawsuits
#:Web, Internet
::: Techmeme

EU Finance Ministers Line Up Behind $21B Tax Ruling Against Apple
#:ditte
::: Slashdot

Stibitz demonstrates remote computing, September 11, 1940
#:storia
::: EDN

Jimu, il robot giocattolo da costruire e programmare
#:games
::: Genjuro75

Let’s Build A Simple Interpreter
dieci post che vi faranno di voi un Dijkstra –o quasi
#:linguaggi di programmazione
::: Ruslan Spivak

clxytrhwkaalwn

Ecco come partire da buoni propositi per garantirsi l’alibi di imbavagliare la rete
#:censura
::: giowile

ACLU Is Launching A Campaign To Convince President Obama To Pardon Edward Snowden
#:sicurezza, spionaggio
::: Slashdot ::: manteblog

European Copyright Ruling Ushers in New Dark Era for Hyperlinks
#:copyright
::: Electronic Frontier Foundation

Printing, cosa cambia dopo l’acquisizione Hp/Samsung
#:ditte
::: TechWeekEurope

New programming language Milk delivers 4x speedups for parallel computing
#:linguaggi di programmazione
::: MIT_CSAIL

14264259_856914594441708_3561104718814119994_n

X-ray reading: imaging method lets you read words through closed books
#:innovazioni, futuro
::: MIT_CSAIL

We’ve signed a letter w/ 24 orgs expressing concern over EC’s #copyright proposal
#:copyright
::: EDiMA_EU

Pokemon Go’s Paying Population Drops By 79% — Still Most Profitable Mobile App In The US
#:dispositivi mobili #:games
::: Slashdot

Edward Snowden Makes ‘Moral’ Case For Presidential Pardon
#:sicurezza, spionaggio
::: Slashdot

Stanford Engineers Propose A Technology To Break The Net Neutrality Deadlock
#:Web, Internet
::: Slashdot

ritchie

Introduction to C Memory Management and C++ Object-Oriented Programming
se del caso prendetevela con b3h3m0th
#:linguaggi di programmazione
::: b3h3m0th

Learning systems programming with Rust
anche per questo
#:linguaggi di programmazione
::: b3h3m0th

Someone Is Learning How To Take Down the Internet, Warns Bruce Schneier
#:Web, Internet #:sicurezza, spionaggio
::: Slashdot

It’s Not Just Wells Fargo – How Sales Targets Can Encourage Wrongdoing
#:sicurezza, spionaggio
::: Slashdot

Why I’m dropping Rust
Rust è giovane; ci sono ancora cose da risolvere ma imho promette bene
#:linguaggi di programmazione
::: hackernoon

csksvlww8aew0zi

The Little C Function From Hell
bugs
#:programming, codice, snippet
::: Embedded in Academia

3 open source alternatives to PowerPoint
#:free open source software
::: rewasp1973

Put the last command’s run time in your Bash prompt
un’idea (può servire in certi casi, non sempre, imho)
#:programming, codice, snippet
::: Jake McCrary

Assange, la Svezia conferma mandato d’arresto per stupro
#:sicurezza, spionaggio
::: la Stampa

14264088_1689862091340561_8096402102930271502_n

Libero e salvo a sua insaputa
forse è solo una parabola ma OK lo stesso. E potrebbe capitare anche a te (forse, se non fai attenzione)😉
#:virus
::: Tech Economy

Why the Apple II ProDOS 2.4 Release is the OS News of the Year
#:sistemi operativi
::: Jason Scott

F*dging up a Racket
cosa non si potrebbe fare con Racket! ci vorrebbe tanto tempo e spirito d’avventura; fossi giovane…😀
#:lisp e derivati
::: hashcollision

La bellezza non salva il mondo, se crea i Crepet
no niente tag; non posso scrivere quello che penso di certi rinkos
::: Il nuovo mondo di Galatea

left382016

Octave – Input e output – VI – 63

btf2

Continuando da qui copio qui.

Input formattato

Octave provides the scanf, fscanf, and sscanf functions to read formatted input. There are two forms of each of these functions. One can be used to extract vectors of data from a file, and the other is more ‘C-like’.

Built-in Function: [val, count, errmsg] = fscanf (fid, template, size)
Built-in Function: [v1, v2, ..., count, errmsg] = fscanf (fid, template, "C")

In the first form, read from fid according to template, returning the result in the matrix val.

The optional argument size specifies the amount of data to read and may be one of

  • Inf Read as much as possible, returning a column vector.
  • nr Read up to nrelements, returning a column vector.
  • [nr, Inf] Read as much as possible, returning a matrix with nr rows. If the number of elements read is not an exact multiple of nr, the last column is padded with zeros.
  • [nr, nc] Read up to nr * nc elements, returning a matrix with nr rows. If the number of elements read is not an exact multiple of nr, the last column is padded with zeros.

If size is omitted, a value of Inf is assumed.
A string is returned if template specifies only character conversions.
The number of items successfully read is returned in count.
If an error occurs, errmsg contains a system-dependent error message.
In the second form, read from fid according to template, with each conversion specifier in template corresponding to a single scalar return value. This form is more “C-like”, and also compatible with previous versions of Octave. The number of successful conversions is returned in count.
See the Formatted Input section of the GNU Octave manual for a complete description of the syntax of the template string.

fscanf non si comporta esattamente come ci si aspetterebbe; ecco un esempio preso dalla documentazione di Matlab.

o283

%i (o %d) vengono promossi😦

Built-in Function: [val, count, errmsg] = scanf (template, size)
Built-in Function: [v1, v2, ..., count, errmsg]] = scanf (template, "C")

This is equivalent to calling fscanf with fid = stdin.
It is currently not useful to call scanf in interactive programs.

Built-in Function: [val, count, errmsg, pos] = sscanf (string, template, size)
Built-in Function: [v1, v2, ..., count, errmsg] = sscanf (string, template, "C")

This is like fscanf, except that the characters are taken from the string string instead of from a stream.
Reaching the end of the string is treated as an end-of-file condition. In addition to the values returned by fscanf, the index of the next character to be read is returned in pos.
Calls to scanf are superficially similar to calls to printf in that arbitrary arguments are read under the control of a template string. While the syntax of the conversion specifications in the template is very similar to that for printf, the interpretation of the template is oriented more towards free-format input and simple pattern matching, rather than fixed-field formatting. For example, most scanf conversions skip over any amount of “white space” (including spaces, tabs, and newlines) in the input file, and there is no concept of precision for the numeric input conversions as there is for the corresponding output conversions. Ordinarily, non-whitespace characters in the template are expected to match characters in the input stream exactly.
When a matching failure occurs, scanf returns immediately, leaving the first non-matching character as the next character to be read from the stream, and scanf returns all the items that were successfully converted.
The formatted input functions are not used as frequently as the formatted output functions. Partly, this is because it takes some care to use them properly. Another reason is that it is difficult to recover from a matching error.

Avanti, qui.

Sintassi per l’input
A scanf template string is a string that contains ordinary multibyte characters interspersed with conversion specifications that start with ‘%’.
Any whitespace character in the template causes any number of whitespace characters in the input stream to be read and discarded. The whitespace characters that are matched need not be exactly the same whitespace characters that appear in the template string. For example, write ‘ , ’ in the template to recognize a comma with optional whitespace before and after.
Other characters in the template string that are not part of conversion specifications must match characters in the input stream exactly; if this is not the case, a matching failure occurs.
The conversion specifications in a scanf template string have the general form:

  • % flags width type conversion
    In more detail, an input conversion specification consists of an initial ‘%’ character followed in sequence by:
  • An optional flag character ‘*’, which says to ignore the text read for this specification. When scanf finds a conversion specification that uses this flag, it reads input as directed by the rest of the conversion specification, but it discards this input, does not return any value, and does not increment the count of successful assignments.
  • An optional decimal integer that specifies the maximum field width. Reading of characters from the input stream stops either when this maximum is reached or when a non-matching character is found, whichever happens first. Most conversions discard initial whitespace characters, and these discarded characters don’t count towards the maximum field width. Conversions that do not discard initial whitespace are explicitly documented.
  • An optional type modifier character. This character is ignored by Octave’s scanf function, but is recognized to provide compatibility with the C language scanf.
    A character that specifies the conversion to be applied.

The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they allow.

Passo qui.
Numeric Input Conversions
Tabella delle conversioni per l’input
Here is a table that summarizes the various conversion specifications:

  • %d’ Matches an optionally signed integer written in decimal.  See Numeric Input Conversions.
    %i’ Matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant. See Numeric Input Conversions.
  • %o’ Matches an unsigned integer written in octal radix. See Numeric Input Conversions.
  • %u’ Matches an unsigned integer written in decimal radix. See Numeric Input Conversions.
  • %x’, ‘%X’ Matches an unsigned integer written in hexadecimal radix. See Numeric Input Conversions.
  • %e’, ‘%f’, ‘%g’, ‘%E’, ‘%G’ Matches an optionally signed floating-point number. See Numeric Input Conversions.
  • %s’ Matches a string containing only non-whitespace characters. See String Input Conversions.
    %c’ Matches a string of one or more characters; the number of characters read is controlled by the maximum field width given for the conversion. See String Input Conversions.
  • %%’ This matches a literal ‘%’ character in the input stream. No corresponding argument is used.

If the syntax of a conversion specification is invalid, the behavior is undefined. If there aren’t enough function arguments provided to supply addresses for all the conversion specifications in the template strings that perform assignments, or if the arguments are not of the correct types, the behavior is also undefined. On the other hand, extra arguments are simply ignored.

Avanti, qui.

Conversioni per l’input di numeri
This section describes the scanf conversions for reading numeric values.
The ‘%d’ conversion matches an optionally signed integer in decimal radix.

The ‘%i’ conversion matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant.
For example, any of the strings ‘10’, ‘0xa’, or ‘012’ could be read in as integers under the ‘%i’ conversion. Each of these specifies a number with decimal value 10.
The ‘%o’, ‘%u’, and ‘%x’ conversions match unsigned integers in octal, decimal, and hexadecimal radices, respectively.
The ‘%X’ conversion is identical to the ‘%x’ conversion. They both permit either uppercase or lowercase letters to be used as digits.
Unlike the C language scanf, Octave ignores the ‘h’, ‘l’, and ‘L’ modifiers.

E infine qui

Conversioni per l’input di stringhe
This section describes the scanf input conversions for reading string and character values: ‘%s’ and ‘%c’.
The ‘%c’ conversion is the simplest: it matches a fixed number of characters, always. The maximum field with says how many characters to read; if you don’t specify the maximum, the default is 1. This conversion does not skip over initial whitespace characters. It reads precisely the next n characters, and fails if it cannot get that many.
The ‘%s’ conversion matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something. Example:

o284

uhmmm… non esattamente come previsto; differenza di versione? o c’è qualcosa che mi sfugge?👿

In pratica però probabilmente questi casi non si devono affrontare (spero)😉

:mrgreen:

Octave – Input e output – V – 62

ck4

Sempre avanti, da qui; oggi copio qui.

Scrivere interi
This section describes the options for the ‘%d’, ‘%i’, ‘%o’, ‘%u’, ‘%x’, and ‘%X’ conversion specifications. These conversions print integers in various formats.
The ‘%d’ and ‘%i’ conversion specifications both print an numeric argument as a signed decimal number; while ‘%o’, ‘%u’, and ‘%x’ print the argument as an unsigned octal, decimal, or hexadecimal number (respectively). The ‘%X’ conversion specification is just like ‘%x’ except that it uses the characters ‘ABCDEF’ as digits instead of ‘abcdef’.

The following flags are meaningful:

  • -’ Left-justify the result in the field (instead of the normal right-justification).
  • +’ For the signed ‘%d’ and ‘%i’ conversions, print a plus sign if the value is positive.
  • ’ For the signed ‘%d’ and ‘%i’ conversions, if the result doesn’t start with a plus or minus sign, prefix it with a space character instead. Since the ‘+’ flag ensures that the result includes a sign, this flag is ignored if you supply both of them.
  • #’ For the ‘%o’ conversion, this forces the leading digit to be ‘0’, as if by increasing the precision. For ‘%x’ or ‘%X’, this prefixes a leading ‘0x’ or ‘0X’ (respectively) to the result. This doesn’t do anything useful for the ‘%d’, ‘%i’, or ‘%u’ conversions.
  • 0’ Pad the field with zeros instead of spaces. The zeros are placed after any indication of sign or base. This flag is ignored if the ‘-’ flag is also specified, or if a precision is specified.

If a precision is supplied, it specifies the minimum number of digits to appear; leading zeros are produced if necessary. If you don’t specify a precision, the number is printed with as many digits as it needs. If you convert a value of zero with an explicit precision of zero, then no characters at all are produced.

0278

Passo qui.

Scrivere floating-points
This section discusses the conversion specifications for floating-point numbers: the ‘%f’, ‘%e’, ‘%E’, ‘%g’, and ‘%G’ conversions.
The ‘%f’ conversion prints its argument in fixed-point notation, producing output of the form [-]ddd.ddd, where the number of digits following the decimal point is controlled by the precision you specify.
The ‘%e’ conversion prints its argument in exponential notation, producing output of the form [-]d.ddde[+|-]dd. Again, the number of digits following the decimal point is controlled by the precision. The exponent always contains at least two digits. The ‘%E’ conversion is similar but the exponent is marked with the letter ‘E’ instead of ‘e’.
The ‘%g’ and ‘%G’ conversions print the argument in the style of ‘%e’ or ‘%E’ (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the ‘%f’ style. Trailing zeros are removed from the fractional portion of the result and a decimal-point character appears only if it is followed by a digit.

The following flags can be used to modify the behavior:

  • -’ Left-justify the result in the field. Normally the result is right-justified.
  • +’ Always include a plus or minus sign in the result.
  • ’ If the result doesn’t start with a plus or minus sign, prefix it with a space instead. Since the ‘+’ flag ensures that the result includes a sign, this flag is ignored if you supply both of them.
  • #’ Specifies that the result should always include a decimal point, even if no digits follow it. For the ‘%g’ and ‘%G’ conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed.
  • 0’ Pad the field with zeros instead of spaces; the zeros are placed after any sign. This flag is ignored if the ‘-’ flag is also specified.

o279

e

o280

Avanti, qui.

Altre specifiche di output
This section describes miscellaneous conversions for printf.
The ‘%c’ conversion prints a single character. The ‘-’ flag can be used to specify left-justification in the field, but no other flags are defined, and no precision or type modifier can be given. For example:

o281

The ‘%s’ conversion prints a string. The corresponding argument must be a string. A precision can be specified to indicate the maximum number of characters to write; otherwise characters in the string up to but not including the terminating null character are written to the output stream. The ‘-’ flag can be used to specify left-justification in the field, but no other flags or type modifiers are defined for this conversion. For example:

o282

Note the leading and trailing spaces.
Uhmmm… i trailings non si vedono ma ci sono per davvero. Ho inoltre aggiunto in questi esempi un a-capo per questioni estetiche.

:mrgreen:

cit. & loll – 9

Yep😀 ecco qui

csoy-6tuaaauqz6-jpg-large

This is, perhaps, the shittiest thing I’ve seen in tech for years
::: lambdista

this is awesome, chapter 3
::: akosma

Features Of The New iPhone 7
::: The Onion

if you give a man a package, he’ll run it for a day
::: olix0r

I made a website to explain how to get yourself out of your git messes in plain english
::: ksylor

lorenzin

la Ministra Beatrice Lorenzin

#procrastination
::: therocksuckers

The difference between these magazine covers is why our movement exists
forza ragazze!!!
::: GirlsWhoCode

println(💩)
::: ThePracticalDev

Ein #Lisp Buch mit Zitate aus Goethes Faust. Ha!
sì, mi sono fatto aiutare da Bing😉
::: RainerJoswig

#perdire
non fatelo nèh!
::: rewasp1973

csjbtu0wcaaeoyz

Quando morirò spargete
::: ailgamar

There are only two kinds of languages
::: alienoid

Do your work as though you had a thousand years to live and as if you were to die tomorrow
::: alienoid

Whenever I hear an R advocate criticize matplotlib
::: jakevdp

Twitter in 1934. A marconigramma… by Marconi
::: dogheria

ufo

Ecco come partire da buoni propositi per garantirsi l’alibi di imbavagliare la rete
::: giowile

Kudos to the clang-analyzer team for creating a static analyzer for C++ that’s free and super-painless to use
da indagare
::: obiltschnig

You can’t accurately describe how complicated the global economy is. …
::: wallingf

Tanto per farvi capire quant’è fottuto questo mondo: AdBlock inizierà a vendere pubblicità
::: TristeMietitore

#Snowden shocked the world, prompted most thorough reconsideration of US intelligence law and policy in decades
::: hrw

How Texas personalizes supercomputing
::: climagic

14333173_813193468817356_2260921448673796949_n

Octave – Input e output – IV – 61

folon

Continuo da qui, copio qui.

Output formattato

This section describes how to call printf and related functions.
The following functions are available for formatted output. They are modeled after the C language functions of the same name, but they interpret the format template differently in order to improve the performance of printing vector and matrix values.
Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., “\n” => newline) are expanded even when the template string is defined with single quotes.

Built-in Function: printf (template, ...)
Print optional arguments under the control of the template string template to the stream stdout and return the number of characters printed.
See the Formatted Output section of the GNU Octave manual for a complete description of the syntax of the template string.
Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., “\n” => newline) are expanded even when the template string is defined with single quotes.

Built-in Function: fprintf (fid, template, ...)
Built-in Function: fprintf (template, ...)
Built-in Function: numbytes = fprintf (...)

This function is equivalent to printf, except that the output is written to the file descriptor fid instead of stdout.
If fid is omitted, the output is written to stdout making the function exactly equivalent to printf.
The optional output returns the number of bytes written to the file.
Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., “\n” => newline) are expanded even when the template string is defined with single quotes.

Built-in Function: sprintf (template, ...)
This is like printf, except that the output is returned as a string.
Unlike the C library function, which requires you to provide a suitably sized string as an argument, Octave’s sprintf function returns the string, automatically sized to hold all of the items converted.
Implementation Note: For compatibility with MATLAB, escape sequences in the template string (e.g., “\n” => newline) are expanded even when the template string is defined with single quotes.

The printf function can be used to print any number of arguments. The template string argument you supply in a call provides information not only about the number of additional arguments, but also about their types and what style should be used for printing them.
Ordinary characters in the template string are simply written to the output stream as-is, while conversion specifications introduced by a ‘%’ character in the template cause subsequent arguments to be formatted and written to the output stream. For example,

o275

This example shows the use of the ‘%d’ conversion to specify that a scalar argument should be printed in decimal notation, the ‘%s’ conversion to specify printing of a string argument, and the ‘%%’ conversion to print a literal ‘%’ character.
There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (‘%o’, ‘%u’, or ‘%x’, respectively); or as a character value (‘%c’).
Floating-point numbers can be printed in normal, fixed-point notation using the ‘%f’ conversion or in exponential notation using the ‘%e’ conversion. The ‘%g’ conversion uses either ‘%e’ or ‘%f’ format, depending on what is more appropriate for the magnitude of the particular number.
You can control formatting more precisely by writing modifiers between the ‘%’ and the character that indicates which conversion to apply. These slightly alter the ordinary behavior of the conversion. For example, most conversion specifications permit you to specify a minimum field width and a flag indicating whether you want the result left- or right-justified within the field.
The specific flags and modifiers that are permitted and their interpretation vary depending on the particular conversion. They’re all described in more detail in the following sections.

Avanti, qui.

Output di matrici
When given a matrix value, Octave’s formatted output functions cycle through the format template until all the values in the matrix have been printed. For example:

o276

If more than one value is to be printed in a single call, the output functions do not return to the beginning of the format template when moving on from one value to the next. This can lead to confusing output if the number of elements in the matrices are not exact multiples of the number of conversions in the format template. For example:

o277

If this is not what you want, use a series of calls instead of just one.

Avanti, qui.

Sintassi di conversione di output
This section provides details about the precise syntax of conversion specifications that can appear in a printf template string.
Characters in the template string that are not part of a conversion specification are printed as-is to the output stream.
The conversion specifications in a printf template string have the general form:

% flags width [ . precision ] type conversion

For example, in the conversion specifier ‘%-10.8ld’, the ‘-’ is a flag, ‘10’ specifies the field width, the precision is ‘8’, the letter ‘l’ is a type modifier, and ‘d’ specifies the conversion style. (This particular type specifier says to print a numeric argument in decimal notation, with a minimum of 8 digits left-justified in a field at least 10 characters wide.)

In more detail, output conversion specifications consist of an initial ‘%’ character followed in sequence by:

  • Zero or more flag characters that modify the normal behavior of the conversion specification.
  • An optional decimal integer specifying the minimum field width. If the normal conversion produces fewer characters than this, the field is padded with spaces to the specified width. This is a minimum value; if the normal conversion produces more characters than this, the field is not truncated. Normally, the output is right-justified within the field.
    You can also specify a field width of ‘*’. This means that the next argument in the argument list (before the actual value to be printed) is used as the field width. The value is rounded to the nearest integer. If the value is negative, this means to set the ‘-’ flag (see below) and to use the absolute value as the field width.
  • An optional precision to specify the number of digits to be written for the numeric conversions. If the precision is specified, it consists of a period (‘.’) followed optionally by a decimal integer (which defaults to zero if omitted).
    You can also specify a precision of ‘*’. This means that the next argument in the argument list (before the actual value to be printed) is used as the precision. The value must be an integer, and is ignored if it is negative.
  • An optional type modifier character. This character is ignored by Octave’s printf function, but is recognized to provide compatibility with the C language printf.
  • A character that specifies the conversion to be applied.

The exact options that are permitted and how they are interpreted vary between the different conversion specifiers.
Ci vorrebbe la tabella riassuntiva… sta arrivando😉

Avanti, qui.

Tabella Delle conversioni di output
Here is a table summarizing what all the different conversions do:

  • %d’, ‘%i’ Print an integer as a signed decimal number. See Integer Conversions, for details. ‘%d’ and ‘%i’ are synonymous for output, but are different when used with scanf for input (see Table of Input Conversions).
  • %o’ Print an integer as an unsigned octal number. See Integer Conversions, for details.
  • %u’ Print an integer as an unsigned decimal number. See Integer Conversions, for details.
  • %x’, ‘%X’ Print an integer as an unsigned hexadecimal number. ‘%x’ uses lowercase letters and ‘%X’ uses uppercase. See Integer Conversions, for details.
  • %f’ Print a floating-point number in normal (fixed-point) notation. See Floating-Point Conversions, for details.
  • %e’, ‘%E’ Print a floating-point number in exponential notation. ‘%e’ uses lowercase letters and ‘%E’ uses uppercase. See Floating-Point Conversions, for details.
  • %g’, ‘%G’ Print a floating-point number in either normal (fixed-point) or exponential notation, whichever is more appropriate for its magnitude. ‘%g’ uses lowercase letters and ‘%G’ uses uppercase. See Floating-Point Conversions, for details.
  • %c’ Print a single character. See Other Output Conversions.
  • %s’ Print a string. See Other Output Conversions.
  • %%’ Print a literal ‘%’ character. See Other Output Conversions.

Nota: gli URL indicati in tabella si trovano anche nel prossimo post.

If the syntax of a conversion specification is invalid, unpredictable things will happen, so don’t do this. In particular, MATLAB allows a bare percentage sign ‘%’ with no subsequent conversion character. Octave will emit an error and stop if it sees such code. When the string variable to be processed cannot be guaranteed to be free of potential format codes it is better to use the two argument form of any of the printf functions and set the format string to %s. Alternatively, for code which is not required to be backwards-compatible with MATLAB the Octave function puts or disp can be used.

printf (strvar);        # Unsafe if strvar contains format codes
printf ("%s", strvar);  # Safe
puts (strvar);          # Safe

If there aren’t enough function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are unpredictable. If you supply more arguments than conversion specifications, the extra argument values are simply ignored; this is sometimes useful.

:mrgreen:

AWK e grep – qualche precisazione

fermat

La raccolta di script AWK pare sia piaciuta. Forse continua, ho ancora materiale, prossimamente… forse…

Ma subito una risposta veloce per un caso trattato superficialmente, questo:

Scrive solo le righe con una regex specificata
awk '/questo/'

OK, ammetto che sono stato troppo superficiale. Integro ma mi riservo una nota finale.

Userò per gli esempi il file txt, questo

uno
due
questo e quello
questa
questo
quella
quello
(5)
otto
ot to
ottantotto

Ed ecco:

s-re1

In alternativa si può usare grep

s-re2

Simili, come si vede, con grep si omettono gli /, la regex trovata viene colorata per via dell’alias

alias grep='grep --color=auto'

grep ha inoltre l’opzione -i per cercare ignorando la differenza tra maiuscole e minuscole, cosa che con AWK (vedi post linkato) è più macchinosa.

Apici o virgolette possono essere omessi in casi normali

s-re3

ma ci sono eccezioni:

s-re4

In alternativa è possibile escapare le parentesi con \ che trasforma il carattere seguente da speciale a normale (letterale).

s-re5

Tranne casi particolari (mai dire mai) mi sembra meno intuitivo.

Resta un grosso argomento da affrontare: le espressioni regolari, regexs o RE. Su di loro sono stati scritti volumi, versati barili d’inchiostro. E io faccio spesso qualche tentativo prima di ottenere quello che voglio.

Nella pagina di raccolta di manuali su questo blog trovate almeno un link minaccioso (dovrei aggiornarla), qui.

In generale mi sembra che questo caso sia meglio usare grep, ma chissà…
Un esempio vero, mio. Per compilare le telenovelas “Visto nel Web” e “cit. & loll” devo indicare l’URL della pagina linkata. Ogni URL è poi collegato a un sito; per sapere se l’ho già memorizzato uso questo script:

s-re6

Infine, tornando ai posts su AWK: sono un punto di partenza …

Aggiornamento
Ho aggiunto 2 tutorials e un quick reference per le espressioni regolari sulla pagina dei manuali. Altro materiale è disponibile online ma non so quanto regolare (inteso come rispettoso dei diriti degli autori).

:mrgreen:

Octave – Input e output – III – 60

mind-evolved

Continuo copiando qui.

Funzioni di I/O come nel C

Octave’s C-style input and output functions provide most of the functionality of the C programming language’s standard I/O library. The argument lists for some of the input functions are slightly different, however, because Octave has no way of passing arguments by reference.
In the following, file refers to a file name and fid refers to an integer file number, as returned by fopen.
There are three files that are always available. Although these files can be accessed using their corresponding numeric file ids, you should always use the symbolic names given in the table below, since it will make your programs easier to understand.

Built-in Function: stdin ()
Return the numeric value corresponding to the standard input stream.
When Octave is used interactively, stdin is filtered through the command line editing functions.

Built-in Function: stdout ()
Return the numeric value corresponding to the standard output stream.
Data written to the standard output is normally filtered through the pager.

Built-in Function: stderr ()
Return the numeric value corresponding to the standard error stream.
Even if paging is turned on, the standard error is not sent to the pager. It is useful for error messages and prompts.

Avanti, qui.

Aprire e chiudere files
When reading data from a file it must be opened for reading first, and likewise when writing to a file. The fopen function returns a pointer to an open file that is ready to be read or written. Once all data has been read from or written to the opened file it should be closed. The fclose function does this. The following code illustrates the basic pattern for writing to a file, but a very similar pattern is used when reading a file.

filename = "myfile.txt";
fid = fopen (filename, "w");
# Do the actual I/O here... (write in this case)
fclose (fid);

Built-in Function: fid = fopen (name)
Built-in Function: fid = fopen (name, mode)
Built-in Function: fid = fopen (name, mode, arch)
Built-in Function: [fid, msg] = fopen (...)
Built-in Function: fid_list = fopen ("all")
Built-in Function: [file, mode, arch] = fopen (fid)

Open a file for low-level I/O or query open files and file descriptors.
The first form of the fopen function opens the named file with the specified mode (read-write, read-only, etc.) and architecture interpretation (IEEE big endian, IEEE little endian, etc.), and returns an integer value that may be used to refer to the file later. If an error occurs, fid is set to -1 and msg contains the corresponding system error message. The mode is a one or two character string that specifies whether the file is to be opened for reading, writing, or both.
The second form of the fopen function returns a vector of file ids corresponding to all the currently open files, excluding the stdin, stdout, and stderr streams.
The third form of the fopen function returns information about the open file given its file id.
For example, myfile = fopen ("splat.dat", "r", "ieee-le"); opens the file splat.dat for reading. If necessary, binary numeric values will be read assuming they are stored in IEEE format with the least significant bit first, and then converted to the native representation.
Opening a file that is already open simply opens it again and returns a separate file id. It is not an error to open a file several times, though writing to the same file through several different file ids may produce unexpected results.

The possible values ‘mode’ may have are

  • r’ (default) Open a file for reading.
  • w’ Open a file for writing. The previous contents are discarded.
  • a’ Open or create a file for writing at the end of the file.
  • r+’ Open an existing file for reading and writing.
  • w+’ Open a file for reading or writing. The previous contents are discarded.
  • a+’ Open or create a file for reading or writing at the end of the file.

Append a “t” to the mode string to open the file in text mode or a “b” to open in binary mode. On Windows and Macintosh systems, text mode reading and writing automatically converts linefeeds to the appropriate line end character for the system (carriage-return linefeed on Windows, carriage-return on Macintosh). The default when no mode is specified is binary mode.
Additionally, you may append a “z” to the mode string to open a gzipped file for reading or writing. For this to be successful, you must also open the file in binary mode.

The parameter arch is a string specifying the default data format for the file. Valid values for arch are:

  • "native" or "n" (default) The format of the current machine.
  • "ieee-be" or "b" IEEE big endian format.
  • "ieee-le" or "l" IEEE little endian format.

However, conversions are currently only supported for ‘native’, ‘ieee-be’, and ‘ieee-le’ formats.
When opening a new file that does not yet exist, permissions will be set to 0666 – umask.

Built-in Function: fclose (fid)
Built-in Function: fclose ("all")
Built-in Function: status = fclose ("all")

Close the file specified by the file descriptor fid.
If successful, fclose returns 0, otherwise, it returns -1. The second form of the fclose call closes all open files except stdout, stderr, and stdin.
Programming Note: When using "all" the file descriptors associated with gnuplot will also be closed. This will prevent further plotting with gnuplot until Octave is closed and restarted.

Function File: is_valid_file_id (fid)
Return true if fid refers to an open file.

Avanti, qui.

Output elementare
Once a file has been opened for writing a string can be written to the file using the fputs function. The following example shows how to write the string ‘Free Software is needed for Free Science’ to the file ‘free.txt’.

o270

Nota: meglio aggiungere “\n” per l’a-capo:

o271

Built-in Function: fputs (fid, string)
Built-in Function: status = fputs (fid, string)

Write the string string to the file with file descriptor fid.
The string is written to the file with no additional formatting. Use fdisp instead to automatically append a newline character appropriate for the local machine.
Return a non-negative number on success or EOF on error.

A function much similar to fputs is available for writing data to the screen. The puts function works just like fputs except it doesn’t take a file pointer as its input.

Built-in Function: puts (string)
Built-in Function: status = puts (string)

Write a string to the standard output with no formatting.
The string is written verbatim to the standard output. Use disp to automatically append a newline character appropriate for the local machine.
Return a non-negative number on success and EOF on error.

Avanti ancora, qui.

Input per righe
To read from a file it must be opened for reading using fopen. Then a line can be read from the file using fgetl as the following code illustrates

o272

Built-in Function: str = fgetl (fid)
Built-in Function: str = fgetl (fid, len)

Read characters from a file, stopping after a newline, or EOF, or len characters have been read.
The characters read, excluding the possible trailing newline, are returned as a string.
If len is omitted, fgetl reads until the next newline character.
If there are no more characters to read, fgetl returns -1.
To read a line and return the terminating newline see fgets.

Built-in Function: str = fgets (fid)
Built-in Function: str = fgets (fid, len)

Read characters from a file, stopping after a newline, or EOF, or len characters have been read.
The characters read, including the possible trailing newline, are returned as a string.
If len is omitted, fgets reads until the next newline character.
If there are no more characters to read, fgets returns -1.
To read a line and discard the terminating newline see fgetl.

o273

Built-in Function: nlines = fskipl (fid)
Built-in Function: nlines = fskipl (fid, count)
Built-in Function: nlines = fskipl (fid, Inf)

Read and skip count lines from the file specified by the file descriptor fid.
fskipl discards characters until an end-of-line is encountered exactly count-times, or until the end-of-file marker is found.
If count is omitted, it defaults to 1. count may also be Inf, in which case lines are skipped until the end of the file. This form is suitable for counting the number of lines in a file.
Returns the number of lines skipped (end-of-line sequences encountered).

o274

Pausa, sarà un capitolo lungo😳
:mrgreen: