quinta-feira, 7 de março de 2019

Using PHP 5.6 and PHP 7.0 on the same machine

Firstly, I'm using Linux Mint Debian Edition 3 (LMDE 3).

I installed this version of LMDE and the default PHP version is the 7.0, however I have legacy systems developed in PHP 5. So, I had to install the oldest version and I did this without uninstall the version 7.

See the steps!

I only managed to take these first steps as root, be careful!

root@lucio:~# apt install ca-certificates apt-transport-https
root@lucio:~# wget -q https://packages.sury.org/php/apt.gpg -O- | sudo apt-key add -
root@lucio:~# echo "deb https://packages.sury.org/php/ stretch main" | sudo tee /etc/apt/sources.list.d/php.list

Now, you can use your login. 

root@lucio:~# exit


Install the PHP 5.6

lucio@lucio:~$ sudo apt update
lucio@lucio:~$ sudo apt install php5.6

Make sure that all necessary packages are installed.

lucio@lucio:~$ sudo apt install php5.6-cli php5.6-common php5.6-curl php5.6-mbstring php5.6-mysql php5.6-xml


You can see the versions like that:

lucio@lucio:~$ sudo update-alternatives --config php
There are 2 choices for the alternative php (providing /usr/bin/php).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php7.0   70        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.0   70        manual mode

Press <enter> to keep the current choice[*], or type selection number: 

But if you change the version by this method, this will not affect apache, it will only affect the PHP client.

Switching between the versions

Now, I'm going to show how to switch between the versions.


First make sure that all PHP versions will be disable.

lucio@lucio:~$ sudo a2dismod php5.6 php7.0

Activate the desired version. 

lucio@lucio:~$ sudo a2enmod php5.6

And finally restart the apache service.

lucio@lucio:~$ sudo systemctl restart apache2





quarta-feira, 20 de fevereiro de 2019

Debian 9 and MongoDB

Debian 9 and MongoDB


This week I upgraded my Mint running under Debian 9.3 (LMDE 3).  

See:

lucio@lucio:~$ cat /etc/debian_version 
9.3


So, I installed Mongo using the default repository. My current version of python 3 is 3.5.3, and I do not want to update python because I'm afraid to break my project - maybe I have to upgrade the pip packages if I did.


Ok... I tried updating python and using it with Mongo 4.0, but the numpy didn't work...and maybe many others too. So, I gave up.


Installing Mongo

lucio@lucio:~$ sudo apt install mongodb



So, this are the versions of my installations.

lucio@lucio:~/desenv/project$ python3 -V
Python 3.5.3

lucio@lucio:~$ mongod --version
db version v3.2.11
git version: 009580ad490190ba33d1c6253ebd8d91808923e4
OpenSSL version: OpenSSL 1.0.2q  20 Nov 2018
allocator: tcmalloc
modules: none
build environment:
    distarch: x86_64
    target_arch: x86_64


It worked fine!

Restoring backups

It's easy restoring backups in Mongo, just use mongorestore - mongorestore <backup path>.

lucio@lucio:~$ mongorestore desenv/project/dump/20190207/



--- 

Installing Mongo 4.0


I will record here the step by step to install Mongo 4.0 in Debian 9.

Make sure you have the curl installed. If not, install it.

lucio@lucio:~$ sudo apt install curl

Install the key of mongodb repository.

lucio@lucio:~$ curl https://www.mongodb.org/static/pgp/server-4.0.asc | sudo apt-key add -

Create the file mongodb-org-4.0.list:

lucio@lucio:~$ sudo vim /etc/apt/sources.list.d/mongodb-org-4.0.list

This will open a new blank file. Paste in the following:

deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main

Save and close the file, then update your package cache:

lucio@lucio:~$ sudo apt update

Install the mongodb-org package to install the server and some supporting tools:

lucio@lucio:~$ sudo apt install mongodb-org

Finally, enable and start the mongod service to get your MongoDB database running:

lucio@lucio:~$ sudo systemctl enable mongod
lucio@lucio:~$ sudo systemctl start mongod

Check if Mongo is running:

lucio@lucio:~$ sudo systemctl status mongod

That's all!!!



