Author Archives: juhan

Coconut – operatori II

1892_5

Ci sono argomenti istituzionali come Octave (sì siamo in ritardo ma il caldo, le ferie, …) e ci sono argomenti che forse poi –chissà– come Coconut. Poi ce ne sono anche altri ancora, come SICP, che meriterebbero più attenzione. Avendo tempo. OK, oggi Coconut, continuo da qui a copiare qui.

Iterator Slicing
Coconut uses a $ sign right after an iterator before a slice to perform iterator slicing. Coconut’s iterator slicing works much the same as Python’s sequence slicing, and looks much the same as Coconut’s partial application, but with brackets instead of parentheses. It has the same precedence as subscription.
Iterator slicing works just like sequence slicing, including support for negative indices and slices, and support for slice objects in the same way as can be done with normal slicing. Iterator slicing makes no guarantee, however, that the original iterator passed to it be preserved (to preserve the iterator, use Coconut’s tee function).
Coconut’s iterator slicing is very similar to Python’s itertools.islice, but unlike itertools.islice, Coconut’s iterator slicing supports negative indices, and is optimized to play nicely with custom or built-in sequence types as well as Coconut’s map, zip, range, and count objects, only computing the elements of each that are actually necessary to extract the desired slice. This behavior can also be extended to custom objects if they define their __getitem__ method lazily and set __coconut_is_lazy__ to True.

c24

Nota: il manuale usa 10**100 ma mi da overflow😳

With Python can’t be done without a complicated iterator slicing function and inspection of custom objects. The necessary definitions in Python can be found in the Coconut header.

Alternative Unicode
Coconut supports Unicode alternatives to many different operator symbols. The Unicode alternatives are relatively straightforward, and chosen to reflect the look and/or meaning of the original symbol.

→ (\u2192)                  => "->"
↦ (\u21a6)                  => "|>"
*↦ (*\u21a6)                => "|*>"
↤ (\u21a4)                  => "<|" 
↤* (\u21a4*)                => "<*|" 
⋅ (\u22c5)                  => "*"
↑ (\u2191)                  => "**"
÷ (\xf7)                    => "/"
÷/ (\xf7/)                  => "//"
∘ (\u2218)                  => ".."
− (\u2212)                  => "-" (only subtraction)
⁻ (\u207b)                  => "-" (only negation)
¬ (\xac)                    => "~"
≠ (\u2260) or ¬= (\xac=)    => "!="
≤ (\u2264)                  => "<=" 
≥ (\u2265)                  => ">="
∧ (\u2227) or ∩ (\u2229)    => "&"
∨ (\u2228) or ∪ (\u222a)    => "|"
⊻ (\u22bb) or ⊕ (\u2295)    => "^"
« (\xab)                    => "<<" 
» (\xbb)                    => ">>"
… (\u2026)                  => "..."
× (\xd7)                    => "@" (only matrix multiplication)

c25

OK, ma forse –sono vecchio– perché cambiare. E poi non è comodissimo introdurre il codice dopo C-S-u. Non sono riuscito a usare quelli con il codice esadecimale, per esempio xf7.

Keywords

data
The syntax for data blocks is a cross between the syntax for functions and the syntax for classes. The first line looks like a function definition, but the rest of the body looks like a class, usually containing method definitions. This is because while data blocks actually end up as classes in Python, Coconut automatically creates a special, immutable constructor based on the given arguments.

Coconut data blocks create immutable classes derived from collections.namedtuple and made immutable with __slots__. Coconut data statement syntax looks like:

data <name>(<args>):
    <body>

<name> is the name of the new data type, <args> are the arguments to its constructor as well as the names of its attributes, and <body> contains the data type’s methods.Subclassing data types can be done easily by inheriting from them in a normal Python class, although to make the new subclass immutable, the line

__slots__ = ()

Rationale
A mainstay of functional programming that Coconut improves in Python is the use of values, or immutable data types. Immutable data can be very useful because it guarantees that once you have some data it won’t change, but in Python creating custom immutable data types is difficult. Coconut makes it very easy by providing data blocks.

Python Docs
Returns a new tuple subclass. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with type names and field names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

Any valid Python identifier may be used for a field name except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

c26

This will fail because data objects are immutable

c27

la versione Python

c28

Showcases the syntax, features, and immutable nature of data types.

c29

Nota: la riga dopo il decoratore viene scritta in modo bizzarro nella REPL, quella corretta è def size(Node(left, right)) = size(left) + size(right) ovviamente.

la versione Python

c30

Pausa, devo digerire il tutto; poi continuo sempre sulle keywords😀
:mrgreen:

