Quantcast
Channel: Planeta Linux Venezuela
Viewing all 1457 articles
Browse latest View live

Milton Mazzarri: The DRY principle

$
0
0

The DRY (Don’t Repeat Yourself) principle it basically consist in the following:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

That said, it’s almost clear that the DRY principle is against the code duplication, something that in the long term affects the maintenance phase, it doesn’t facilitate the improvement or code refactoring and, in some cases, it can generate some contradictions, among other problems.

Recently I have inherited a project, and one of the things that I noticed in some part of the source code are the following:

After a glance, you can save some bytes and apply the facade and module pattern without breaking the API compatibility in this way:

But, if you have read the jQuery documentation it’s obvious that the previous code portions are against the DRY principle, basically, this functions expose some shorthands for the $.ajax method from the jQuery library. That said, it’s important to clarify that jQuery, from version 1.0, offers some shorthands, they are: $.get(), $.getJSON(), $.post(), among others.

So, in this particular case, I prefer to break the backward compatibility and delete the previous code portions. After that, I changed the code that used the previous functions and from this point I only used the shorthands that jQuery offers, some examples may clarify this thought:

Another advantage of using the shorthand methods that jQuery provides is that you can work with Deferreds, one last thing that we must take in consideration is that jqXHR.success() and jqXHR.error() callback methods are deprecated as of jQuery 1.8.

Anyway, I wanted to share my experience in this case. Also, remark that we need to take care of some principles at the moment we develop software and avoid to reinvent the wheel or do overengineering.

Last but not least, one way to read offline documentation that I tend to use isDash or Zeal, I can access a bunch of documentation without the need of an Internet connection, give it a try!

The DRY principle was originally published by Milton Mazzarri at milmazz on June 25, 2014.


Jesus Palencia: Documental: Código Linux

Jesus Palencia: Documental: Historia Secreta de los Hackers Informáticos: Los Primeros Hackers

Jesus Palencia: Los números de 2014

$
0
0

Los duendes de las estadísticas de WordPress.com prepararon un informe sobre el año 2014 de este blog.

Aquí hay un extracto:

Un teleférico de San Francisco puede contener 60 personas. Este blog fue visto por 2.800 veces en 2014. Si el blog fue un teleférico, se necesitarían alrededor de 47 viajes para llevar tantas personas.

Haz click para ver el reporte completo.


Jesus Palencia: Documental: La historia de Internet: La guerra de los Navegadores

Jesus Palencia: I Will Rise: Un vídeo musical en honor a Nikola Tesla

Muammar El Khatib: Eliminar caracteres ocultos de archivos de texto plano con vim

$
0
0
Download PDF

No todos usan el mismo editor de texto. No todos usan el mismo sistema operativo. No es un secreto para nadie. Cuando se trabaja en grupos bastante heterogéneos puede ocurrir que el editor de texto introduce estos caracteres ocultos que si se encuentran dentro de un script bash por ejemplo, generan esos famosos: command not found. Uno de los caracteres ocultos más comunes que he encontrado es ^M, pero imagino que se puede encontrar cualquier otro tipo de aberración. Estos son artefactos agregados por editores generalmente gráficos. Sin más preámbulo, la solución más rápida que he encontrado hasta el momento es cambiar el format file (ff) y guardar el archivo:

 

:set ff=unix

:w

De esta manera los !@#$%* caracteres ocultos son eliminados.

 

Jesus Palencia: Documental: La historia de Internet: Nueva Búsqueda


Jesus Palencia: Documental: La historia de Internet: Ebay y Amazon

Jesus Palencia: Documental: La historia de Internet: El futuro digital

José Luis Rivas: Recordando a Aaron Swartz

$
0
0

Un libro que me encantó es «Homeland» de Cory Doctorow, trata sobre un grupo de hackers que se ven envueltos en situaciones que los deja expuestos a uno de los gobiernos y empresas más poderosas que existen y deben hacer algo aún así los haga correr peligros. Una historia de ficción sobre gente como Aaron Swartz.

Pero lo mejor del libro, es que precisamente cierra con dos cartas, una por Jacob Appelbaum, uno de los primeros mimbros de Wikileaks y desarrollador del proyecto Tor; y otra por Aaron Swartz. La carta de Aaron la traduje y publico a continuación, espero les sirva de inspiración para que sigan en sus luchas aún cuando a veces parezca que quién da la batalla del otro lado es muy grande e invencible:

Hola, soy Aaron. Se me ha dado este pequeño espacio aquí al final del libro porque soy un humano de carne y hueso, y cómo tal, puedo decirte algo que no creerías si viniese de la boca de cualquiera de esos carácteres ficticios:

Esto es real.

