Archivi per la categoria ‘Script’
venerdì, 4 maggio 2012
La programmazione modulare è un paradigma di programmazione che permette di definire un programma come l’insieme di più unità indipendenti tra di loro, chiamate appunto “moduli“.
In questo contesto è possibile sviluppare un software lavorando singolarmente sulle sue componenti, isolando funzioni e strutture tra loro affini e favorendo la riusabilità del codice stesso.
Inoltre diventa estremamente semplice estendere le funzionalità del programma con la creazione di nuovi moduli o la modifica di quelli già esistenti.
Javascript non ha un supporto nativo alla programmazione modulare, ma grazie alla sua estrema flessibilità è possibile attuare questo paradigma seguendo il cosidetto “module pattern“. Quest’ultimo prevede la creazione di una classe singleton, con una propria visibilità (o scope) che garantisce il principio dell’information hiding.
Il seguente codice è una mia personale implementazione del module pattern.
/** Modulo per la gestione di un veicolo **/
( function ( BASE, NAME ) {
BASE[ NAME ] = ( function () {
/** PRIVATO **/
var fuel = 0;
/** PUBBLICO **/
var setFuel = function ( value ) { fuel = value; };
var getFuel = function () { return fuel; };
var move = function () { fuel -= 1; };
// Restituisco i membri e i metodi pubblici
return {
setFuel: setFuel,
getFuel: getFuel,
move: move
};
}() );
}( window, 'Vehicle' ) );
(continua…)
Pubblicato in Programmazione, Script | Nessun commento »
giovedì, 19 aprile 2012
Un’implementazione Javascript della funzione date di PHP.
/*
Title --- formatdate.js
Copyright (C) 2012 Giacomo Trudu - wicker25[at]gmail[dot]com
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation version 3 of the License.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
= Version 1.1 =
+ improved performance
*/
/** Formatta un timestamp o un'oggetto Date **/
var formatDate = function ( format, time, r ) {
// Preparo i parametri
r = ( typeof( r ) != 'undefined' && r );
var date = ( typeof( time ) != 'undefined' ) ? ( time instanceof Date ? time : new Date( time * 1000 ) ) : new Date;
// Calcolo il numero dei secondi dall'inizio dell'anno
var yearSecs = ( date - new Date( date.getFullYear(), 0, 1 ) ) / 1000;
// Estraggo alcune informazioni dalla formattazione standard
var meta = String( date ).match( /^.*?([A-Z]{1,4})([\-+]\d{4}) \(([A-Z]+)\).*$/ );
// Estraggo le informazioni
date = {
d : date.getDate(),
D : date.getDay(),
m : date.getMonth(),
y : date.getFullYear(),
l : ( new Date( date.getFullYear(), 1, 29 ).getMonth() === 1 | 0 ),
h : date.getHours(),
M : date.getMinutes(),
s : date.getSeconds(),
u : date.getMilliseconds(),
t : date.getTime(),
z : date.getTimezoneOffset()
};
// Stringa della data formattata
var str = '';
// Riempie di zeri le cifre alla sinistra di un numero
var pad = function ( value, len ) {
return ( '000000000' + String( value ) ).slice( -len );
};
// Parametri della formattazione
var fmt_values = {
d : function () { return pad( date.d, 2 ); },
D : function () { return [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ][ date.D ]; },
j : function () { return date.d; },
l : function () { return [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ][ date.D ]; },
N : function () { return date.D + 1; },
S : function () { return [ 'th', 'st', 'nd', 'rd' ][ date.d % 10 > 3 ? 0 : ( date.d < 10 || date.d > 20 ) * date.d % 10 ]; },
w : function () { return date.D; },
z : function () { return Math.ceil( yearSecs / 86400 ); },
W : function () { return Math.ceil( yearSecs / 604800 ); },
F : function () { return [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ][ date.m ]; },
m : function () { return pad( date.m + 1, 2 ); },
M : function () { return [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ][ date.m ]; },
n : function () { return date.m + 1; },
t : function () { return [31, (date.l ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][ date.m ]; },
L : function () { return date.l; },
Y : function () { return date.y; },
y : function () { return String( date.y ).slice( -2 ); },
a : function () { return ( date.h < 12 ? 'am' : 'pm' ); },
A : function () { return ( date.h < 12 ? 'AM' : 'PM' ); },
g : function () { return date.h % 12 || 12; },
G : function () { return date.h; },
h : function () { return pad( date.h % 12 || 12, 2 ); },
H : function () { return pad( date.h, 2 ); },
i : function () { return pad( date.M, 2 ); },
s : function () { return pad( date.s, 2 ); },
u : function () { return date.u * 1000; },
I : function () { return ( date.m > 2 && date.m < 10 || ( date.m == 2 && date.D - date.d >= 8 - 1 ) ); },
O : function () { return meta[2]; },
P : function () { return meta[2].slice( 0, -2 ) + ':' + meta[2].slice( -2 ); },
T : function () { return meta[3]; },
Z : function () { return -date.z * 60; },
c : function () { return ( !r ? formatDate( 'Y-m-d\\TH:i:sP', time, true ) : null ); },
r : function () { return ( !r ? formatDate( 'D, d M Y H:i:s O', time, true ) : null ); },
U : function () { return Math.floor( date.t / 1000 ); }
};
// Divido la stringa di formattazione in token tenendo conto dei caratteri di escape
var tokens = format.match( /(\\.|.)/gi );
// Costruisco la stringa del tempo
for ( var i = 0; i < tokens.length; i++ )
str += ( tokens[i] in fmt_values ? fmt_values[ tokens[i] ]() : ( tokens[i].length == 1 ? tokens[i] : tokens[i][1] ) );
return str;
};
Esempio di utilizzo:
formatDate( 'j, n, Y' ); // => '10, 3, 2001'
formatDate( 'F j, Y, g:i a' ); // => 'March 10, 2001, 5:16 pm'
formatDate( 'd/m/Y', 1230000000 ); // => '23/12/2008'
formatDate( 'H:i', new Date() ); // => '19:52'
formatDate( 'c' ); // => '2012-04-20T19:12:35+02:00'
formatDate( '\\i\\t \\i\\s \\t\\h\\e jS \\d\\a\\y.' ); // => 'it is the 20th day.'
Oppure si può integrare direttamente al tipo Date:
Date.prototype.format = function ( format ) { return formatDate( format, this ); };
// Esempio:
var timestr = new Date().format( 'd/m/Y' );
Pubblicato in Programmazione, Script | Nessun commento »
sabato, 10 marzo 2012
Un problema che mi ha dato del filo da torcere… Maledetti percorsi assoluti.
<html>
<head>
<script type="text/javascript" src="lib/jquery.js"></script>
<title>Titolo della pagina</title>
</head>
<body>
<div>\[ \left [ - \frac{\hbar^2}{2 m} \frac{\partial^2}{\partial x^2} + V \right ] \Psi
= i \hbar \frac{\partial}{\partial t} \Psi \]</div>
<a id="loadMathJax" href="#">Carica MathJax</a>
<script type="text/javascript">
<!--
// Percorso alla libreria
var MathJax_path = 'lib/mathjax/';
// Carico MathJax alla pressione del link
$('#loadMathJax').click( function () {
// Creo la configurazione di MathJax
var config =
"MathJax.Ajax.config.root = '" + MathJax_path + "';" + // <- Importante
"MathJax.Hub.Config( { " +
" extensions: [ 'tex2jax.js' ], " +
" jax: [ 'input/TeX', 'output/HTML-CSS' ], " +
" tex2jax: { " +
" inlineMath: [ ['\[', '\]'] ], " +
" processEscapes: true " +
" }, " +
"});";
$('head').append( $('<script></script>').attr( 'type', 'text/x-mathjax-config' ).text( config ) );
// Carico la libreria
$.getScript( MathJax_path + 'MathJax.js?config=TeX-AMS-MML_HTMLorMML', function () {
// Modifico il pulsante
$('#loadMathJax').unbind( 'click' ).css( 'text-decoration', 'line-through' );
} );
} );
-->
</script>
</body>
</html>
Pubblicato in Matematica, Programmazione, Script | Nessun commento »
sabato, 13 novembre 2010
Meteosat Europa
Questo semplice script scarica ad intervalli regolari un’immagine presa dal web e la copia sul nostro sfondo. Vi chiedete a quale scopo? Stavo curiosando tra le immagini della terra fornite da Meteosat, che si aggiornano ogni 15 minuti, quando ho pensato di aggiungerle direttamente al mio desktop.
(continua…)
Pubblicato in GNU/Linux, Grafica, Internet, Programmazione, Script, Software | Nessun commento »
martedì, 28 settembre 2010
Avete un vecchio PC che da anni utilizzate solo come fermaporte? Beh.. Riciclatelo!
In questa breve guida vi spiegherò come configurare un semplice Muletto per il download attraverso BitTorrent, gestito in remoto tramite protocollo SSH.
Ecco di cosa abbiamo bisogno:
- L’unità centrale del PC menzionato sopra, munito di scheda di rete (costo approssimativo: 10€).
- Una linea ADSL decente con annesso Router (un’uscita ethernet servirà al nuovo server).
- Una copia su CD/DVD del sistema operativo Debian (o Ubuntu Server, o quello che volete).
(continua…)
Pubblicato in File sharing, GNU/Linux, Internet, Programmazione, Script, Software, Tutorial | 2 Commenti »
mercoledì, 27 gennaio 2010
Umounting con Zenity e Bash
Un’altro di quelli script che “ti tornano utili”. Visto che Thunar non mi dava la possibilità di scegliere con quale tool volessi smontare le partizioni.
#!/bin/bash
#=====================================================================================
# Title: umount.sh
# Author: "Giacomo Trudu" aka "Wicker25" - wicker25[at]gmail[dot]com
# Site: http://www.hackyourmind.org/ - wicker25@gmail.com
# License: GNU General Public License (GPL)
# Description: Finestra di dialogo per l'unmounting di un dispositivo
#=====================================================================================
# Impostazioni generali
mount_path="/media";
cdrom="cdrom0";
cmd_eject="eject";
cmd_umount="pumount";
# Mostro la finestra di scelta
answer=$(ls -1 -d $mount_path/* | zenity --title="Rimozione di un dispositivo" --list \
--text "Seleziona il dispositivo da rimuovere" --column "Partizione" );
# Controllo la validità della scelta
if [ "$answer" != "" ]; then
echo "Rimuovo '$answer'...";
# Verifico se si tratta di un cdrom
if [ "$answer" == "$mount_path/$cdrom" ]; then
# Esplusione del cdrom
( echo; $cmd_eject "$answer" ) | zenity --progress \
--title="Espulsione in corso" \
--text "Espulsione del dispositivo '$answer' in corso..." \
--pulsate;
else
# Espulsione del dispositivo
( echo; $cmd_umount "$answer" ) | zenity --progress \
--title="Rimozione in corso" \
--text "Rimozione del dispositivo '$answer' in corso..."\
--pulsate;
fi
fi
Come al solito andrebbe associato ad una combinazione di tasti rapidi..
Pubblicato in GNU/Linux, Programmazione, Script, Tutorial | Nessun commento »
|
|