Friday, February 2, 2018

How to save changes of read-only file from vim.

It happened to me a lot that after doing some updates to a file by using vim, I forgot it needed root permission, so I have to use a known command which allow to me to do this operation without leaving the state.

:w !sudo tee %

But let's say we want this to be a little more automatic task, well I found this trick very useful which consists of adding the following line to your ~/.vimrc file:

cmap w!! w !sudo tee > /dev/null %

So now you just need to execute:

:w!!

to get this done.

Friday, December 1, 2017

Configuring multiple SSH keys for Git projects in Bitbucket.


#Scenario
Let's say you have a corporate account associated to your private organization projects (repositories), but also have your personal account to work in two different workstations.

When you try to use a repository which do not use your "default" ssh key, you will get a message like:

even if you already added a second key for it.

What happens is that, since we are working with the same service/domain (bitbucket), only one key will be used for project referring that hostname.

So, in order to work with different projects from different accounts, we could setup an "alias" in a configuration file into our ssh folder:

# ~/.ssh/config

Host bitbucket.org
  Hostname bitbucket.org
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/<keyname>

Host <domain-alias>
  Hostname bitbucket.org
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/<keyname>


and use it into your git configuration:

# <repo-path>/.git/config

[remote "origin"]
    url = git@<domain-alias>:<username>/<projectname>.git
    fetch = +refs/heads/*:refs/remotes/origin/*


In this way you should be able to work projects of different accounts hosted in the same service.

Written in collaboration with John Benavides.

Monday, November 27, 2017

Evaluating element locators in Chrome Developer Tools.

When working on test automation, one of the main tasks is finding the right element locators.
So in order to validate you are working with the correct elements you could take advantage of some Dev Tools features.


Finding locators by using the Inspector:

1. Open the Chrome Dev Tools by pressing F12.
2. At the top-left side you will find the selector icon.
3. Click on it and then the element selector you want to get.



Evaluating locators in the Elements panel:

1. By pressing Ctrl+f you will invoke the Find bar.
2. So you can use it to test either your locator is present in the DOM or if it is unique.



Evaluating locators via the Console:

If you prefer to do it via the Console panel, you can use the following syntax:

$x(locator)

e.g. Finding element by its class name: $x("//input[@class='single-data']")


Friday, September 29, 2017

How to select the Chrome's developer tools Dark theme.

1. Open the Chrome developer tools (press F12 key)
2. Click on "Customize and Control DevTools" menu
3. Select "Settings" option



4. From Preferences -> Appearance section, select Theme = Dark

5. Enjoy debugging


Monday, July 31, 2017

Accessing MySQL Server from Docker Container.

For this example we will be using an image from Docker Hub.

You can list the available images by executing:

docker search mysql


and download it with:

docker pull mysql

If you want to list your local images, just type:

docker images



Now in order to create the container we can execute a command with the following options:

docker run -p <port>:<port> --name <container-name> -v <local-folder>:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=<root-password> -d mysql:<tag>

where:

-p Publish a container’s port(s) to the host
--name Assign a name to the container
-v Bind mount a volume
-e Sets the MYSQL_ROOT_PASSWORD environment variable
-d Run container in background and print container ID
tag Tag specifying the MySQL version you want.

Then if you want to see the containers currently running:

docker ps


But, How can I start working with the MySQL of the docker container?

Via terminal (accessing the container bash):

docker exec -it <container-name> bash


Or just pointing your favorite Database Client to the container configuration:






Sunday, July 23, 2017

How to show current Git Branch in the Terminal.

Adding (replacing) the following code to your .bashrc file will do the trick:

# Add git branch if its present to PS1

parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi

How it looks your bash prompt:


See the original post here.

Thursday, June 8, 2017

Change the Browser User-Agent by using Chrome DevTools

Either you are testing an app which verifies the User-Agent or you just want to see your app rendered in a different one. There is an option included in the Chrome Developer Tools which allows you to change this value without having to install any additional third-party software for this.

Steps:

1. In Chrome, open the DevTools (by pressing F12 key)
2. Display the "Customize and control DevTools" options menu:


3. Select the "Show console drawer" option
4. From the new Console section, display the options menu:


5. Select "Network conditions" option
6. Observe the new tab is added to the Console section
7. Look for "User agent" and uncheck the "Select automatically" option
8. Now you are able to select a different agent from the list:

9. Refresh the page so the changes take effect.

Friday, January 20, 2017

How to integrate ESLint with Sublime Text 3

In order to evaluate your code using eslint, you first need to have it installed in your system.

npm install -g eslint

To test it, you can simple execute eslit <filename>.js from the command line.

1. Now, we can proceed to install the Sublime Text pluging by going through Preferences -> Package Control -> Install Package

2. Select "SublimeLinter-contrib-eslint".


3. And, finally just copy a .eslintrc file (with the rules definitions) to the root path of your project.


or generate it by typing eslint --init


And that's it!, now you will be highlighted for every syntax error detected in your files (based on your .eslintrc configuration) while editing them.


Tuesday, August 16, 2016

MySQL: Import CSV file data into temporary tables.

Sometimes is needed to query the database based on an external data file (.csv).
So we could consider to import this data to a temporary table to achieve this, and to ensure not to alter the database schema at all.

Let's say we have a table like this:

mysql> SELECT * from User;
+------+----------+-------------+------------+
| id   | name     | last_name   | sport      |
+------+----------+-------------+------------+
| 1000 | Oscar    | Soliz       | cycling    |
| 1001 | Wendy    | Cornejo     | athletics  |
| 1002 | Karen    | Torrez      | swimming   |
| 1003 | Rosemary | Quispe      | marathon   |
| 1004 | Stefany  | Coronado    | athletics  |
| 1005 | Jose     | Quintanilla | swimming   |
+----+------------+-----------+--------------+

And a CSV file which content some ids:

id
1002
1004
1005

Now, assume we have the following scenario:

"Given a list of User IDs (CSV file), we want to know the name and sport of these people."

Steps:

1. Create a temporary table:

CREATE TEMPORARY TABLE user_ids (id INT(11));

2. Import data from the CSV file:

LOAD DATA INFILE "/file_path/user_ids.csv"
INTO TABLE user_ids
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES; # To ignore headers (first row)


3. Finally you can build the query and work like it is one more table in the database, e.g:

SELECT CONCAT(u.name, ' ', u.last_name) name, u.sport
FROM User u
WHERE u.id IN (SELECT id FROM user_ids);

+------------------+------------+
| name             | sport      |
+------------------+------------+
| Karen Torrez     | swimming   |
| Stefany Coronado | athletics  |
| Jose Quintanilla | swimming   |
+------------------+------------+

Tuesday, April 19, 2016

MySQL: How to export query results to a CSV file

You can use the following query, making sure you have write permission over the destination path.

SELECT field1, field2
FROM table_name INTO OUTFILE '/destination_path/result.csv' 
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Including headers:

(SELECT 'label_field1','label_field2')
UNION 
(SELECT field1, field2
FROM table_name
INTO OUTFILE '/destination_path/result.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n');

Tuesday, April 5, 2016

Empower your Gmail with Mailtrack

What is Mailtrack?


Mailtrack is a Chrome extension for Gmail, which allows you to know when the messages you send have been read.
Basically it brings the double-checks (✓✓) we usually see in mobile messaging to your Gmail inbox and it is free for unlimited time!


Main Features:
- See which messages have been read, how long ago, how many times and which device they were opened on.
- Real-Time desktop notifications
- The only email tracking app with double-checks for Gmail.



Who is it for?
- Account managers, businesses, sales teams and people with direct client relationships
- Professionals looking to increase their productivity
- Teams, project managers, coordinators and internal communications
- Independent people (individuals, freelancers) and people actively looking for employment

Tuesday, March 29, 2016

Configuring Google Chrome Proxy

It should be as easy as going through the Chrome Settings->Network (Change Proxy settings..)


But if for any reason you are not able to access this page in Linux.
e.g.
"When running Google Chrome under a supported desktop environment, the system proxy settings will be used. However, either your system is not supported or there was a problem launching your system configuration."



We can use a workaround by editing the desktop configuration file (assuming you are using GNOME desktop environment).


1. Open the google-chrome.desktop file:

sudo vim /usr/share/applications/google-chrome.desktop

2. And add the proxy you want to use next to the exec value:
e.g: --proxy-server="112.199.65.190:3128" (Philippines proxy server)


3. Save the changes and restart the browser
Verify you are navigating under the configured proxy.

You can use any page to scan and show you what is your current IP address.
e.g. http://ipaddress.com/


Wednesday, March 23, 2016

Hide vertical line from Atom editor

You may first want to know why this is supposed to be there.



The wrap-guide package places a vertical line in each editor at a certain column to guide your formatting, so lines do not exceed a certain width.

But In case you prefer just have it hidden, you can simple do it in different ways:

Editing Preferences:
1. Go to Edit->Preferences->Packages
2. Search for the 'wrap-guide' package and disable it



Editing the Stylesheet:
1. Go to Edit->Stylesheet..
2. Here you personalize the styles as desired:
2.1 To just hide it:

atom-text-editor::shadow .wrap-guide {  
  visibility: hidden;
}

2.2. To play a little bit with other properties:

atom-text-editor::shadow .wrap-guide {
  width: 10px;
  opacity: .3; //barely visible
  background-color: red; //test purpose
}


Saturday, October 3, 2015

Cómo desabilitar la reproducción de videos automática en Facebook.


Solo debes seleccionar:

1. Configuración (Settings)



2. En el panel lateral izquierdo selecciona la option "Videos"
3. Finalmente desabilita la opción "Reproducir videos automáticamente"

Saludos.

Saturday, May 16, 2015

Como alojar tu proyecto web en Google Drive

Es tan sencillo como copiar el folder de tu proyecto a Google Drive y publicarlo.

Pasos:
1. Subir el folder de tu proyecto a Google Drive.
2. Click derecho sobre el folder y seleccionar la opción Share (Compartir)


3. Click sobre la opción Advanced del cuadro de diálogo desplegado


4. En la sección de permisos de visualización (Who can access), click sobre la opción Change


5. Seleccionar la opción On - Public on the web


6. Click Save para guardar los cambios
7. Pero antes de cerrar el cuadro de dialogo, copia el id que se muestra en el link público del folder


8. Finalmente para ver tu pagina, copia el ide despues de la siguiente direccion:
www.googledrive.com/host/<id_folder>
ejm: www.googledrive.com/host/0B5OCI8D4u4IcaGZJb3VIMklmZ2M

Tuesday, April 7, 2015

Como ejecutar JavaScript en Sublime Text usando NodeJS

Bueno, como requisito debemos tener NodeJS instalado y a continuación se debe realizar la siguiente configuración en Sublime Text 3.

Pasos:
1. Crear un nuevo "Build System" desde la opción Tools > Build System > New Build System...


2. Reemplazar el código desplegado por el siguiente:
{
"cmd": ["node", "$file"],
"selector": "source.js"
}


3. Guardar los cambios con el siguiente nombre "Node.sublime-build" en la ruta por defecto.


4. Seleccionar el sistema creado nuevamente desde Tools > Build System > Node


5. Finalmente para ejecutar el código debemos seleccionar la opción Tools > Build (o presionar las techas Ctrl + B)


Wednesday, April 1, 2015

Como descargar videos de Facebook

Una manera simple de descargar videos de Facebook sin instalar software adicional (plugins/capturadores de video) es hacerlo desde la vista para móvil de la página.

Pasos:
1. Abrir el link del video

2. Cambiar la dirección del video por el del sitio para móvil, esto se consigue reemplazando (en la URL) la "www" por "m", por ejemplo:
https://www.facebook.com/ruta_video -> https://m.facebook.com/ruta_video

2. Click derecho sobre el video (mientras reproduce)

3. Seleccionar la opción "Save video as.." (Guardar como)


4. Selecciona un destino para guardarlo.

Friday, September 19, 2014

Cochabamba: Verifica si eres Jurado para las Elecciones 2014

Ayer me encontré una página muy interesante para consultar si uno ha sido seleccionado como jurado para las elecciones de Octubre, sin embargo por ahora la lista de Cachabamba no se encuentra habilitada en esta. Por lo que decidí realizar la extracción de datos de la lista publicada por LosTiempos y reutilizando el código de Marco Antonio, generé el siguiente sitio:



Ojalá les sea de ayuda.

Monday, August 11, 2014

Instalar EMMET en Sublime Text 3

Emmet (antes Zen-Coding) es un plugin desarrollado para optimizar la escritura de codigo en HTML / XML y CSS. También es compatible con Sublime Text 3 y estos son los pasos para su instalación.

Pasos:
1. Abrir la consola a través de la opción View -> Show Console



2. Ejecuta el siguiente código (extraido de sublime.wbond.net) en la consola:

import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)


3. Reiniciar el editor
4. Abrir la Paleta de Comandos Tools ->Command Palette  (Ctrl+Shift+P)


5. Buscar y seleccionar “Install Package


6. En la nueva lista filtrar y seleccionar el nombre del plugin “Emmet


Para confirmar que el plugin ha sido instalado correctamente puedes ingresar el siguiente texto:
html:5 
y seguidamente al presionar la tecla Tab deberás tener una estructura básica de html5 listo para editar.


Nota: El archivo debe ser guardado previamente con el formato correcto (.html) para que las funciones de autocompletado funcionen.