Octave – stringhe – VIII – 24

teide

Sempre stringhe, da qui copiando qui.


Funzioni per la classe character
Octave also provides the following character class test functions patterned after the functions in the standard C library. They all operate on string arrays and return matrices of zeros and ones. Elements that are nonzero indicate that the condition was true for the corresponding character in the string array. For example:

o137

Mapping Function: isalnum (s)
Return a logical array which is true where the elements of s are letters or digits and false where they are not.
This is equivalent to (isalpha (s) | isdigit (s)).

Mapping Function: isalpha (s)
Return a logical array which is true where the elements of s are letters and false where they are not.
This is equivalent to (islower (s) | isupper (s)).

Function File: isletter (s)
Is an alias for the isalpha function.

Mapping Function: islower (s)
Return a logical array which is true where the elements of s are lowercase letters and false where they are not.

o138

Mapping Function: isupper (s)
Return a logical array which is true where the elements of s are uppercase letters and false where they are not.

Mapping Function: isdigit (s)
Return a logical array which is true where the elements of s are decimal digits (0-9) and false where they are not.

Mapping Function: isxdigit (s)
Return a logical array which is true where the elements of s are hexadecimal digits (0-9 and a-fA-F).

o139

Mapping Function: ispunct (s)
Return a logical array which is true where the elements of s are punctuation characters and false where they are not.

o140

Mapping Function: isspace (s)
Return a logical array which is true where the elements of s are whitespace characters (space, formfeed, newline, carriage return, tab, and vertical tab) and false where they are not.

Mapping Function: iscntrl (s)
Return a logical array which is true where the elements of s are control characters and false where they are not.

o141

Mapping Function: isgraph (s)
Mapping Function: isprint (s)

Return a logical array which is true where the elements of s are printable characters (but not the space character) and false where they are not.

o142

Mapping Function: isascii (s)
Return a logical array which is true where the elements of s are ASCII characters (in the range 0 to 127 decimal) and false where they are not.

o143

Attenzione che non è come sembra: il controllo viene fatto sui bytes:

o144

Function File: isstrprop (str, prop)
Test character string properties.
If str is a cell array, isstrpop is applied recursively to each element of the cell array.
Numeric arrays are converted to character strings.

The second argument prop must be one of

  • "alpha" True for characters that are alphabetic (letters).
  • "alnum" "alphanum" True for characters that are alphabetic or digits.
  • "lower" True for lowercase letters.
  • "upper" True for uppercase letters.
  • "digit" True for decimal digits (0-9).
  • "xdigit" True for hexadecimal digits (a-fA-F0-9).
  • "space" "wspace" True for whitespace characters (space, formfeed, newline, carriage return, tab, vertical tab).
  • "punct" True for punctuation characters (printing characters except space or letter or digit).
  • "cntrl" True for control characters.
  • "graph" "graphic" True for printing characters except space.
  • "print" True for printing characters including space.
  • "ascii" True for characters that are in the range of ASCII encoding.

o145

Cioè, se ho capito bene isstrprop fa tutto quello che fanno tutte le altre, in base a prop.

Dai, prossimamente si cambia😀

:mrgreen:

cit. & LOLL – 1

Pare funzioni la raccolta delle cose meno seriose viste in settimana; vediamo se le prove devono continuare. E poi oggi c’è da ricordare un avvenimento speciale😀

Image-of-eagle-on-the-moon

the reason python is the best numerical language
::: moorepants

pare che piace
::: f_126_ck

it’s really very hard to identify the funnest part of this document
::: johnregehr

OH: “What’s systemd?”
::: QEDunham

Come to the nerd side…
::: SciencePorn

Cn0rpGeUMAAwR88

Equally true of #programming #imho
::: Symbo1ics

Durante il #GolpeTurchia #Erdogan per salvarsi usa i social network
::: SteBiotech

Looks like my colleague and I have gained a reputation
::: sanityinc

teachers
::: SciencePorn

A Phylogeny and Evolutionary History of the Pokémon
::: Improbable Research

apollo-11-crew

Pratchett moment at @curry_on_conf
::: alcortesm1

how to be a wizard programmer
::: b0rk

IT HAS BEGUN #curryon
sì, vale il tutto-maiuscolo
::: bodil ::: bodil

Git Merge
::: manisha72617183

5K people turn up to catch Pokémon in Chicago
::: TechCrunch

CnzQGGTXYAAEfBz

Larry Wall is wearing a shirt that says “Need New Haters
::: cmeik

Nell’informatica si capisce subito quando ti propongono un lavoro di merda
::: PTKDev

There are 10 types of people
::: pyjokes_bot