segunda-feira, 18 de fevereiro de 2019

Creating and updating root password in Mysql


# Creating the first root password

If you have just installed mysql-server and have not set the root password, you will create the password like this:

$ sudo mysqladmin -uroot password 'password' 


# Updating the root password

For updating the root password, you can do like this:

$ sudo mysqladmin -u root -p'oldpassword' password 'newpassword'




sexta-feira, 14 de dezembro de 2018

Regex on VS Code

Place underscore between words

Find: ([A-Za-z])( )([A-Za-z])
Replace: $1_$3

Find

Ano
Sit reg
Dcih
Apres
Espec
Cgc hosp
Org rec
Ident
Org loc
Nome pac
Logr
Numero
Compl
Tipo bairr
Cs
Cs cod

Replace 

Ano
Sit_reg
Dcih
Apres
Espec
Cgc_hosp
Org_rec
Ident
Org_loc
Nome_pac
Logr
Numero
Compl
Tipo_bairr
Cs
Cs_cod








quinta-feira, 22 de novembro de 2018

Importing files from pg_dump


For importing files generated by pg_dump command, use the command pg_restore, like that:

$ pg_restore -Uusername -hlocalhost -c -v -Fc -ddatabase < file.pg_dump

Options:
  • -U: username
  • -h: host
  • -c: drop database before recreating
  • -v: verbose mode
  • -Fc: the archive is in the custom format of pg_dump
  • -d: database

For more options look on page manpage by pg_restore.

$ man pg_restore


SQL files

In case you have a sql file to import, use this command:

$ psql -Uusername -hlocalhost -v -ddatabase < file.sql


That's all!

quarta-feira, 31 de outubro de 2018

VS Code - Switch between edit and terminal

  1. Open Keyboard Shortcuts [Ctrl + K, Ctrl + S]
  2. Search for Focus Terminal
enter image description here
  1. Set your shortcut, in my case I used Ctrl+'
Check the editor shortcut searching for Focus First Editor, default Ctrl + 1
enter image description here

terça-feira, 30 de outubro de 2018

Importing CSV files to SQLite3 database


Today we will learn how to import n CSV files to a SQLite3 database. Yes, I wrote SQLite3, not SQLite, because the import command just has inside SQLite version 3.

First of all, you need install the SQLite3.
$ sudo apt-get install sqlite3

Now, execute the SQLite3.
$ sqlite3

This is the current version installed in my machine.
$ sqlite3
SQLite version 3.8.7.1 2014-10-29 13:59:56
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite>

Set the csv mode.
sqlite> .mode csv

Here I define the separator used in my CSV files.
sqlite> .separator ';'

Now I start importing the files.
sqlite> .import /home/lucio/desenv/file1.csv table1
sqlite> .import /home/lucio/desenv/file2.csv table2
sqlite> .import /home/lucio/desenv/file3.csv table3

Ok, I only imported 3 files, but you can import as many as you want.

You can check the tables created.
sqlite> .table
table1     table2     table3

Now, I save the tables in a sqlite file.
sqlite> .backup main my_database.db

And finish! I hope I was helpful.






quinta-feira, 30 de agosto de 2018

Handling pdf files in linux, using command line


Some times I need to merge or split files in pdf, and a great tool for this is PDFtk. I, generally, prefer use the command line, it's just my preference, so, follow the tips:

Installing


$ sudo apt-get install pdftk


Merging separate files in one


$ pdftk file1.pdf file2.pdf output final_file.pdf


Splitting files


$ pdftk A=fileA.pdf cat A1 output page1.pdf

or, if you want the pages 1 to 3 and the 5:

$ pdftk A=fileA.pdf cat A1-3 A5 output final_file.pdf

or yet, the pages you want are in different files, see:

$ pdftk A=fileA.pdf B=fileB.pdf cat A1-3 A5 B4-5 B7 output final_file.pdf
 I took the pages 1, 2, 3 and 5 of fileA, and pages 4, 5 and 7 of fileB.


Graphical Interface



Now, if you dont't like command line, and want using a graphical tool, you need to know the PDF Chain.

Installing


$ sudo apt-get install pdfchain