Claro, no hay alguien llamado Marcus o Ange realmente, al menos no que yo conozca, pero sí sé de gente real justo como ellos. Si quieres, puedes ir a San Francisco y conocerlos. Y mientras estás allí, puedes jugar D&D con John Gilmore o construir un cohete en Noisebridge o trabajar con algunos hippies en un proyecto de arte para Burning Man.

Y si algo de las cosas más relacionadas con conspiraciones en el libro te parecen demasiado alocadas para ser verdad, bueno, simplemente googlea Blackwater, Xe o BlueCoat. (Yo mismo tengo una solicitud FOIA pendiente para saber más de "software para manejo de persona", pero los federales dicen que les va a tomar tres años más redactar todos los documentos relevantes.)

Ahora, yo espero que te hayas divertido quedándote despierto toda la noche leyendo acerca de estas cosas, pero la parte que viene es importante así que presta atención: lo que está pasando ahora no es algún reality show de televisión donde simplemente puedes sentarte en casa y ver.

Esta es tu vida, este es tú país -- y se quieres mantenerlo seguro, debes involucrarte.

Sé que es fácil sentirse sin poder, como si no hubiese algo que puedas hacer para que baje la marcha o detener "el sistema." Como si todos los hilos son movidos por fuerzas oscuras y poderosas lejanas a tu control. Yo me siento de esa forma también, a veces. Pero simplemente no es verdad.

Hace menos de un año, un amigo me llamó para decirme sobre un proyecto de ley oscuro del cuál había escuchado llamado Acta para Combatir la Vulneración En Línea y La Falsificación o COICA (En Inglés es: Combatting Online Infringement and Counterfeitting Act, de allí la abreviación COICA). Mientras leía el proyecto empecé a preocuparme más y más: bajo estas provisiones, el gobierno podría censurar sitios web que no le gusten sin algo como un juicio. Sería la primera vez que el gobierno de los EEUU se le darían poderes para censurar el acceso a la red.

El proyecto había sido introducido hace un día o dos, pero ya tenía un par de docenas de senadores apoyándola. Y, a pesar de nunca haber un debate ya estaba siendo programada para ser votada en sólo un par de días. Nadie había reportado al respecto y ése era justamente el punto: ellos querían apurar esta cosa para que pasara antes que alguien se diese cuenta.

Afortunadamente, mi amigo se dió cuenta. Nos quedamos despiertos todo el fin de semana y lanzamos un sitio web explicando qué decía el proyecto de ley, con una petición que podías firmar en rechazo al proyecto que te daría números de teléfonos para llamar a tus representantes en el senado. Le dijimos al respecto a algunos amigos y ellos le dijeron a algunos de sus amigos y en cuestión de un par de días teníamos más de 200 mil personas en nuestra petición. Fue increíble.

Bueno, la gente promoviendo esta ley no paró. Ellos gastaron literalmente decenas de millones de dólares haciendo lobby para éste proyecto de ley. La cabeza de cada compañía de medios grandes voló a Washington, D.C. y allí se reunieron con el jefe de personal del presidente y amablemente le recordaron de los millones de dólares que le habían donado a la campaña del presidente y le explicaron cómo lo que ellos querían -- la única cosa que querían -- era que esta ley se aprobara.

Pero la presión pública siguió creciendo. Para intentar sacar a la gente del camino ellos intentaron cambiando el nombre de la ley -- llamándola PIPA y SOPA, incluso llamándola E-PARASITES Act -- pero no importó cómo la llamaron, más y más personas se siguieron diciéndole a sus amigos sobre la ley y consiguiendo más y más personas que se opusieran. Pronto, las firmas en nuestra petición iba en millones.

Logramos detenerlos por más de un año con diferentes tácticas, pero se dieron cuenta que si esperaban más quizás nunca lograrían tener un chance de pasar esta ley. Así que programaron un voto apenas volviesen de la pausa de invierno.

Pero mientras los miembros del congreso estaban fuera en la pausa de invierno, manteniendo reuniones públicas y en las salas de sus pueblos en casa, la gente empezó a visitarlos. En todo el país, miembros del congreso empezaron a ser cuestionados por sus electores acerca de su apoyo a esa sucia ley de censura del internet. Y los miembros del congreso empezaron a asustarse -- algunos llegando tan lejos como responderles atacandome.

Pero esto ya no se trataba de mi -- nunca se trató de mi. Desde el principio fue sobre ciudadanos tomando las cosas en sus propias manos: haciendo vídeos en YouTube y escribiendo canciones oponiéndose a la ley, haciendo gráficos mostrando cuánto dinero los promotores de la ley habían recibido de las industrias promoviéndola, y organizando boycotts poniéndo presión en las compañías que habían promovido la ley.