fucktrumpeting
::: DynamicWebPaige

I think I found a bug in ENIAC…
::: PyBeeWare

CnzisAGWAAAfCHJ

Octave – stringhe – VII – 23

thewiz

Sempre stringhe, continuo da qui e oggi affronto un argomento speciale, le regexps, copiando qui.

Built-in Function: [s, e, te, m, t, nm, sp] = regexp (str, pat)
Built-in Function: [...] = regexp (str, pat, "opt1", ...)

Regular expression string matching.
Search for pat in str and return the positions and substrings of any matches, or empty values if there are none.

The matched pattern pat can include any of the standard regex operators, including:

  • . Match any character
  • * + ? {} Repetition operators, representing
  • * Match zero or more times
  • + Match one or more times
  • ? Match zero or one times
  • {n} Match exactly n times
  • {n,} Match n or more times
  • {m,n} Match between m and n times
  • [...] [^...] List operators. The pattern will match any character listed between “[” and “]“. If the first character is “^” then the pattern is inverted and any character except those listed between brackets will match.
    Escape sequences defined below can also be used inside list operators. For example, a template for a floating point number might be [-+.\d]+.
  • () (?:) Grouping operator. The first form, parentheses only, also creates a token.
  • | Alternation operator. Match one of a choice of regular expressions. The alternatives must be delimited by the grouping operator () above.
  • ^ $ Anchoring operators. Requires pattern to occur at the start (^) or end ($) of the string.

In addition, the following escaped characters have special meaning.

  • \d Match any digit
  • \D Match any non-digit
  • \s Match any whitespace character
  • \S Match any non-whitespace character
  • \w Match any word character
  • \W Match any non-word character
  • \< Match the beginning of a word
  • \> Match the end of a word
  • \B Match within a word

Implementation Note: For compatibility with MATLAB, escape sequences in pat (e.g., “\n” => newline) are expanded even when pat has been defined with single quotes. To disable expansion use a second backslash before the escape sequence (e.g., “\\n“) or use the regexptranslate function.

The outputs of regexp default to the order given below

  • s The start indices of each matching substring
  • e The end indices of each matching substring
  • te The extents of each matched token surrounded by (...) in pat
  • m A cell array of the text of each match
  • t A cell array of the text of each token matched
  • nm A structure containing the text of each matched named token, with the name being used as the fieldname. A named token is denoted by (?<name>...).
  • sp A cell array of the text not returned by match, i.e., what remains if you split the string based on pat.

Particular output arguments, or the order of the output arguments, can be selected by additional opt arguments. These are strings and the correspondence between the output arguments and the optional argument are

'start'            s
'end'              e
'tokenExtents'     te
'match'            m
'tokens'           t
'names'            nm
'split'            sp

Additional arguments are summarized below.

  • ‘once’ Return only the first occurrence of the pattern.
  • ‘matchcase’ Make the matching case sensitive. (default)
    Alternatively, use (?-i) in the pattern.
  • ‘ignorecase’ Ignore case when matching the pattern to the string.
    Alternatively, use (?i) in the pattern.
  • ‘stringanchors’ Match the anchor characters at the beginning and end of the string. (default)
    Alternatively, use (?-m) in the pattern.
  • ‘lineanchors’ Match the anchor characters at the beginning and end of the line.
    Alternatively, use (?m) in the pattern.
  • ‘dotall’ The pattern . matches all characters including the newline character. (default)
    Alternatively, use (?s) in the pattern.
  • ‘dotexceptnewline’ The pattern . matches all characters except the newline character.
    Alternatively, use (?-s) in the pattern.
  • ‘literalspacing’ All characters in the pattern, including whitespace, are significant and are used in pattern matching. (default)
    Alternatively, use (?-x) in the pattern.
  • ‘freespacing’ The pattern may include arbitrary whitespace and also comments beginning with the character ‘#’.
    Alternatively, use (?x) in the pattern.
  • ‘noemptymatch’ Zero-length matches are not returned. (default)
  • ‘emptymatch’ Return zero-length matches.
    regexp ('a', 'b*', 'emptymatch') returns [1 2] because there are zero or more ‘b‘ characters at positions 1 and end-of-string.

Built-in Function: [s, e, te, m, t, nm, sp] = regexpi (str, pat)
Built-in Function: [...] = regexpi (str, pat, "opt1", ...)

Case insensitive regular expression string matching.
Search for pat in str and return the positions and substrings of any matches, or empty values if there are none. See regexp, for details on the syntax of the search pattern.

Built-in Function: outstr = regexprep (string, pat, repstr)
Built-in Function: outstr = regexprep (string, pat, repstr, "opt1", ...)

