Wednesday, October 7, 2020

Using phpword to merge two Mircrosoft Office Word .docx documents

How to combine or embed and insert another .docx file (Microsoft office docx word document) into another one using PHPWord

Joining two .docx document using php (phpword library)

$mainTemplateProcessor = new \PhpOffice\PhpWord\TemplateProcessor("file1");
//$mainTemplateProcessor ->setValue('var_name', $value);

$innerTemplateProcessor = new \PhpOffice\PhpWord\TemplateProcessor("file2");
//$innerTemplateProcessor->setValue('var2_name', $value2);

// extract internal xml from template that will be merged inside main template
$innerXml = $innerTemplateProcessor->gettempDocumentMainPart();
$innerXml = preg_replace('/^[\s\S]*<w:body>(.*)<\/w:body>.*/', '$1', $innerXml);

// remove tag containing header, footer, images
$innerXml = preg_replace('/<w:sectPr>.*<\/w:sectPr>/', '', $innerXml);

// inject internal xml inside main template
$mainXml = $mainTemplateProcessor->gettempDocumentMainPart();
$mainXml = preg_replace('/<\/w:body>/', '<w:p><w:r><w:br w:type="page" /><w:lastRenderedPageBreak/></w:r></w:p>' . $innerXml . '</w:body>', $mainXml);
$mainTemplateProcessor->settempDocumentMainPart($mainXml);

$mainTemplateProcessor->saveAs($result_file_name);


In order for the above code to work, you need to modify edit and add to the TemplateProcessor.php file those two functions:

public function gettempDocumentMainPart()
{
    return $this->tempDocumentMainPart;
}

public function settempDocumentMainPart($new)
{
    return $this->tempDocumentMainPart = $new;
}


This answer is based on the answer of @pfleu here: https://github.com/PHPOffice/PHPWord/issues/1130



 

Saturday, September 26, 2020

Teu Sonho - Online Interprete Seus Sonhos (teusonho.org)

Teusonho.org - Online Interprete Seus Sonhos

https://teusonho.org é um software de interpretatação online de sonhos usando IA para análise em tempo real de sonhos repetidos e símbolos de sonhos.I took my website for dream analysis using Artificial Intelligence and Machine Learning that I have created in Hebrew https://dreamon.co.il and also in English https://understandmydreams.com and created a version in Portuguese https://teusonho.org with new dream symbols and new dreams.

Peguei meu site para análise de sonhos usando Inteligência Artificial e Aprendizado de Máquina que criei em hebraico https://dreamon.co.il e também em inglês https://understandmydreams.com e criei uma versão em português https://teusonho.org com novos símbolos de sonho e novos sonhos.

Also on twitter: https://twitter.com/OrgTeusonho

 

Online Interprete Seus Sonhos

Sunday, August 30, 2020

nginx rewrite and redirect rule like .htaccess in apache

In order to rewrite for example:

https://www.teusonho.org/symbol/casa to /symbol.php=casa

You can use:

location /symbol {
         rewrite ^/symbol/([^/\.]*)$ /symbol.php?symbol=$1;
    }

Loading (importing) an .sql mysql dumpfile and showing progress bar

When loading and importing a large .sql mysql dump file and you wish to know how long is it going to take and where does the process status is standing using a progress bar from the mysqldump loading you can us pv (pipe viewer)

For example:

pv sqldumpfile.sql | mysql database name

About pv (pipe viewer) utility for Linux:


Tuesday, May 26, 2020

Connecting to MySQL 8 from Old PHP version using mysqli

If you have upgraded your MySQL to MySQL 8 version and still using older version of PHP you might encounter a few problems in the connection using mysqli connector library.

1.
The first problem we are going to solve is:

php mysql 8: "Server sent charset (255) unknown to the client. Please, report to the developers"

The problem is that MySQL have changed the default character set from utf8 to utf8mb4 and it is not supported by mysqli connector (nor PDO as I have checked) in older versions of php.

"The default collation for utf8mb4 differs between MySQL 5.7 and 8.0 ( utf8mb4_general_ci for 5.7, utf8mb4_0900_ai_ci for 8.0). When the 8.0 client requests a character set of utf8mb4 , what it sends to the server is the default 8.0 utf8mb4 collation; that is, the utf8mb4_0900_ai_ci."

The way to solve it easily (there are other ways, such as upgrading php or connectors and more ...) is to force MySQL 8.0 to use UTF8 as default charset for connection.

Add those lines at the end of the my.cnf configuration file. In Ubunutu 20.04 it will be /etc/mysql/mysql.conf.d/mysqld.cnf

So:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