Y funcionó -- tomó la ley desde un punto político sin problema alguno que se suponía debía pasar unánimamente a una posición más parecida a tener un balón tóxico que nadie quería tocar. ¡Incluso los promotores de la ley empezaron a sacar declaraciones oponiéndose a la ley! Oh sí, esos dueños de medios estaban molestos...

Así no es como se supone que el sistema deba funcionar. ¡Un montón de chicos no detienen unas de las fuerzas más poderosas en Washington simplemente escribiendo en sus portátiles!

Pero pasó. Y tú puedes hacer que pase de nuevo.

El sistema está cambiando. Gracias a la Internet, todos los días personas pueden saber acerca de cosas y organizarse incluso si el sistema está determinado a ignorarlo. Ahora, quizás no ganes todo el tiempo -- esto es la vida real, después de todo -- pero finalmente tenemos una oportunidad.

Pero sólo funciona si tú tomas parte en ello. Y ahora que has leído este libro y aprendido cómo hacerlo, estas perfectamente informado sobre cómo hacerlo de nuevo. Es correcto: ahora depende de ti cambiar el sistema.

Aaron Swartz.

Milton Mazzarri: Grunt: The Javascript Task Manager

$
0
0

Grunt

When you play the Web Developer role, sometimes you may have to endure some repetitive tasks like minification, unit testing, compilation, linting, beautify or unpack Javascript code and so on. To solve this problems, and in the meantime, try to keep your mental health in a good shape, you desperately need to find a way to automate this tasks. Grunt offers you an easy way to accomplish this kind of automation.

In this article I’ll try to explain how to automate some tasks with Grunt, but I recommend that you should take some time to read Grunt’s documentation and enjoy the experience by yourself.

So, in the following sections I’ll try to show you how to accomplish this tasks:

  • Concatenate and create a minified version of your CSS, JavaScript and HTML files.
  • Automatic generation of the documentation for JavaScript with JSDoc.
  • Linting your Javascript code.
  • Reformat and reindent (prettify) your Javascript code.

You can install Grunt via npm (Node Package Manager), so, in order to install Grunt you need to install Node.js first.

Now that you have Node.js and npm installed is a good time to installglobally the Grunt CLI (Command Line Interface) package.

$ sudo npm install -g grunt-cli

Once grunt-cli is installed you need to go to the root directory of your project and create a package.json file, to accomplish this you can do the following:

$ cd example_project$ npm init

The previous command will ask you a series of questions in order to create thepackage.json file, package.json basically store metadata for projects published as npm modules. It’s important to remember to add this file to your source code versioning tool to facilitate the installation of the development dependencies among your partners via npm install command.

At this point we can install Grunt and their respective plugins in the existing package.json with:

$ npm install grunt --save-dev

And the plugins that you need can be installed as follows:

$ npm install <grunt-plugin-name> --save-dev

Please note that the --save-dev parameter will modify your devDependencies section in your package.json. So, be sure to commit the updated package.json file with your project whenever you consider appropriate.

Code documentation

If you document your code following the syntax rules defined on JSDoc 3, e.g.:

/**  * A callback function returning array defining where the ticks  * are laid out on the axis.  *  * @function tickPositioner  * @see {@link http://api.highcharts.com/highstock#yAxis.tickPositioner}  * @param {String} xOrY - Is it X or Y Axis?  * @param {Number} min - Minimum value  * @param {Number} max - Maximum value  * @returns {Array} - Where the ticks are laid out on the axis.  */functiontickPositioner(xOrY,min,max){// do somethingreturntickPositions;}

If you need more information about JSDoc, read their documentation, it’s easy to catch up.

The next step to automate the generation of the code documentation is to install first the grunt-jsdoc plugin as follows:

$ npm install grunt-jsdoc --save-dev

Once grunt-jsdoc is installed you must create your Gruntfile.js in the root directory of your project and then add the jsdoc entry to the options of the initConfig method.

module.exports=function(grunt){// Project configuration.grunt.initConfig({pkg:grunt.file.readJSON('package.json'),jsdoc:{dist:{src:['src/*.js','test/*.js'],dest:'doc'}}});};

Then, you need to load the plugin after the initConfig method in theGruntfile.js:

// Load the plugin that provides the 'jsdoc' task.grunt.loadNpmtasks('grunt-jsdoc');

The resulting Gruntfile.js until now is:

module.exports=function(grunt){// Project configuration.grunt.initConfig({pkg:grunt.file.readJSON('package.json'),jsdoc:{dist:{src:['src/*.js','test/*.js'],dest:'doc'}}});// Load the plugin that provides the 'jsdoc' task.grunt.loadNpmtasks('grunt-jsdoc');};

To generate the documentation, you need to call the jsdoc task as follows:

$ grunt jsdoc

Immediately you can see, inside the doc directory, the available documentation in HTML format with some beautiful styles by default.

JSDoc

Linting your Javascript code

In order to find suspicious, non-portable or potential problems in Javascript code or simply to enforce your team’s coding convention, whatever may be the reason, I recommend that you should include a static code analysis tool in your toolset.

The first step is to define your set of rules. I prefer to specify the set of rules in an independent file called .jshintrc located at the root directory of the project, let’s see an example:

// file: .jshintrc{"globals":{"Highcharts":true,// This is only necessary if you use Highcharts"module":true// Gruntfile.js},"bitwise":true,"browser":true,"camelcase":true,"curly":true,"eqeqeq":true,"forin":true,"freeze":true,"immed":true,"indent":4,"jquery":true,"latedef":true,"newcap":true,"noempty":true,"nonew":true,"quotmark":true,"trailing":true,"undef":true,"unused":true}

If you need more details about the checks that offer every rule mentioned above, please, read the page that contains a list ofall options supported by JSHint

To install the grunt-contrib-jshint plugin do the following:

$ npm install grunt-contrib-jshint --save-dev

Next, proceed to add the jshint entry to the options of the initConfig method in the Gruntfile.js as follows:

jshint:{options:{jshintrc:'.jshintrc'},all:['Gruntfile.js','src/*.js','test/*.js']}

Then, as it’s done in the previous section, you need to load the plugin after the initConfig method in the Grunfile.js

// Load the plugin that provides the 'jshint' task.grunt.loadNpmTasks('grunt-contrib-jshint');

To validate your Javascript code against the previous set of rules you need to call the jshint task:

$ grunt jshint

Note that if you need more information or explanations about the errors that you may receive after the previous command I suggest that you should visitJSLint Error Explanations site.

Code Style

As I mentioned in the previous section, I suggest that you should maintain an independent file where you define the set of rules about your coding styles:

// file: .jsbeautifyrc{"indent_size":4,"indent_char":" ","indent_level":0,"indent_with_tabs":false,"preserve_newlines":true,"max_preserve_newlines":2,"jslint_happy":true,"brace_style":"collapse","keep_array_indentation":false,"keep_function_indentation":false,"space_before_conditional":true,"break_chained_methods":false,"eval_code":false,"unescape_strings":false,"wrap_line_length":0}

Next, proceed to add the jsbeautifier entry to the options of the initConfig method in the Gruntfile.js as follows:

jsbeautifier:{modify:{src:'index.js',options:{config:'.jsbeautifyrc'}},verify:{src:['index.js'],options:{mode:'VERIFY_ONLY',config:'.jsbeautifyrc'}}}

The next step it to load the plugin after the initConfig method:

// Load the plugin that provides the 'jsbeautifier' task.grunt.loadNpmTasks('grunt-jsbeautifier');

To adjust your JS files according to the previous set of rules you need to call the jsbeautifier task:

$ grunt jsbeautifier:modify

Concat and minified CSS, HTML, JS

In order to reduce your CSS, HTML and JS files do as follows:

$ npm install grunt-contrib-uglify --save-dev$ npm install grunt-contrib-htmlmin --save-dev$ npm install grunt-contrib-cssmin --save-dev

Next, proceed to add the htmlmin, cssmin and uglify entries to the options of the initConfig method in the Gruntfile.js as follows:

htmlmin:{dist:{options:{removeComments:true,collapseWhitespace:true},files:{'dist/index.html':'src/index.html',// 'destination': 'source''dist/contact.html':'src/contact.html'}}},cssmin:{add_banner:{options:{banner:'/* My minified css file */'},files:{'path/to/output.css':['path/to/**/*.css']}}},uglify:{options:{banner:'/* <%= grunt.template.today("yyyy-mm-dd") %> */\n',separator:',',compress:true,},chart:{src:['src/js/*.js'],dest:'dist/js/example.min.js'}}

The next step it to load the plugins after the initConfig method:

// Load the plugin that provides the 'uglify' task.grunt.loadNpmTasks('grunt-contrib-uglify');// Load the plugin that provides the 'htmlmin' task.grunt.loadNpmTasks('grunt-contrib-htmlmin');// Load the plugin that provides the 'cssmin' task.grunt.loadNpmTasks('grunt-contrib-cssmin');

To adjust your files according to the previous set of rules you need to call the htmlmin, cssmin or uglify tasks:

$ grunt htmlmin$ grunt cssmin$ grunt uglify

After loading all of your Grunt tasks you can create some aliases.

If you want to create an alias to run the three previous tasks in one step do as follows:

// Wrapper around htmlmin, cssmin and uglify tasks.grunt.registerTask('minified',['htmlmin','cssmin','uglify']);

So, to execute the three tasks in one step you can do the following:

$ grunt minified

The previous command is a wrapper around the htmlmin, cssmin and uglify tasks defined previously.

Wrapping all together we get the following [Grunfile.js][]

Other plugins

Grunt offers you a very large amount of plugins, they have a dedicated section to list them!

I recommend that you should take some time to check out the followingplugins:

Conclusion

Certainly, Grunt do a great job when we talk about task automation, also, automating this repetitive tasks is fun and reduce the errors associated with tasks that in the past we used to run manually over and over again. That been said, I definitely recommend that you should try Grunt, you will get in exchange an improvement in your development workflow, also with it you can forget to endure repetitive tasks that we hate to do, as a consequence you will get more free time to focus on getting things done.

Last but not least, another option for Grunt is Gulp, I recently read about it, if you look at their documentation you notice that their syntax is more clean than Grunt, also is very concise and allows chaining calls, following the concept of streams that pipes offer in *nix like systems, so, I’ll give it a try in my next project.

Grunt: The Javascript Task Manager was originally published by Milton Mazzarri at milmazz on June 28, 2014.

Jesus Palencia: El Blog de Sinfallas ahora en Planeta VasLibre

$
0
0

El día de hoy la comunidad VasLibre ha inaugurado uno más de sus proyectos llamado “Planeta VasLibre” esta iniciativa nos permitirá de tener acceso a noticias relacionadas con el mundo del software y hardware libre, así como también a temas relacionados.

Puedes utilizarlo mediante su sitio web o agregándolo a tu lector de noticias favorito, esta desarrollado usando bootstrap y jquery, cuenta con una licencia libre (en este caso GPL v2) y puede ser descargado desde su repositorio en Github.

Como se puede leer en la nota de lanzamiento del proyecto entre los blogs seleccionados para formar parte de la inauguración del sitio se encuentra este blog :D junto a otros blogs pertenecientes a activistas del software libre en Venezuela, si quieres leer la lista completa de los blogs participantes puedes hacer clic aquí.

Que esperas entra ahora y entérate de las noticias mas interesantes sobre Linux en tu propio idioma.

Enlace: Planeta VasLibre


Tagged: planeta, vaslibre

Miguel Ángel Useche: Ahora pueden leerme desde el planeta VaSlibre

$
0
0

Les informo que VaSlibre, un grupo de usuarios de software libre radicados en la ciudad de Valencia, Venezuela; ahora tiene planeta (una página donde se muestran las entradas de distintos blogs) y me alegra que hayan decidido colocar el mío allí.

Así, recomiendo leer a Planeta VaSlibre y disfrutar de los artículos escritos por varios miembros de la comunidad. De esta forma, pueden leer contenido disponible en varios blogs de forma centralizada y que probablemente alguno de ellos no los conozcas por no haber estado involucrado al grupo.

El sitio es http://planeta.vaslibre.org.ve/ y recuerda guardarlo en tu lector de feeds favorito.

Milton Mazzarri: Grunt: The Javascript Task Manager

$
0
0

Grunt

When you play the Web Developer role, sometimes you may have to endure some repetitive tasks like minification, unit testing, compilation, linting, beautify or unpack Javascript code and so on. To solve this problems, and in the meantime, try to keep your mental health in a good shape, you desperately need to find a way to automate this tasks. Grunt offers you an easy way to accomplish this kind of automation.

In this article I’ll try to explain how to automate some tasks with Grunt, but I recommend that you should take some time to read Grunt’s documentation and enjoy the experience by yourself.

So, in the following sections I’ll try to show you how to accomplish this tasks:

  • Concatenate and create a minified version of your CSS, JavaScript and HTML files.
  • Automatic generation of the documentation for JavaScript with JSDoc.
  • Linting your Javascript code.
  • Reformat and reindent (prettify) your Javascript code.

You can install Grunt via npm (Node Package Manager), so, in order to install Grunt you need to install Node.js first.

Now that you have Node.js and npm installed is a good time to installglobally the Grunt CLI (Command Line Interface) package.

$ sudo npm install -g grunt-cli

Once grunt-cli is installed you need to go to the root directory of your project and create a package.json file, to accomplish this you can do the following:

$ cd example_project$ npm init

The previous command will ask you a series of questions in order to create thepackage.json file, package.json basically store metadata for projects published as npm modules. It’s important to remember to add this file to your source code versioning tool to facilitate the installation of the development dependencies among your partners via npm install command.

At this point we can install Grunt and their respective plugins in the existing package.json with:

$ npm install grunt --save-dev

And the plugins that you need can be installed as follows:

$ npm install <grunt-plugin-name> --save-dev

Please note that the --save-dev parameter will modify your devDependencies section in your package.json. So, be sure to commit the updated package.json file with your project whenever you consider appropriate.

Code documentation

If you document your code following the syntax rules defined on JSDoc 3, e.g.:

/**  * A callback function returning array defining where the ticks  * are laid out on the axis.  *  * @function tickPositioner  * @see {@link http://api.highcharts.com/highstock#yAxis.tickPositioner}  * @param {String} xOrY - Is it X or Y Axis?  * @param {Number} min - Minimum value  * @param {Number} max - Maximum value  * @returns {Array} - Where the ticks are laid out on the axis.  */functiontickPositioner(xOrY,min,max){// do somethingreturntickPositions;}

If you need more information about JSDoc, read their documentation, it’s easy to catch up.

The next step to automate the generation of the code documentation is to install first the grunt-jsdoc plugin as follows:

$ npm install grunt-jsdoc --save-dev

Once grunt-jsdoc is installed you must create your Gruntfile.js in the root directory of your project and then add the jsdoc entry to the options of the initConfig method.

module.exports=function(grunt){// Project configuration.grunt.initConfig({pkg:grunt.file.readJSON('package.json'),jsdoc:{dist:{src:['src/*.js','test/*.js'],dest:'doc'}}});};

Then, you need to load the plugin after the initConfig method in theGruntfile.js:

// Load the plugin that provides the 'jsdoc' task.grunt.loadNpmtasks('grunt-jsdoc');

The resulting Gruntfile.js until now is:

module.exports=function(grunt){// Project configuration.grunt.initConfig({pkg:grunt.file.readJSON('package.json'),jsdoc:{dist:{src:['src/*.js','test/*.js'],dest:'doc'}}});// Load the plugin that provides the 'jsdoc' task.grunt.loadNpmtasks('grunt-jsdoc');};

To generate the documentation, you need to call the jsdoc task as follows:

$ grunt jsdoc

Immediately you can see, inside the doc directory, the available documentation in HTML format with some beautiful styles by default.

JSDoc

Linting your Javascript code

In order to find suspicious, non-portable or potential problems in Javascript code or simply to enforce your team’s coding convention, whatever may be the reason, I recommend that you should include a static code analysis tool in your toolset.

The first step is to define your set of rules. I prefer to specify the set of rules in an independent file called .jshintrc located at the root directory of the project, let’s see an example:

// file: .jshintrc{"globals":{"Highcharts":true,// This is only necessary if you use Highcharts"module":true// Gruntfile.js},"bitwise":true,"browser":true,"camelcase":true,"curly":true,"eqeqeq":true,"forin":true,"freeze":true,"immed":true,"indent":4,"jquery":true,"latedef":true,"newcap":true,"noempty":true,"nonew":true,"quotmark":true,"trailing":true,"undef":true,"unused":true}

If you need more details about the checks that offer every rule mentioned above, please, read the page that contains a list ofall options supported by JSHint

To install the grunt-contrib-jshint plugin do the following:

$ npm install grunt-contrib-jshint --save-dev

Next, proceed to add the jshint entry to the options of the initConfig method in the Gruntfile.js as follows:

jshint:{options:{jshintrc:'.jshintrc'},all:['Gruntfile.js','src/*.js','test/*.js']}

Then, as it’s done in the previous section, you need to load the plugin after the initConfig method in the Grunfile.js

// Load the plugin that provides the 'jshint' task.grunt.loadNpmTasks('grunt-contrib-jshint');

To validate your Javascript code against the previous set of rules you need to call the jshint task:

$ grunt jshint

Note that if you need more information or explanations about the errors that you may receive after the previous command I suggest that you should visitJSLint Error Explanations site.

Code Style

As I mentioned in the previous section, I suggest that you should maintain an independent file where you define the set of rules about your coding styles:

// file: .jsbeautifyrc{"indent_size":4,"indent_char":" ","indent_level":0,"indent_with_tabs":false,"preserve_newlines":true,"max_preserve_newlines":2,"jslint_happy":true,"brace_style":"collapse","keep_array_indentation":false,"keep_function_indentation":false,"space_before_conditional":true,"break_chained_methods":false,"eval_code":false,"unescape_strings":false,"wrap_line_length":0}

Next, proceed to add the jsbeautifier entry to the options of the initConfig method in the Gruntfile.js as follows:

jsbeautifier:{modify:{src:'index.js',options:{config:'.jsbeautifyrc'}},verify:{src:['index.js'],options:{mode:'VERIFY_ONLY',config:'.jsbeautifyrc'}}}

The next step it to load the plugin after the initConfig method:

// Load the plugin that provides the 'jsbeautifier' task.grunt.loadNpmTasks('grunt-jsbeautifier');

To adjust your JS files according to the previous set of rules you need to call the jsbeautifier task:

$ grunt jsbeautifier:modify

Concat and minified CSS, HTML, JS

In order to reduce your CSS, HTML and JS files do as follows:

$ npm install grunt-contrib-uglify --save-dev$ npm install grunt-contrib-htmlmin --save-dev$ npm install grunt-contrib-cssmin --save-dev

Next, proceed to add the htmlmin, cssmin and uglify entries to the options of the initConfig method in the Gruntfile.js as follows:

htmlmin:{dist:{options:{removeComments:true,collapseWhitespace:true},files:{'dist/index.html':'src/index.html',// 'destination': 'source''dist/contact.html':'src/contact.html'}}},cssmin:{add_banner:{options:{banner:'/* My minified css file */'},files:{'path/to/output.css':['path/to/**/*.css']}}},uglify:{options:{banner:'/* <%= grunt.template.today("yyyy-mm-dd") %> */\n',separator:',',compress:true,},chart:{src:['src/js/*.js'],dest:'dist/js/example.min.js'}}

The next step it to load the plugins after the initConfig method:

// Load the plugin that provides the 'uglify' task.grunt.loadNpmTasks('grunt-contrib-uglify');// Load the plugin that provides the 'htmlmin' task.grunt.loadNpmTasks('grunt-contrib-htmlmin');// Load the plugin that provides the 'cssmin' task.grunt.loadNpmTasks('grunt-contrib-cssmin');

To adjust your files according to the previous set of rules you need to call the htmlmin, cssmin or uglify tasks:

$ grunt htmlmin$ grunt cssmin$ grunt uglify

After loading all of your Grunt tasks you can create some aliases.

If you want to create an alias to run the three previous tasks in one step do as follows:

// Wrapper around htmlmin, cssmin and uglify tasks.grunt.registerTask('minified',['htmlmin','cssmin','uglify']);

So, to execute the three tasks in one step you can do the following:

$ grunt minified

The previous command is a wrapper around the htmlmin, cssmin and uglify tasks defined previously.

Wrapping all together we get the following [Grunfile.js][]

Other plugins

Grunt offers you a very large amount of plugins, they have a dedicated section to list them!

I recommend that you should take some time to check out the followingplugins:

Conclusion

Certainly, Grunt do a great job when we talk about task automation, also, automating this repetitive tasks is fun and reduce the errors associated with tasks that in the past we used to run manually over and over again. That been said, I definitely recommend that you should try Grunt, you will get in exchange an improvement in your development workflow, also with it you can forget to endure repetitive tasks that we hate to do, as a consequence you will get more free time to focus on getting things done.

Last but not least, another option for Grunt is Gulp, I recently read about it, if you look at their documentation you notice that their syntax is more clean than Grunt, also is very concise and allows chaining calls, following the concept of streams that pipes offer in *nix like systems, so, I’ll give it a try in my next project.

Grunt: The Javascript Task Manager was originally published by Milton Mazzarri at milmazz on June 28, 2014.


Jesus Palencia: Lista de proveedores DNS públicos y gratuitos para sustituir a los de su ISP

$
0
0

En algunas ocasiones nos vemos en la necesidad de dejar de utilizar los DNS asignados por nuestro ISP, ya sea por una falla, por alguna forma de censura o simplemente porque el rendimiento no es el adecuado.

A continuación les muestro una lista de diferentes proveedores DNS junto a los IP necesarios para su utilización.

  • Level 3 Communications:
    209.244.0.3 – 209.244.0.4 (estas IP direccionan las peticiones a los servidores de Level 3 mas cercanos a su ubicación)
    4.2.2.1 – 4.2.2.2
    4.2.2.3 – 4.2.2.4
    4.2.2.5 – 4.2.2.6
  • Google Public DNS:
    8.8.8.8 – 8.8.4.4
  • OpenDNS: (Acepta DNSCrypt)
    208.67.222.222 – 208.67.220.220
  • Comodo Secure DNS:
    8.26.56.26 – 8.20.247.20
  • DNS Advantage:
    156.154.70.1 – 156.154.71.1
  • DNS.Watch: (Acepta DNSSEC)
    84.200.69.80 – 84.200.70.40
  • SafeDNS:
    195.46.39.39 – 195.46.39.40
  • GreenTeamDNS:
    81.218.119.11 – 209.88.198.133
  • OpenNIC:
    111.67.16.202 – 103.25.56.238
    111.223.227.125 – 119.252.20.75
    108.61.213.134 – 163.47.20.30
    142.4.205.47 – 69.28.67.83
  • Public-Root:
    Países Bajos: 46.244.10.5
    Hungría: 79.172.201.120
    Francia: 46.244.10.70
    Reino Unido: 80.252.121.2
    Canadá: 209.97.202.107
    Australia: 46.244.10.98
    Estados Unidos: 199.5.157.131 – 208.71.35.137
    India: 122.183.133.220
    Singapur: 46.244.10.116
    Rusia: 82.146.40.113
    Irán: 128.65.160.37
    Perú: 200.37.61.62

Si su conexión utiliza IPv6 acá les dejo una lista de diferentes proveedores DNS que soportan dicho protocolo.

  • Google Public DNS:
    2001:4860:4860::8888 – 2001:4860:4860::8844
  • OpenDNS:
    2620:0:ccc::2 – 2620:0:ccd::2
  • DNS.Watch:
    2001:1608:10:25::1c04:b12f – 2001:1608:10:25::9249:d69b

Adicionalmente podemos utilizar namebench, una herramienta que podemos instalar en nuestra PC y que mediante algunas pruebas nos ayudara a seleccionar los servidores DNS adecuados para nuestra conexión.

Para finalizar les dejo los enlaces a unas páginas en donde explican como podemos cambiar los DNS en Ubuntu y Windows, a la hora de configurar los DNS les recomiendo seleccionar como primario y secundario IPs de proveedores diferentes.

Espero que esta información les sea útil, saludos…

Referencias:


Tagged: dns, red

Jesus Palencia: Instalar Usermin en Debian y derivados

$
0
0

Usermin es una interfaz basada en web para webmail, cambio de contraseña, filtros de correo, fetchmail y mucho más. Es desarrollado por el equipo a cargo del desarrollo de Webmin, está diseñado para ser utilizado por los usuarios que no sean root regulares en un sistema Unix les permite realizar tareas que serían capaces de ejecutar si esta conectado a través de SSH de una manera cómoda y sin complicaciones.

Existen paquetes para casi todas las plataformas y su instalación en Debian es bastante sencilla.

  • Descargamos el paquete desde aquí.
  • Abrimos un terminal (como root) e instalamos las dependencias necesarias.
# apt install perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-pty-perl apt-show-versions
  • Abrimos un terminal (como root) y vamos al directorio donde descargamos el paquete y lo instalamos con el siguiente comando.
# dpkg -i *.deb
  • Al finalizar solo hace falta abrir un navegador e ir a la siguiente dirección http://localhost:20000 e ingresamos con nuestras credenciales.

Espero les sea útil…

Referencias:


Tagged: debian, usermin

Jesus Palencia: Síguelos y sabrás todo sobre Firefox OS y demás productos Mozilla

$
0
0

Hoy quiero compartir esta pequeña lista de sitios Web, cuentas de Twitter y Facebook dedicadas a compartir información sobre Firefox OS y otros productos de la fundación Mozilla así como también sobre sus comunidades.

Sitios Web:

Facebook:

Twitter:

¿Que esperas? síguelos y esta atento a las ultimas novedades sobre los proyectos de la fundación Mozilla, saludos…

 


Tagged: socialmedia

Jesus Palencia: La Era del VideoGame Cap. 1/5: Destreza

$
0
0

Cada miércoles a partir de hoy publicare un capitulo de algún documental relacionado con el mundo de la tecnología. Hoy iniciaremos con un documental llamado “La Era del VideoGame” espero lo disfruten.

Enlace al vídeo en Youtube


Tagged: videogame

Jesus Palencia: MediosLibres GNU/Linux una distribución para medios audiovisuales

$
0
0

Este Lunes 26 de Enero de 2015 es el día del la publicación oficial de la beta 2 del sabor de Ubuntu Estudio 12.04.5 Medioslibres GNU/Linux. Su nombre código es Shamatari, incluye más de 260 aplicaciones listas para medios radiofónicos, audiovisuales e impresos. Se distribuye bajo licencia GPLv3. Además, adiciona una amplia variedad de aplicaciones destinadas a facilitar el trabajo en los medios de comunicación.

Cuenta con versiones para 32 y 64 bits, pueden descarga la iso en la web del proyecto, así como también pueden acceder a mucha documentación relacionada con el tema, tal como un centro de soporte, una wiki, documentación, aula-virtual y una serie de vídeo-tutoriales que se vienen desarrollando para simplificar la experiencia en MediosLibres GNU/Linux.

Le deseo mucha suerte a este proyecto y espero tener mas noticias pronto, saludos…

Enlaces de interés:


Tagged: medioslibres
Viewing all 1457 articles
Browse latest View live