Replace occurrences of pattern pat in string with repstr.
The pattern is a regular expression as documented for regexp.

o134

Options in addition to those of regexp are

  • ‘once’ Replace only the first occurrence of pat in the result.
  • ‘warnings’ This option is present for compatibility but is ignored.

Implementation Note: For compatibility with MATLAB, escape sequences in pat (e.g., “\n” => newline) are expanded even when pat has been defined with single quotes. To disable expansion use a second backslash before the escape sequence (e.g., “\\n“) or use the regexptranslate function.

Function File: regexptranslate (op, s)
Translate a string for use in a regular expression.
This may include either wildcard replacement or special character escaping.
The behavior is controlled by op which can take the following values

  • "wildcard" The wildcard characters ., *, and ? are replaced with wildcards that are appropriate for a regular expression.
  • "escape" The characters $.?[], that have special meaning for regular expressions are escaped so that they are treated literally.

o135

Function File: untabify (t)
Function File: untabify (t, tw)
Function File: untabify (t, tw, deblank)

Replace TAB characters in t with spaces.
The input, t, may be either a 2-D character array, or a cell array of character strings. The output is the same class as the input.
The tab width is specified by tw, and defaults to eight.
If the optional argument deblank is true, then the spaces will be removed from the end of the character data.

The following example reads a file and writes an untabified version of the same file with trailing spaces stripped.
Uso un file ottenuto copiando una parte di un file di sistema (di Octave), questo:

function [varargout] = getfields (s, varargin)

	if (! all (isfield (s, varargin)))
		error ("getfields: some fields not present");
	endif

	if (all (size (s) <= 1))
		varargout = fields2cell (s, varargin);
	else
		error ("getfields: structure must be scalar or empty");
	endif

endfunction

o136

Adesso come faccio a far vedere che ha funzionato e i tab (8 char) sono stati sostituiti da spazi? Uh! c’è diff:

o137

Le regexps sono abbastanza simili alle solite per cui niente screenshots inutili. E –al solito– quando si dovessero usare si dovranno fare tentativi, senza perdere la pazienza, senza scoraggiarsi😉

:mrgreen:

Memo per me quando uso Windows

Best

A volte mi capita –e potrebbe capitare anche a altri– di dover usare Windows (10 o altri) per fare cose sensate, tipo quelle che si fanno nel terminale; quello che là è conosciuto come Prompt dei comandi.

Ogni volta è il solito dramma, e poi per i post su AWK –prossimamente– servirebbe…
OK, questa volta me lo scrivo, tutto per bene.
Uso uno script (che là si chiama batch; io che sono vecchio ricordo che il batch era una cosa completamente differente, come dice il nome, ma tant’è), questo (udt.bat):

@echo off
echo sono %username%
echo sono nella cartella
dir
pause

Sono ospite sul ‘puter della figlia di mio fratello (che ringrazio) per cui tutto da penna USB, con divieto di rovinare qualcosa😉

Inserendo la penna (ehi! al primo tentativo!) si apre il file manager full-screen da ridurre in finestra. Nella cartella giusta, E:\dos, posso fare doppio-click su udt (nota: niente estensione anche se si potrebbe, ma non io su questa macchina, settare diversamente) ottengo

1

che è proprio quel che volevo. Notare il messaggio “Premi un tasto …”, indotto dal comando pasue. Sì perché al termine dello script .bat la finestra del terminale si chiude.

Comportamento scomodo per chi deve interagire con il terminale in modo continuo. Ma c’è un modo semplice per avere il terminale come con Linux. Tra i millemila modi windoziani io uso la scorciatoia che mi sembra più semplice: premere in tasti Win+R e scrivere cmd😀 Fatto.

2

Ci sono un po’ di cose da notare (per i linuxiani):

  • la directory (cartella) corrente è automaticamente esaminata per il comando, prima di cercarlo nella path; quindi basta udt invece di .\udt o ./udt;
  • non c’è distinzione (per i comandi) tra maiuscolo e minuscolo;
  • il comando pause che termina lo script ovviamente non chiude il terminale.

Una cosa che potrebbe servire a noi linuxiani: inserire la directory corrente nella PATH, come si vede non c’è:

3

Si può fare, io uso una combinazione alias + script; non so se c’è un modo più semplice. L’alias da me, per ragioni storiche, si chiama agpa (da aggiungi alla path): alias agpa='source ~/bin/ag_pa

Lo script ~/bin/ag_pa semplicissimo:

#!/bin/bash
export PATH=$PWD:$PATH
echo $PATH

ed ecco:

4