That's all, folks!

Some commands of pip - python package manager

In case you have the two python version installed in your system, using pip when you using python2.x and pip3 when using python3.


Installing

Using python 2.x:
$ sudo apt-get install python-pip

or, if you want to use python3:
$ sudo apt-get install python3-pip

Updating

pip
$ sudo pip install --upgrade pip

pip3
$ sudo pip3 install --upgrade pip

You can also use the above command to upgrade the pip packages, see:
$ pip install --upgrade package_name

Installing packages

pip
$ sudo pip install package_name

pip3
$ sudo pip3 install package_name


If you want install an especific package version, use the command like this example:
$ sudo pip install googlemaps==3.0.2

In case you already have this package installed, just upgrade it:
$ sudo pip install --upgrade googlemaps

Listing all of installed packages

pip:
$ sudo pip freeze

pip3
$ sudo pip3 freeze

Checking the pip version

pip
$ sudo pip --version

pip3
$ sudo pip3 --version


That's all folks!

terça-feira, 21 de agosto de 2018

DPKG RETURNED AN ERROR CODE (1)


Recentemente tive problemas com warsaw quando que não obitve sucesso na instalação do pacote de segurança da Caixa Econômica Federal, em meu Linux Mint.
Contudo, a instalação do .deb bloqueou apt, retornando sempre o mesmo erro, de que teve problemas com o warsaw e o dpkg retornava erro. Nada adiantava, quando que após algumas pesquisas resolvi o problema.

Remova os pacotes com o nome warsaw do /var/lib/dpkg/info/

$ sudo rm  /var/lib/dpkg/info/warsaw.*

Pronto, agora:

$ sudo apt-get clean
$ sudo apt-get autoremove







quinta-feira, 2 de agosto de 2018

"Failed to fetch http://dl.google.com/linux/earth/deb/dists/stable/Release"


I have received this warning every time I upgrade my Linux Mint Debian Editian 2 (LMDE 2). Today I decided to solve this problem. After some research I found a possible solution. I'm still testing, but I'll share it this way to fix the problem:

First step, execute this command:
$ sudo sed -i -e 's/deb http/deb [arch=amd64] http/' "/etc/apt/sources.list.d/google-earth-pro.list"

So, execute this one:
$ sudo sed -i -e 's/deb http/deb [arch=amd64] http/' "/etc/cron.daily/google-earth-pro"

And then:
$ sudo apt-get update ; sudo apt-get check

As I commented, I'm still testing if this configuration will be reset, but with this I can upgrade the sources. In case I have news I will tell you.

Tks!

sábado, 21 de julho de 2018

Access to Bitbucket stopped to work via http and git


Yesterday I changed my Vivo Fibra plan to 100 Mb, so the company had to change the router. Everything was working fine until I needed to do a git pull, from my bitbucket repository. After tireless searches I found the solution. I still don't know if it has other solution, but this one worked to me. 

I just put it in the file /etc/hosts the line:

104.192.143.2 bitbucket.org

Now, try again to git pull or access bitbucket.org via browser. 

I hope this tip has helped you.

;)

quinta-feira, 5 de abril de 2018

Infinite loop in npm install


To solve this error, run:

$ sudo npm -g --unsafe-perm install node-sass

Laravel - error on migrate


PHP 5.6
Mysql 5.5
Laravel 5.4


I had this error while executing: php artisan migrate

Syntax error or access violation: 1071 Specified key was too long; max key l ength is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))


I solved by changing the file config/database.php:

'charset' => 'utf8mb4' by 'charset' => 'utf8'
'collation' => 'utf8mb4_unicode_ci' by 'collation' => 'utf8_unicode_ci'

Drop the created tables by laravel, and execute php artisan migrate again.

quarta-feira, 11 de outubro de 2017

Mysql: errno 12

Message error: InnoDB: mmap(xxx bytes) failed; errno 12


To resolve the Mysql error 12, follow this steps:

$ sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
$ sudo mkswap /swapfile 
$ sudo swapon /swapfile

Add this line to /etc/fstab
/swapfile swap swap defaults 0 0

This last step is needed if you would like to automatically enable swap file after each reboot.