And add at the end (must be at the end of the file):
[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
default_authentication_plugin = mysql_native_password

do not forget to restart the server after:
sudo service mysql restart

2.
Second problem is new plugin for MySQL 8 passwords. Instead of the default mysql_native_password it is now using caching_sha2_password so you will get the error:  mysqli::__construct(): The server requested authentication method unknown to the client [caching_sha2_password]

The last line we added to the my.cnf file should fix it but not entirely. When creating the users inside your database make sure to CREATE USER or ALTER USER to use the mysql_native_password like that:

CREATE USER 'username'@`location` IDENTIFIED WITH mysql_native_password BY '[somepassword]'; 

That solved me some problems.

Monday, May 25, 2020

The way I use mysqldump



sudo mysqldump --master-data=1 --flush-logs --single-transaction --routines --quick --all-databases > db.sql

Friday, May 15, 2020

Simple system to track errors in code and find them easily

Hi,

Here is a trick I developed during my years as a developer / programmer and team code leader. This system not just helps you to find the location of the error or warning in the code, but also who wrote it (without the need to open Git Blame or SVN log) and when was it coded in written.

They say that grep (find in all files) is the best friend of the programmer. Hence if you see an error in text or log file, let's say "Error: can't find configuration file". So you copy the text and "grep" it. It might be you would find this string in a few places scattered around the code.

So, we have started to give some Error Codes to the error. For example "Error: can't find configuration file (1029)". This will make it much easier and this unique error code is easy to search inside all the code files.

So how do you keep all the Error Codes unique ? Maybe a new programmer will add the same code number.

Do you keep a file with all Error Codes ?

Here is my system for assigning error codes:

"Error: some error description (ErrorCode: 20200515.1271726)"

And here is the format of the Error Code

YYYYMMDD.XXXHHII

YYYY, MM, DD - is obvious the date the code was written

HH, II - is the hour and minutes

The XXX is a unique number each of the coder team member identifier.

So let's say a programmer called Dani with code 019 have to add a new log  line with some warning or error. He will add 20200515.0191727 as the Error Code.
Next time I will see this code I can easily 'grep' it and I can also know who wrote this piece of code and when.

Believe me, it helps when the team is large.

Cheers.
Cnaan

Tuesday, March 24, 2020

Defragmentation and resizing to minimize HD size of a Virtual Machine Drive for Virtual Box

When creating a Virtual HD for Virtual Machine in Virtual Box, you can create a large disc space but the actual size on the disc can be much smaller until you fill it up.
But after you fill it, and then delete and try to free space the size on the host disc still remain large.

Here is how to resize the Virtual Drive HD on the host machine:

You have to do the following steps:

Run defrag in the guest (Windows only)
Nullify free space:

With a Linux Guest run this:
dd if=/dev/zero of=/var/tmp/bigemptyfile bs=4096k ; rm /var/tmp/bigemptyfile
Or:

telinit 1
mount -o remount,ro /dev/sda1
zerofree -v /dev/sda1
With a Windows Guest, download SDelete from Sysinternals and run this:

sdelete.exe c: -z
(replace C: with the drive letter of the VDI)

Shutdown the guest VM

Now run VBoxManage's modifymedium command with the --compact option:

With a Linux Host run this:

vboxmanage modifymedium --compact /path/to/thedisk.vdi
With a Windows Host run this:

VBoxManage.exe modifymedium --compact c:\path\to\thedisk.vdi
With a Mac Host run this:

VBoxManage modifymedium --compact /path/to/thedisk.vdi
This reduces the vdi size.

https://superuser.com/questions/529149/how-to-compact-virtualboxs-vdi-file-size

Wednesday, March 11, 2020

גרף שעוקב אחר התפשטות והדבקות נגיף הקורונה בארץ

העיתונות מפרסמת הרבה מספרים והרבה מלל. אז אני מנסה לתמצת את זה, ותמונה שווה יותר מאלף מילים וגרף שווה יותר. אז אני אוסף את פרומי העיתונות ועוקב כמה חולי קורונה חדשים יש לנו כל יום ושם את זה על גרף בשאיפה לראות מגמות, כמה נדבקים, כמה נדבקו בארץ מקורונה ולכמה תחלואה בארץ ישראל גורם הנגיף COVID-19. 

ניתן גם לראות את המספרים הגולמיים של חולי הקורנה, הדבקות חדשות, חולים קשה וכמה הבריאו מהנגיף ישירות במסמך Google Sheets שיצרתי על חולי הקורונה.

והנה גרף חולי הקורונה בארץ:

Saturday, March 7, 2020

Firefox notifications permissions fix for non secured domains (http and not https)

I had a running internal service inside an organization intranet. We wanted to allow notifications (web notifications) but we couldn't. In order to allow notifications for website and domains, both Firefox and Chrome requires https. Quite annoying since it is an Intranet inside the organization.

Trying to install a self-sign certificate or a signed certificate inside the organization (where there is no outside internet connectivity) it's really a pain in the a** and does not work well - and if you ask me it should be much easier and simple than it is.

I found a nice bypass workaround to allow notifications from websites and domains without SSL, hence http:// and not https:// for Firefox.

Firefox holds a file inside the Mozilla directory called permissions.sqlite which is a sqlite database file that holds the permissions for domains. You can add your domain there http://yourdomainname with permissions for notifications and it will work.

I have created a demonstration for Windows here
https://gist.github.com/caviv/8df5fa11a98e0e33557f75215f691d54 in go (golang)

Tuesday, January 28, 2020

Fixing screen not waking up (xorg) on Ubuntu from command line

Sometimes after xubunutu screen is in hibernate mode the screen does not wake up.

Open terminal ALT+CTRL+F1 (tty)

Run:
  sleep 5 && xrandr -d :0 --output 'eDP-1' --primary --auto

Then switch fast back to the graphic mode (ALT+CTRL+F7) wait a few seconds for the screen to wake up.

'eDP-1' is the name of your screen

You can see connected screens running
    xrandr -d :0