OK; ovviamente chiudendo il terminale la PATH torna quella originaria😀

:mrgreen:

Octave – stringhe – VI – 22

1106

Continuo da qui con le funzioni di manipolazione delle stringhe, copiando qui.

Function File: [a, ...] = strread (str)
Function File: [a, ...] = strread (str, format)
Function File: [a, ...] = strread (str, format, format_repeat)
Function File: [a, ...] = strread (str, format, prop1, value1, ...)
Function File: [a, ...] = strread (str, format, str, prop1, value1, ...)

Read data from a string.
The string str is split into words that are repeatedly matched to the specifiers in format. The first word is matched to the first specifier, the second to the second specifier and so forth. If there are more words than specifiers, the process is repeated until all words have been processed.
The string format describes how the words in str should be parsed. It may contain any combination of the following specifiers:

  • %s The word is parsed as a string.
  • %f, %n The word is parsed as a number and converted to double.
  • %d, %u The word is parsed as a number and converted to int32.
  • %*', '%*f', '%*s The word is skipped.
  • For %s and %d, %f, %n, %u and the associated %*s ... specifiers an optional width can be specified as %Ns, etc. where N is an integer > 1. For %f, format specifiers like %N.Mf are allowed.
  • literal In addition the format may contain literal character strings; these will be skipped during reading.

Parsed word corresponding to the first specifier are returned in the first output argument and likewise for the rest of the specifiers.
By default, format is “%f“, meaning that numbers are read from str. This will do if str contains only numeric fields.

o130

Optional numeric argument format_repeat can be used for limiting the number of items read:

  • -1 (default) read all of the string until the end.
  • N Read N times nargout items. 0 (zero) is an acceptable value for format_repeat.

The behavior of strread can be changed via property-value pairs. The following properties are recognized:

  • "commentstyle" Parts of str are considered comments and will be skipped. value is the comment style and can be any of the following.
  • "shell" Everything from # characters to the nearest end-of-line is skipped.
  • "c" Everything between /* and */ is skipped.
  • "c++" Everything from // characters to the nearest end-of-line is skipped.
  • "matlab" Everything from % characters to the nearest end-of-line is skipped.
    user-supplied. Two options: (1) One string, or 1x1 cell string: Skip everything to the right of it; (2) 2x1 cell string array: Everything between the left and right strings is skipped.
  • "emptyvalue" Value to return for empty numeric values in non-whitespace delimited data. The default is NaN. When the data type does not support NaN (int32 for example), then default is zero.
  • "multipledelimsasone" Treat a series of consecutive delimiters, without whitespace in between, as a single delimiter. Consecutive delimiter series need not be vertically "aligned".
  • "treatasempty" Treat single occurrences (surrounded by delimiters or whitespace) of the string(s) in value as missing values.
  • "returnonerror" If value true (1, default), ignore read errors and return normally. If false (0), return an error.
  • "whitespace" Any character in value will be interpreted as whitespace and trimmed; the string defining whitespace must be enclosed in double quotes for proper processing of special characters like “\t“. In each data field, multiple consecutive whitespace characters are collapsed into one space and leading and trailing whitespace is removed. The default value for whitespace is “ \b\r\n\t” (note the space). Whitespace is always added to the set of delimiter characters unless at least one “%s” format conversion specifier is supplied; in that case only whitespace explicitly specified in "delimiter" is retained as delimiter and removed from the set of whitespace characters. If whitespace characters are to be kept as-is (in e.g., strings), specify an empty value (i.e., “”) for "whitespace"; obviously, whitespace cannot be a delimiter then.

When the number of words in str doesn’t match an exact multiple of the number of format conversion specifiers, strread’s behavior depends on the last character of str:

  • last character = “\n” Data columns are padded with empty fields or Nan so that all columns have equal length
  • last character is not “\n” Data columns are not padded; strread returns columns of unequal length

No, niente immagine, niente prove, sperando di non dovermici trovare a usarla😳

Built-in Function: newstr = strrep (str, ptn, rep)
Built-in Function: newstr = strrep (cellstr, ptn, rep)
Built-in Function: newstr = strrep (..., "overlaps", val)

Replace all occurrences of the pattern ptn in the string str with the string rep and return the result.
The optional argument "overlaps" determines whether the pattern can match at every position in str (true), or only for unique occurrences of the complete pattern (false). The default is true.
s may also be a cell array of strings, in which case the replacement is done for each element and a cell array is returned.

o131

Function File: substr (s, offset)
Function File: substr (s, offset, len)