sexta-feira, 24 de março de 2017

Erro no pip


Hoje me deparei com o seguinte erro ao executar o pip:

$ sudo pip install <pacote>
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 356, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2476, in load_entry_point
    return ep.load()
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2190, in load
    ['__name__'])
  File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 74, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "/usr/lib/python2.7/dist-packages/pip/vcs/mercurial.py", line 9, in <module>
    from pip.download import path_to_url
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 25, in <module>
    from requests.compat import IncompleteRead
ImportError: cannot import name IncompleteRead

Para resolver o problema, basta apenas atualizar o pip com o easy_install:

$ sudo easy_install --upgrade pip

Feito isso, o pip será atualizado e resolvido o problema.

$ sudo pip

Usage:   
  pip <command> [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  search                      Search PyPI for packages.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).
  --log <path>                Path to a verbose appending log.
  --proxy <proxy>             Specify a proxy in the form [user:passwd@]proxy.server:port.
  --retries <retries>         Maximum number of retries each connection should attempt (default 5 times).
  --timeout <sec>             Set the socket timeout (default 15 seconds).
  --exists-action <action>    Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host <hostname>   Mark this host as trusted, even though it does not have valid or any HTTPS.
  --cert <path>               Path to alternate CA bundle.
  --client-cert <path>        Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
  --cache-dir <dir>           Store the cache data in <dir>.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.

sexta-feira, 24 de fevereiro de 2017

Problemas de acentuação no Sublime Text


Uso o Linux Mint Debian Edition (LMDE) e tive um problema de acentuação no Sublime Text, por exemplo, ´a, ´e, n~ao, ...

Para resolver esse problema, faça o seguinte processo:

$ im-config


Clique em OK, na próxima tela Yes e selecione a opção none.

Feito isso, dê o logout do sistema (reinicie o X) e após logar-se novamente teste a acentuação no Sublime.

quinta-feira, 23 de fevereiro de 2017

Adicionar e/ou remover idiomas no linux



Use o seguinte comando pelo terminal:

$ sudo dpkg-reconfigure locales

Escolha os idiomas que gostaria de ter no seu sistema, optando pelos pacotes que tenham o charset UTF-8. Escolha o idioma padrão do sistema, e reinicie a máquina.

Optei por fazer pela linha de comando, pois pelo Menu >> Preferências >> Idiomas não conseguia instalar novos idiomas devido a algum erro no sistema, que não consegui ver.

quarta-feira, 8 de fevereiro de 2017

mdbtools


MDB para CSV


Para exportar uma tabela de um arquivo MDB para CSV, use o comando:

$ mdb-export -d ';' -D %F DADOS.mdb "tabela 1" > tabela_1.csv

Explicando os parâmetros:

-d ';'

Indica que quero os campos separados por ponto e vírgula

-D %F

Usado para que os campos de datas sejam no formato YYYY-MM-DD, caso não use ficaria MM/DD/AA HH:MM:SS.  (esse parâmetro não está disponível para o comando mdb-sql)

"tabela 1"

Notem que usei o nome da tabela entre aspas duplas, pois tive experiência com uma base MDB em que tinha os nomes das tabelas compostos, e caso não use aspas dará erro no comando. Essa dica serve para as outras ferramentas do mdbtools.


SELECT no shell usando mdb-sql


Para fazer um SELECT pela linha de comando, use essa opção:

$ echo 'select coluna from "tabela 1"' | mdb-sql DADOS.mdb

Outra forma seria:

$ mdb-sql DADOS.mdb

Irá aparecer:

1 =>


Para listar todas as tabelas do seu MDB, digita na sequência:

1 => list tables
2 => go

Para listar todas as colunas de uma tabela:

1 => describe table "tabela 1"
2 => go

Para fazer SELECT:

1 => SELECT coluna FROM "tabela"
2 => go

terça-feira, 7 de fevereiro de 2017


Instalando pacotes tar.bz2


Para instalar pacotes .tar.bz2, no linux, use a sequência de comandos abaixo:

$ tar xjf Downloads/anki-2.0.41-amd64.tar.bz2
$ cd anki-2.0.41
$ sudo make install