How Unix programmers at restaurants search menus for their favorite plate

A Unix programmer heads over to the local diner to get something to eat for lunch. He, or Bob as he prefers, knows better than to manually scan the entire menu with his eyeballs because it’s inefficient. Bob knows that there’s a better way to automate the process in searching for what he wants to eat.

Last time he was here he had a pretty good pasta-and-shrimp plate for under 10 bucks.

Bob wonder’s if this same dish is still available. He pops open his laptop running Linux and scrapes the restaurant website menu table into a plain text file.

menu.txt

the menu

steak burrito $11.95
pasta and shrimp $9.75
caesar salad $6.50

Now that Bob has the menu, he does a grep search for the pasta-and-shrimp plate:

$ cat menu.txt | grep shrimp

pasta and shrimp $9.75

So far so good. He filters for the price column by using awk and the NF variable (which is the number of columns fields available) in order to get the last column containing the prices:

$ cat menu.txt | grep shrimp | awk '{print $NF}'

$9.75

The starvation is kicking in and he’s typing furiously by now. Bob proceeds with sed to turn the dollar amount into an integer by replacing everything except for what’s inbetween the dollar symbol and decimal period. He’ll use a capturing group and replace the contents with the first capture group \1:

$ cat menu.txt | grep shrimp | awk '{print $NF}' | sed -E 's/\$([0-9]+)\..*/\1/g'

9

Finally, using the handy test command and the less-than flag -lt, Bob can check whether the price is less than 10 with the help of xargs to pipe the value as the first argument to test:

$ cat menu.txt | grep shrimp | awk '{print $NF}' | sed -E 's/\$([0-9]+)\..*/\1/g' | xargs -I {} test {} -lt 10 

But wait there’s no output! Actually, test returns an exit status code of 0 if the condition passes or 1 if no match.

Bob simply echo’s Available if the previous command was successful by using &&, otherwise he’ll echo 🙁 by using the double pipe || if it was not successful:

$ cat menu.txt | grep shrimp | awk '{print $NF}' | sed -E 's/\$([0-9]+)\..*/\1/g' | xargs -I {} test {} -lt 10 && echo 'Available!' || echo ':('

Available!

Voila! there it is, the desired pasta-and-shrimp plate is still the under ten bucks. Bob is happy and proceeds to order his favorite dish.

(hope you liked this intro post to unix pipes and bash commands!)

Fonte:


github miguelmota


link miguelmota.com

Best Practice and Recommendations for Linux Server

Securing Linux server is very important to protect your data, intellectual property from the hands of crackers (hackers). The system administrator is responsible for security of the Linux box. In this blog we will go through important tips for hardening a Linux server.

Note: In this blog we are targeting specifically CentOS & RHEL Linux Operating system but same concept can be applied to other Linux/Unix flavors as well.

Link here to best practices

Link here to Linux Server Maintenance Checklist

Unity – Aggiungi link all’eseguibile in /opt

Place the installation to a common area (/opt).

$ sudo mkdir /opt/eclipse
$ sudo mv  /home/USERNAME_HIDDEN/eclipse/java-neon/ /opt/eclipse/

make a common link to the eclipse program to /usr/local/bin/eclipse.

$ sudo ln -s /opt/eclipse/eclipse /usr/local/bin/eclipse

Test running eclipse from the commandline.. Type this without a path:

$ eclipse

If it doesn’t work the exec program might be at:

/opt/eclipse/eclipse/eclipse

Fix this by removing the previous link and linking the exec with:

$ sudo rm /usr/local/bin/eclipse
$ sudo ln -s /opt/eclipse/eclipse/eclipse /usr/local/bin/eclipse

When you can bring up Eclipse from the commandline, you can make a desktop entry by creating a desktop program with.

Create the GUI Launcher

$ gedit  /home/USERNAME_HIDDEN/.local/share/applications/eclipse.desktop

copy and paste this into the editor then save it:

[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Name=Eclipse
Exec=/usr/local/bin/eclipse
Comment=Eclipse Integrated Development Environment
Icon=/opt/eclipse/eclipse/icon.xpm
Categories=programing;IDE;utility

Now eclipse should appear in your Ubuntu Launcher search button.

Continue reading

Using Custom Bulk Actions – Azioni di gruppo

I’m happy to tell you that in WordPress 4.7, developers can register their own bulk actions on list table screens.

custom-bulk-action-screenshot

Let’s walk through the steps required to add one.

An option in the dropdown

To add an option in the Bulk Actions dropdown HTML element, register a callback on the bulk_actions-{screen_id} filter that adds the new option onto the array. Replace {screen_id} with the ID of the admin screen to offer the bulk action on.

To add a bulk action “Email to Eric,” we could use the following code:

1
2
3
4
5
6
add_filter( 'bulk_actions-edit-post', 'register_my_bulk_actions' );
function register_my_bulk_actions($bulk_actions) {
  $bulk_actions['email_to_eric'] = __( 'Email to Eric', 'email_to_eric');
  return $bulk_actions;
}

Handling the form submission

To handle a bulk action form submission, register a callback on the handle_bulk_actions-{screen_id} filter for the corresponding screen. The filter expects the redirect URL to be modified, so be sure to modify the passed $redirect_url. This allows us to carry success or failure state into the next request to display a notice to the user. The other callback arguments will differ depending on the screen here to include contextually relevant data.

To add a bulk action handler for emailing the selected posts, we could use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
add_filter( 'handle_bulk_actions-edit-post', 'my_bulk_action_handler', 10, 3 );
function my_bulk_action_handler( $redirect_to, $doaction, $post_ids ) {
  if ( $doaction !== 'email_to_eric' ) {
    return $redirect_to;
  }
  foreach ( $post_ids as $post_id ) {
    // Perform action for each post.
  }
  $redirect_to = add_query_arg( 'bulk_emailed_posts', count( $post_ids ), $redirect_to );
  return $redirect_to;
}

Showing notices

We could use the existing notice hooks to let the user know what happened, depending on the state we set in the URL:

1
2
3
4
5
6
7
8
9
10
11
12
13
add_action( 'admin_notices', 'my_bulk_action_admin_notice' );
function my_bulk_action_admin_notice() {
  if ( ! empty( $_REQUEST['bulk_emailed_posts'] ) ) {
    $emailed_count = intval( $_REQUEST['bulk_emailed_posts'] );
    printf( '<div id="message" class="updated fade">' .
      _n( 'Emailed %s post to Eric.',
        'Emailed %s posts to Eric.',
        $emailed_count,
        'email_to_eric'
      ) . '</div>', $emailed_count );
  }
}

For the curious, see the related changeset and Trac ticket.

Security Tools to Check for Viruses and Malware on Linux

Antivirus tool

Whether you need an antivirus or anti-malware scanner or a tool to hunt for rootkits, Linux has you covered.

Wait, Linux needs antivirus and anti-malware solutions? I thought it was immune to such things. Perhaps a bit of clarification is necessary here.

First and foremost, no operating system is 100 percent immune to attack. Whether a machine is online or offline, it can fall victim to malicious code. Although Linux is less prone to such attacks than, say, Windows, there is no absolute when it comes to security. I have witnessed, first hand, Linux servers hit by rootkits that were so nasty, the only solution was to reinstall and hope the data backup was current. I’ve been a victim of a (very brief) hacker getting onto my desktop, because I accidentally left desktop sharing running (that was certainly an eye opener). The lesson? Even Linux can be vulnerable.

So why does Linux need tools to prevent viruses, malware, and rootkits? It should be obvious why every server needs protection from rootkits — because once you are hit with a rootkit, all bets are off as to whether you can recover without reinstalling the platform. It’s antivirus and anti-malware where admins start getting a bit confused.

Let me put it simply — if your server (or desktop for that matter) makes use of Samba or sshfs (or any other sharing means), those files will be opened by users running operating systems that are vulnerable. Do you really want to take the chance that your Samba share directory could be dishing out files that contain malicious code? If that should happen, your job becomes exponentially more difficult. Similarly, if that Linux machine performs as a mail server, you would be remiss to not include AV scanning (lest your users be forwarding malicious mail).

With all of that said, what are your options? Let’s take a look at a few tools, offered for the Linux platform, that do a good job of protecting you (and your users) from viruses, malware, and rootkits.

ClamAV

Without a doubt, ClamAV is the most popular option for keeping viruses off of your Linux machines and out of your shared directories. There are a few reasons why ClamAV is so popular among the Linux crowd. First, it’s open source, which in and of itself is a big win. Second, it’s very effective in finding trojans, viruses, malware, and other threats. ClamAV features a multi-threaded scanner daemon that is perfectly suited for mail servers and on-demand scanning.

ClamAV can be run from command line or it with the ClamTK GUI. Both tools are easy to use and very dependable. Installing ClamAV is simple.

For Debian-based systems:

sudo apt install clamav

For RHEL/CentOS systems:

sudo yum install epel-release

sudo yum install clamav

For Fedora-based systems:

sudo dnf install clamav

For SUSE-based systems:

sudo zypper in clamav

If you’re running a Debian-based desktop, you can install ClamTK (the GUI) with the command:

sudo apt install clamtk

There are also third-party tools that can be added (to include support for the likes of MTA, POP3, Web & FTP, Filesys, MUA, Bindings, and more).

Upon installation, the first thing you’ll want to do is update the signatures with the command sudo freshclam. Once that completes, you can scan a directory with the command:

clamscan -r -i DIRECTORY

where DIRECTORY is the location to scan. The -r option means to recursively scan and the -i options means to only print out infected files. If you work with the GUI, it’s even easier. From the GUI you can run a scan and, should ClamAV find anything, act on it (Figure 1).

ClamAV

Figure 1: ClamAV found a file with possible malicious code.

Javascript validazione date

Per validare le date in lato frontend attraverso javascript:

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
console.log( dateRegex.test( $('your input').val() ) );

Oppure:

validate_ddmmyyyy(value){
    var dateRegex = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
    if(dateRegex.test(value)){
        

    }
}

ESTRAPOLAZIONE GRAFICA

Usare rsync per una sincronizzazione in locale

Come detto, grazie a rsync è possibile sincronizzare file e cartelle in modo facile e sicuro. Supponendo di voler sincronizzare due cartelle in locale (ad esempio per creare un backup o una copia “esportabile” su una chiavetta USB) potremmo usare una sintassi del genere:

rsync -avz /path/to/source /path/to/destination

Vediamo nel dettaglio le opzioni utilizzate:

  • a => modalità “archivio” (copia ricorsivamente tutti i file, preservando permessi, timestamp, link simbolici, owner e gruppi);
  • v => modalità “verbose”, offre un output a video circa il risultato dell’elaborazione;
  • z => comprime i dati usando l’algoritmo gzip;

Non sovrascrivere i file modificati di recente

Si faccia attenzione: utilizzando la sintassi vista sopra, rsync andrà ad allineare il contenuto del path di destinazione con quello del path sorgente! Se nella cartella di destinazione si hanno dei file più recenti rispetto alla cartella sorgente e li si vuole preservare si dovrà aggiungere il comando -u, in caso contrario, infatti, la cartella di destinazione viene allineata con la sorgente a prescindere che i files in essa contenuti siano più recenti o meno.

rsync -auvz /path/to/source /path/to/destination

Sincronizzare un solo file

Volendo è possibile utilizzare rsync per effettuare il backup di un singolo file specificandone il nome in qualità di sorgente:

rsync -avz /path/to/source/filename /path/to/destination

Sincronizzare solo la struttura della directory

E’ possibile decidere di sincronizzare solo la struttura della directory sorgente nella destinazione remota. Per farlo useremo l’opzione -d in questo modo:

rsync -avd /path/to/source/filename /path/to/destination

Eliminare i file non presenti nella posizione sorgente

Supponiamo di avere dei files nella cartella di destinazione che non sono presenti nella cartella sorgente. Come si comporta rsync in questa situazione? Normalmente ignora questi file e li lascia dove sono. Se, tuttavia, preferiamo eliminarli possiamo utilizzarel’opzione –delete in questo modo:

rsync -avd --delete /path/to/source/filename /path/to/destination

Sincronizzare solo i file già presenti nella cartella di destinazione

E’ anche possibile dire ad rsync di sincronizzare esclusivamente i files già presenti nella folder di destinazione evitando cioè di crearne di nuovi qualora nella sorgente siano presenti files non rinvenibili nella directory target. Per una simile eventualità si utilizzerà l’opzione –existing in questo modo:

rsync -avd --existing /path/to/source/filename /path/to/destination

Convertire file .flac in .mp3

In questo modo utilizzando ffmpeg di default vengono anche passati i tag presenti sul brano originale

for f in *.flac; do ffmpeg -i "$f" -b:a 320k "${f%flac}mp3"; done

Per dettagli:

Explanation of the used arguments in this example:

  • -i – input file
  • -vn – Disable video, to make sure no video is included if the source would be a video file
  • -ar – Set the audio sampling frequency. For output streams it is set by default to the frequency of the corresponding input stream. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options.
  • -ac – Set the number of audio channels. For output streams it is set by default to the number of input audio channels. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options. So used here to make sure it is stereo (2 channels)
  • -ab – actually seems to be changed, so should be replaced for newer ffmpeg version to -b:a 192k Converts the audio bitrate to be exact 192kbit per second
  • -f – Force input or output file format. The format is normally auto detected for input files and guessed from the file extension for output files, so this option is not needed in most cases.

https://trac.ffmpeg.org/wiki/Encode/MP3

Collection of small and useful freeware utilities

http://www.nirsoft.net/

NirSoft web site provides a unique collection of small and useful freeware utilities, all of them developed by Nir Sofer.
If you are looking for Windows password-recovery tools, click here.
If you are looking for network tools, click here.
To view your IP address and other information, click here.
To view all major IP address blocks assigned to your country, click here.
To read the Blog of NirSoft, click here.
To download a package of all NirSoft utilities (Updated every week), go to this Web page.

Per favore, non chiamateli nativi digitali

Una ricerca della Bicocca smonta il mito della competenza informatica giovanile. Poiché i ragazzi usano dispositivi che si connettono in modo trasparente, invisibile, non percepiscono Internet come un’infrastruttura di base. Stanno crescendo in un mondo nel quale non solo non sanno, ma non possono smontare, smanettare, sperimentare. Tutto questo non crea nativi digitali. Polli di batteria, piuttosto

User add user del from Ubuntu

Aggiungere un user:

$ sudo useradd -m -p passwordtoset username

(-m crea la home page, -p aggiunge la password)

Mostra l’elenco degli utenti presenti:

$ sudo cut -d: -f1 /etc/passwd

Rimuovere un user

$ sudo deluser --remove-home username

 

Box designer Laser Cut

Disegna la tua scatola da tagliare con il taglio laser

http://boxdesigner.connectionlab.org/

Importare il risultato con Inkscape

Piano: 500 mm x 370 mm

Colore: nero

Prima prova:
Box designer cut width: 0.1 mm
Spesore contorno inkscape 1 mm
Potenza laser 270

Seconda prova:
Box designer cut width: 0.05 mm
Spessore contorno 1 mm
Spessore contorno 0.1 mm
Potenza laser: 260

Terza prova Con scatola completa
Box designer cut width: 0.02 mm
Spessore contorno 1 mm (abbiamo capito che è insignificante)
Potenza laser: 260

Conoscere la data di creazione di un file in GNU/Linux

In Ext4 è possibile farlo con:

sudo debugfs -R stat /pippo/Scrivania/test.txt /dev/sda3

Ed infatti, creando un file di test e dando quel comando, l’output è:

Inode: 6029808 Type: regular Mode: 0644 Flags: 0x80000
Generation: 3337172570 Version: 0x00000000:00000001
User: 1000 Group: 1000 Size: 0
File ACL: 0 Directory ACL: 0
Links: 1 Blockcount: 0
Fragment: Address: 0 Number: 0 Size: 0
 ctime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
 atime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
 mtime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
crtime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
Size of extra inode fields: 28
EXTENTS:
(END)

dove la quartultima riga contiene il dato che ci interessa, cioè crtime (creation time).

Gli altri sono:

  • ctime (change time): ora del cambiamento, che può includere anche solo una modifica ai permessi senza apertura del file;
  • atime (access time): ora di accesso al file;
  • mtime (modification time): ora di modifica del file.

Schematicamente, ecco cosa avviene (la x indica un cambio del timestamp):

ctime atime mtime crtime
Creazione file x x x x
Apertura file x
Modifica file x x x
Cambio permessi x

 

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

  • (INNER) JOIN: Returns records that have matching values in both tables
  • LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
  • RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
  • FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

SQL INNER JOIN  SQL LEFT JOIN  SQL RIGHT JOIN  SQL FULL OUTER JOIN

join