Return the substring of s which starts at character number offset and is len characters long.
Position numbering for offsets begins with 1. If offset is negative, extraction starts that far from the end of the string.
If len is omitted, the substring extends to the end of s. A negative value for len extracts to within len characters of the end of the string.

o132

A questo punto ci sono le regexps; pausa😉
:mrgreen:

SICP – cap. 1 – Esempio: test di primalità – esercizi – 33

wizard-of-oz

Sempre esercizi, qui, continuando da qui.

Exercise 1.27.  Demonstrate that the Carmichael numbers listed […]  [below] really do fool the Fermat test. That is, write a procedure that takes an integer n and tests whether an is congruent to a modulo n for every a<n, and try your procedure on the given Carmichael numbers.

Carmichael numbers
Numbers that fool the Fermat test are called Carmichael numbers, and little is known about them other than that they are extremely rare. There are 255 Carmichael numbers below 100,000,000. The smallest few are 561, 1105, 1729, 2465, 2821, and 6601. In testing primality of very large numbers chosen at random, the chance of stumbling upon a value that fools the Fermat test is less than the chance that cosmic radiation will cause the computer to make an error in carrying out a “correct” algorithm. Considering an algorithm to be inadequate for the first reason but not for the second illustrates the difference between mathematics and engineering.

Uhmmm… basta eseguire il test di Fermat precedentemente visto in questo post, inserendo i valori elencati.
Determino dapprima i fattori componenti i numeri di Carmichael:

s58

Questo è il codice usato

(define (square x)
  (* x x))

(define (expmod base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
         (remainder (square (expmod base (/ exp 2) m))
                    m))
        (else
         (remainder (* base (expmod base (- exp 1) m))
                    m))))

(define (fermat-test n)
  (define (try-it a)
    (= (expmod a n n) a))
  (try-it (+ 1 (random (- n 1)))))
(define (fast-prime? n times)
  (cond ((= times 0) true)
        ((fermat-test n) (fast-prime? n (- times 1)))
        (else false)))

e ottengo:

s59

e

s60.png

Bill the Lizard raggruppa i test, è più bravo lui😀
Molto sintetico (non ho verificato) Ken Dick.
Simile la soluzione di s-sol.
Spaceman Aki è OK, molto simile ai precedenti.

In conclusione sono stato troppo banale, dovevo elaborare il codice, non limitarmi ad applicarlo nella forma già usata; promesso per il futuro. Rileggendo scopro che non ho risolto l’esercizio; devo fare più attenzione😳

:mrgreen:

Octave – stringhe – V – 21

ndr-society

ndr society

Continuo da qui, sempre sulle stringhe, copio qui.

Function File: str = strjoin (cstr)
Function File: str = strjoin (cstr, delimiter)

Join the elements of the cell string array, cstr, into a single string.
If no delimiter is specified, the elements of cstr are separated by a space.
If delimiter is specified as a string, the cell string array is joined using the string. Escape sequences are supported.
If delimiter is a cell string array whose length is one less than cstr, then the elements of cstr are joined by interleaving the cell string elements of delimiter. Escape sequences are not supported.

o124

Function File: strmatch (s, A)
Function File: strmatch (s, A, "exact")

Return indices of entries of A which begin with the string s.
The second argument A must be a string, character matrix, or a cell array of strings.
If the third argument "exact" is not given, then s only needs to match A up to the length of s. Trailing spaces and nulls in s and A are ignored when matching.

o125

Caution: strmatch is scheduled for deprecation. Use strncmp (normal case), or strcmp ("exact" case), or regexp in all new code.

Function File: [tok, rem] = strtok (str)
Function File: [tok, rem] = strtok (str, delim)

Find all characters in the string str up to, but not including, the first character which is in the string delim.
str may also be a cell array of strings in which case the function executes on every individual string and returns a cell array of tokens and remainders.
Leading delimiters are ignored. If delim is not specified, whitespace is assumed.
If rem is requested, it contains the remainder of the string, starting at the first delimiter.

o126

Function File: [cstr] = strsplit (str)
Function File: [cstr] = strsplit (str, del)
Function File: [cstr] = strsplit (..., name, value)
Function File: [cstr, matches] = strsplit (...)

Split the string str using the delimiters specified by del and return a cell string array of substrings.
If a delimiter is not specified the string is split at whitespace {" ",   "\f", "\n", "\r", "\t", "\v"}. Otherwise, the delimiter, del must be a string or cell array of strings. By default, consecutive delimiters in the input string s are collapsed into one resulting in a single split.
Supported name/value pair arguments are:

  • collapsedelimiters which may take the value of true (default) or false.
  • delimitertype which may take the value of "simple" (default) or "regularexpression". A simple delimiter matches the text exactly as written.  Otherwise, the syntax for regular expressions outlined in regexp is used.

The optional second output, matches, returns the delimiters which were matched in the original string.

Examples with simple delimiters:

o127

Examples with regularexpression delimiters:

o128

Function File: [cstr] = ostrsplit (s, sep)
Function File: [cstr] = ostrsplit (s, sep, strip_empty)

Split the string s using one or more separators sep and return a cell array of strings.
Consecutive separators and separators at boundaries result in empty strings, unless strip_empty is true. The default value of strip_empty is false.
2-D character arrays are split at separators and at the original column boundaries.

o129

Pausa che poi arriva un argomento lungo😀
:mrgreen:

Octave – stringhe – IV – 20

sg5.png

Sempre a copiare, qui, proseguendo a raccontare, da qui.

Manipolare stringhe
Octave supports a wide range of functions for manipulating strings. Since a string is just a matrix, simple manipulations can be accomplished using standard operators. The following example shows how to replace all blank characters with underscores:

0114

Nota completamente fuori posto ma scoperta adesso: per spezzare una riga si usa ... in questo modo:

o115

OK, torno alle stringhe😳

For more complex manipulations, such as searching, replacing, and general regular expressions, the following functions come with Octave.

Function File: deblank (s)
Remove trailing whitespace and nulls from s.
If s is a matrix, deblank trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element.

o116

sì, pessima immagine, non si vedono gli spazi😦

Function File: strtrim (s)
Remove leading and trailing whitespace from s.
If s is a matrix, strtrim trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element.

o117

Function File: strtrunc (s, n)
Truncate the character string s to length n.
If s is a character matrix, then the number of columns is adjusted.
If s is a cell array of strings, then the operation is performed on each cell element and the new cell array is returned.

o118

Function File: findstr (s, t)
Function File: findstr (s, t, overlap)
Return the vector of all positions in the longer of the two strings s and t where an occurrence of the shorter of the two starts.
If the optional argument overlap is true (default), the returned vector can include overlapping positions.

o119

Caution: findstr is scheduled for deprecation. Use strfind in all new code.

Function File: idx = strchr (str, chars)
Function File: idx = strchr (str, chars, n)
Function File: idx = strchr (str, chars, n, direction)
Function File: [i, j] = strchr (...)

Search for the string str for occurrences of characters from the set chars.
The return value(s), as well as the n and direction arguments behave identically as in find.
This will be faster than using regexp in most cases.

o120

Uhmmm… mica capito tanto bene; approfondisco:

o121

il mystero permane: non usarla in questo modo😀

Function File: index (s, t)
Function File: index (s, t, direction)
Return the position of the first occurrence of the string t in the string s, or 0 if no occurrence is found.
s may also be a string array or cell array of strings.

o122

Function File: rindex (s, t)
Return the position of the last occurrence of the character string t in the character string s, or 0 if no occurrence is found.
The rindex function is equivalent to index with direction set to "last".

Built-in Function: idx = strfind (str, pattern)
Built-in Function: idx = strfind (cellstr, pattern)
Built-in Function: idx = strfind (..., "overlaps", val)

Search for pattern in the string str and return the starting index of every such occurrence in the vector idx.
If there is no such occurrence, or if pattern is longer than str, or if pattern itself is empty, then idx is the empty array [].
The optional argument "overlaps" determines whether the pattern can match at every position in str (true), or only for unique occurrences of the complete pattern (false). The default is true.
If a cell array of strings cellstr is specified then idx is a cell array of vectors, as specified above.

o123

Pausa; l’argomento durerà parecchio😉
:mrgreen:

Visto nel Web – 244

Settimana terribile! Che mi fa sentire vecchio e stanco già di prima mattina; ma basta lamentele, ecco cosa ho visto nel Web.

hate

The code that took America to the moon was just published to GitHub, and it’s like a 1960s time capsule
#:programmazione funzionale #:storia
::: Quartz ::: glipari ::: Siamo Geek

TIOBE’s Language-Popularity Index Sees A New Top 10 Language: Assembly
#:linguaggi di programmazione
::: Slashdot

C++ 17: A Newer Version of C++ to bring more power and simplicity
::: Technotification

Rust and Rest
Rust è OK😀
#:linguaggi di programmazione
::: Armin Ronacher

HMD global to Create New Generation of Nokia Mobile Phones
Micro$oft diversamente da HP con Apollo lascerà viva Nokia –forse
#:dispositivi mobili #:hardware
::: Technotification

Lifestyle of Software Engineers

Grenoble continues to move schools to open source
#:free open source software
::: Joinup

Stuxnet/Cyberwar Documentary Reviewer: ‘The U.S. Has Pwned Iran’
#:sicurezza, spionaggio
::: Slashdot

‘Pokémon Go’ is already bigger than Tinder, and it’s about to overtake Twitter
#:dispositivi mobili #:Web, Internet
::: Business Insider ::: Donearm ::: Slashdot ::: IGIhosT ::: Black Bag ::: mikko ::: fabiochiusi ::: pixelatedboat ::: Slashdot

shlex — Parse Shell-style Syntaxes
prima o poi serve; io per esempio…
#:programming, codice, snippet
::: PyMOTW-3

@jakevdp and I are excited to announce the 1.0 release of Altair
#:programming, codice, snippet
::: ellisonbg ::: LorenaABarba

13615176_631492917008246_2539766788368549500_n

Linkage 001
ehi! mi fa concorrenza: tanti link, vari
#:Web, Internet
::: Send More Paramedics

How To Activate God Mode On Windows 7,8 and 10
riporto, non è che m’interessi, nèh!
#:sistemi operativi
::: Technotification

Evolution of an Erlang Programming Style
adoro queste storie di vecchi (come me; più smart di me)😀
#:programmazione funzionale #:storia
::: Programming in the 21st Century

Altair
Altair is a declarative statistical visualization library for Python
#:programming, codice, snippet
::: ellisonbg

Ubuntu Phone su altri dispositivi, grazie a Marius
#:dispositivi mobili
::: Dario Cavedon

chickeneels

MIT Says Their Anonymity Network Is More Secure Than Tor
#:sicurezza, spionaggio
::: Slashdot

Open Source Intelligence: cos’è e a cosa serve?
#:sicurezza, spionaggio
::: Tech Economy

Shipping Rust in Firefox
#:linguaggi di programmazione #:Web, Internet
::: Mozilla Hacks

Really, really cool browser based, Markdownesque Diagram Generator
#:tools, componenti software #:Web, Internet
::: rit

Alan Kay Wikia
tutto su un visionario cui dobbiamo tante cose
#:storia #:protagonisti
::: Alan Kay Wikia

13406746_632550776908630_7212103799529263018_n

The Egison Programming Language
Egison is a programming language that realizes non-linear pattern-matching against non-free data types
#:linguaggi di programmazione
::: Egison

Una lista di risorse di tutti i tipi
#:tip, suggerimenti
::: ly f(x)

15 Interesting Facts about Mobile Gaming
sarà vero? e chi non ha il dispositivo mobile?
#:dispositivi mobili
::: Technotification

Is it better to be lucky than good in Silicon Valley?
#:programming, codice, snippet
::: Computer History Museum

gluon
Gluon (previously called embed_lang) is a small, statically-typed, functional programming language designed for application embedding
#:linguaggi di programmazione
::: Marwes

fortune-cookie

MIT’s anonymous online communications protocol Riffle could beat Tor at its own game
#:sicurezza, spionaggio
::: TechCrunch

Microsoft wins landmark appeal over seizure of foreign emails
#:sicurezza, spionaggio
::: Reuters

145 Tech Leaders Say ‘Trump Would Be A Disaster For Innovation’
#:innovazioni, futuro
::: Slashdot

Wikipedia Zero sta violando la neutralità della Rete?
questione difficile; però: vogliamo lasciare tutto ai preti?
#:Web, Internet
::: Umanesimo Digitale

Python 3 for Scientists
ancora nelle pimissime fasi iniziali ma da seguire😀
#:linguaggi di programmazione
::: Python 3 for Scientists

CnUjekmWcAEbfl2

Il magico mondo del #coding: perché dovresti imparare a programmare
#:programming, codice, snippet
::: michelegentili

How the #internet was invented
#:storia
::: nilocram

Pokémon is a Go: Augmented Reality Takes the World by Storm
::: Computer History Museum

get the tweets of a user and save them in CSV
#:programming, codice, snippet
::: Python Adventures

CniBiUWXEAAEU2c

Attending Scipy 2016
#:linguaggi di programmazione #:Web, Internet
::: Qingkai Kong

Dask
Dask is a flexible parallel computing library for analytics
#:programming, codice, snippet
::: Dask

Turchia e cellulari
#:dispositivi mobili #:sicurezza, spionaggio
::: Siamo Geek

SOS sta per Scuola Open Source, ovvero quella delle utopie realizzabili (per esempio a Bari…)
#:free open source software
::: CheFuturo

Clf500lWgAAbnev

Iscriviti

Ricevi al tuo indirizzo email tutti i nuovi post del sito.

Segui assieme ad altri 94 follower