GreenCodes https://greencodes.net DevOps Partner Thu, 06 Apr 2023 11:33:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.2 https://greencodes.net/wp-content/uploads/2023/03/cropped-greencodes_new_logo_robot_final-copy1-32x32.png GreenCodes https://greencodes.net 32 32 Case Study for Litesource Speed Optimization https://greencodes.net/case-study-for-litesource-speed-optimization/ https://greencodes.net/case-study-for-litesource-speed-optimization/#respond Thu, 06 Apr 2023 11:32:46 +0000 https://greencodes.net/?p=7781 Deprecated: preg_split(): Passing null to parameter #2 ($subject) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 3442
]]>
Client

Litesource

Task

Speed Optimization

Project Overview

Litesource is an inventory management system built with PHP, Codeigniter, MySQL, and Apache server for the backend, and Vanilla JavaScript and jQuery for the frontend. Inventory management is the practice of overseeing and controlling the ordering, storage, and use of components that a company uses in production. As the project scaled up, one of the key challenges we faced was optimizing the system's speed to provide a seamless user experience.

Challenges
  • Low latency in the system
  • Inefficient performance of the system
  • Delay in the data processing
  • Issues with data integrity and system reliability
  • User dissatisfaction

Solution

To optimize the system’s speed we focused on two things, Mysql query optimization, and cache management.

  1. MYSQL Query Optimization
    To optimize the system’s speed, we focused on MySQL query optimization. We took the following steps:

    • Indexing: We identified various tables that were used in long subqueries and joins and added indexes to them. Indexing these tables helped improve the query performance significantly.
    • Query Refactoring: We refactored various SELECT statements and joins, replacing subqueries with joins where possible. This helped reduce the number of queries and improved query performance.
    • Stored Procedure: We also used stored procedures to optimize the database operations. Stored procedures helped us reduce network traffic by allowing us to execute multiple SQL statements with a single call. This helped improve the overall performance of the system.
  2. Cache Management
    We also implemented a cache management system using Redis to improve the system’s speed. We took the following steps:

    • Trigger: We created a trigger in a few tables that are frequently updated. As soon as new data is inserted or updated, the trigger calls a stored procedure that adds the data to the schedule table.
    • Cron Job: We set up a cron job that reads the schedule table every two seconds and updates the Redis cache if anything has changed in the database.

By using Redis as a caching layer, we were able to reduce the load on the database and improve the system’s speed. The cache management system also helped ensure that the system always showed the latest data to the users.

Conclusion:

By implementing MySQL query optimization and a cache management system using Redis, we were able to significantly improve the inventory management system’s speed and provide a seamless user experience. Our changes resulted in a faster and more reliable system that was able to handle a large amount of data and provide real-time updates to the users.

]]>
https://greencodes.net/case-study-for-litesource-speed-optimization/feed/ 0
Programming: From Beginner to Expert https://greencodes.net/programming-from-beginner-to-expert/ https://greencodes.net/programming-from-beginner-to-expert/#respond Fri, 10 Feb 2023 12:58:47 +0000 http://localhost/greencodes/?p=7480

Expert at anything was once a beginner.

Programming/Scripting is a method to communicate with any machine especially to ask machines to perform ordered task. Since early 2000, hardware has evolved from VLSI to modern day compact chips performing operations within mili seconds. We merely reach to the point when hardware may limit the execution of our script. There are other way around like using network of computing devices for a single operation. We certainly are not discussing about it. In this blog we will be talking about the good practice and patterns  human brain can follow to become a good script/code writer.

‘Expert Programmer’ is a virtual term. I prefer the word ‘Experienced’ rather than ‘Expert’. Expertise are those trait that comes with hard work and long term exposure to any field. Thus the significance of Experience is equivalently essential for an individual to be an Expert. Since there are numerous  programming languages, each for their own specialized functionality and fields of implementation  and a lot of them falls in the same area of implementation(Web-application, Software Development).We can differentiate them with their main fundamental components. There are basically the scripts that  runs under web with HTTP protocol and script running for an OS for a single user, which can be called Web-Application of scripting. In simple words we can call them as scripting run via browser and software installed. (As I am expecting the reader to be fresh graduate.)

In web programming, The most common and popular languages used are PHP, Java, Asp.net, Ruby, Python etc. When I was a fresh graduate back in 2011 I always wondered how the f×ck did script did their job while not being noticed by anyone? Where do you write the script and How everything worked? Later I realized there are a number of areas contributing to make the magic happen behind the curtains. This article may not dive deeper into each area but I will try my best to  briefly explain the WTF system that runs beside the browser .

When you enter some website address like Facebook.com in your browser and hit enter , you are now going to a computer where the files for the website are . In simple word, there’s a computer you are remotely excising somewhere in Silicon Valley from your laptop which whose name is Facebook.com(domain name) . Other URL like ‘HTTP://example.com’ is also a computer likewise to facebook.com. There are mechanisms that are hidden to the user. Hiding all the abstractions and translating it unto a understandable language, all website URLs have IP address something like 11.22.33.44 probably named John’s computer or Ben’s computer. So when you write some web address like http://john.com, you are taken to john’s computer. Now the question is when you visit that URL, how the hell you see a web page with nice slider and all that fancy content? The programming thing that I’m talking about is ready to be disclosed, the mystery.

With john.com, you are taken into john computer. John’s computer now has installed a web server. Another term came up suddenly, ‘web server’ but its very simple. It is just a interface to enter into an operating system. Johns computer has an OS and software like Apache or nginx or similar which open a secure port that allows user to enter into the actual system. The magic mystery is probably unveiled now .

We write script, which are compiled by the compiler or interpreter. The compiler is installed into that OS and we write script and save it as file there in  johns computer. Since  john’s computer serves the users request, it can be treated as server. So another term server just got induced. Don;t get anxious  yet . Server is just a remote computer which should always be turned on in order to respond to the request. We install php, java or any interpreter, that reads the script we have written and does the job as it is instructed. Isn’t that simple?

Now another question is which programming language you must choose? Well the answer is simple. Sometimes you write script in the language that is used in your company that you do intern or you search the company which uses script that you like. Definitely there are advantages of using some languages over another the area that it specializes for. There are rumors of using some languages depending on the number of visitors but guess what It’s just a hoax. I am going to write another article covering this later. But the main thing is we must first understand the user’s requirement and select language accordingly.

All languages serves the same request and respond in same way. Its just like using English or Chinese. The only difference is we need to setup the environment so that Chinese or English is understood. We setup or install LAMP tech. like Apache servers  so that PHP language is understood. We install java on the OS environment so that java language is understood or interpreted. So we go to china and speak Chinese there. We go to USA and speak English. Going to USA is exactly similar to installing English interpreter. Now we code or script in English.

Talking to the real world, most inbuilt functions for all popular languages are in English word. This is just a way some defined actions are taken and understood. Well here bargain came up the new term “inbuilt functions”. they are nothing but just commands shortcuts like saying search in English. We are given a task of searching car key in room. Well this is a task. Now similarly we call search in a sentence for a word. In PHP, there is a function str_pos which finds that word “love” is in 2nd position in the sentence “I love this world.”

Coming back to expert programmer:

So the first thing to be an expert in English is knowing all the English words. A toddler learns everyday the new word and by the age of 7 he almost speaks fluent English, in condition his parents speak English. So the main thing is the learning environment. Exactly similar, we write PHP a script and PHP listener or interpreter understands what we are trying to do. When I understood script we write are understood line by line Like we read book, then computing machine is just an English speaking person.

Lets not deviate this time. Being expert English speaker relies mainly on knowing all words and usage of correct grammar. Now you got it. Becoming expert in php exactly the same. Know all words called inbuilt functions and know the grammar called syntax. Now you are expert. The more you speak English the more you know it. the more you code in php the more you know. Its true they both are not analogous. But the main theme is the same. So you keep on talking in php language and you keep on being expert. Yes expert. You keep on programming in java and you are becoming expert in java. the same in ruby and so on in asp.net. Don’t give up. Just keep on communicating. 50% give up in first 3 month. Its just because you do not realize the words are main thing.

So its like vocabulary. sadly partial truth. you are missing grammar my friend. If you merge grammar and words you really are an expert. The vocabulary is pre-defined programming inbuilt functions and grammar is web server and html for web. 99% give up on grammar from 50% 3 month interns who give up. The more appropriate term might be “Experienced”. You become experienced and get used to the language you have been writing.

Generally while learning we get confused by so many terms: html, css, javascript, webserver, apache, database, server, .htaccess, php modules, json, apis, gateways. There are really a number of things we must be familiar with. We can treat them as english keywords like nouns, verbs, conjuctions etc. If we knew the connection between them and the roles they play making the bigger picture of complete web system, we truly become expert and experienced.

Similar to many elements forming the web, there are many areas of work as well in terms of employment and job category in programming. Some prefer designing and have unique creativity. They work in html, CSS for the display part featured by JavaScript for animated visibility. They create cool slider, banners and play with colors. Some prefer inner programming parts executing or scripting the whole algorithm. For project with large features, it takes time and need to carefully plan the resource management. We can call them as project managers. The system should be bug free and need to be tested properly. We call them as quality assurance. Few personnel’s are needed to handle the servers.

Definitely the path is lengthy but the journey will be fun and can be covered in time. Working with scripting is best thing for those who are willing to learn in progressive and incremental manner everyday. New technologies keep on coming and we must keep pace with that keep ourselves updated. The most fun part is you will be learning new things every next day. Sometimes its totally new sometimes it’s just an update to what you already knew. But the world of scripting and programming never stops teaching you thinks. So good-luck for invincible journey my fellow coders. Just Remember never to give up and stop learning. CODE THE ROAD Amigos, Adios.

]]>
https://greencodes.net/programming-from-beginner-to-expert/feed/ 0
Semaphore 2.0 basic setup for linux/ubuntu users https://greencodes.net/semaphore-2-0-basic-setup-for-linux-ubuntu-users/ https://greencodes.net/semaphore-2-0-basic-setup-for-linux-ubuntu-users/#respond Fri, 10 Feb 2023 12:56:28 +0000 http://localhost/greencodes/?p=7478

Semaphore2.0 Steps:

Setup git project:

 

    1. Get ready with all latest/fresh data/files which you are going to deploy on server.
    2. Create required branches on git which you want to deploy on server and put fresh data on git.
    3. Create .semaphore folder on root of the project and inside of .semaphore folder create semaphore.yml file.  The semaphore.yml file looks like below
      where you can change following values:
        1. Git Branch Docker Build.
        2. ssh_file_name (it’s name can be changed but name should be remembered, same ssh title and file should be created later).
        3. Git Branch Name (This block pulls data from git to server, you can change it’s name to anything you want).
        4. ssh -t -o StrictHostKeychecking=no -p 21/22 user@hostname.com "cd /home/server-user/public_html && git fetch --all && git reset --hard origin/git_branch" this is the command to pull data from git to server, where user@hostname.com is your server user and host-name and git_branch is branch name which you want to pull from
    4. Now push to git after changing semaphore.yml file. (it’s compulsory).

 

Setup on server:

 

    1. Login via ssh to the server.
    2. Remove .git folder, .gitignore(don’t ignore) and .gitattributes from server if exists.
    3. Run command: ssh-keygen -t rsa -b 4096 -C ssh_file_name , Just hit enter key do not change anything (path or name). key tile must be same name like ssh_file_name which you have already assigned on semaphore.yml file.
    4. Download id_rsa and id_rsa.pub files to local from .ssh folder, which is on the root of server.
    5. Rename id_rsa to ssh_file_name and id_rsa.pub to ssh_file_name.pub.
    6. Go to https://github.com/settings/keys and paste content of ssh_file_name.pub file to add new ssh, title will be automatically created having the title name ssh_file_name.
    7. Go to cpanel and add/paste the same public key(ssh_file_name.pub) to SSH section.
    8. Run cmd: ssh -T git@github.com , must say “hi username, ….” (it means your server is successfully connected with git server).
    9. Create required directory for related branches like: cd /home/server-user/public_html.
    10. Hit follwing git commands :
        1. git init
        2. git remote add origin git@github.com:git-username/git-repo.git(git repo on SSH format, not on https).
        3. git fetch --all
        4. git reset --hard origin/master(branch)
        5. git checkout master(branch)
    11. Make sure your git project has same ssh file name matching like ssh_file_name on semaphore.yml file.
    12. Go to semaphore -> select organization -> new project and Select Project (add repository).
    13. On Project List you can see your chosen projects, then click to this project and you can see on the top right side arrow icon, click to that, After click you can see like Install sem CLI & Connect to username, again click to this and you can see two commands like Install sem command line tools and Connect to username organization hit these commands to the terminal to install semaphore on local.
    14. After successful installation of semaphore on local, hit following command on terminal to add private ssh key to semaphore project
      Cmd to add private ssh key:
      • sem create secret ssh_file_name --file ~/Downloads/ssh_file_name:/home/semaphore/.keys/ssh_file_name (key which you was downloaded from server previously and key name should be same like ssh_file_name).

      Cmd to view keys:

        • sem get secret.
    15. Setup has been completed.
    16. Now after pushing your change on git, your code will automatically deployed on server.

 

 

]]>
https://greencodes.net/semaphore-2-0-basic-setup-for-linux-ubuntu-users/feed/ 0
Upgrading MySQL 5.1 to 5.7 in CentOS 6/7 or any Red Hat Variations https://greencodes.net/upgrading-mysql-5-1-to-5-7-in-centos-6-7-or-any-red-hat-variations/ https://greencodes.net/upgrading-mysql-5-1-to-5-7-in-centos-6-7-or-any-red-hat-variations/#respond Fri, 10 Feb 2023 12:55:31 +0000 http://localhost/greencodes/?p=7476 Upgrading MySQL 5.1 to 5.7 in CentOS steps:

The upgrade must be done in incremental through major versions:-

  • 5.1
  • 5.5
  • 5.6 and finally to
  • 5.7

This ensures that the actual database table schema definition changes are properly handled by the mysql_upgrade function of mysql.

The service runs as mysql until mysql 5.6 but it’s mysqld from 5.7 onwards. We will download and install the binaries straight from mysql site i.e we will not rely on any EPEL or IUS repository. You will need sudo access to perform the upgrade.

Backup your database for safety.
Download your favourite zipper.
yum install xz
mysqldump –routines –all-databases | xz > /root/mysqlupgrade/mysql51/mysql-5.1.dump.sql.xz

Step 1: upgrade from 5.1 to 5.5

Download rpms or get the download link from https://dev.mysql.com/downloads/mysql/5.5.html#downloads to upgrade to 5.5 first. A .tar will have all the dependencies of that version.

Upload using FTP software (eg filezilla) the downloaded rpm or ssh into your server and do the wget of rpm tar to any location that has write permission. 

Shutdown MySQL 5.1 for upgrade

mysql -u root -ppassword --execute="set global innodb_fast_shutdown=0"
or simply run:
set global innodb_fast_shutdown=0
logging into mysql.
mysqladmin -u root -ppassword shutdown

Go to the directory where you have write permission and get the .tar of rpms
wget https://cdn.mysql.com//Downloads/MySQL-5.5/MySQL-5.5.62-1.el6.x86_64.rpm-bundle.tar

Extract it,
tar -xvf MySQL-5.5.62-1.el6.x86_64.rpm-bundle.tar 

Uninstall the old 5.1 rpms. Get the list by:-
rpm -qa | grep ‘MySQL’

Uninstall the output  each one by using rpm -e:-
rpm -e MySQL51-client-5.1.73-1.cp1150.x86_64 MySQL51-shared-5.1.73-1.cp1150.x86_64 MySQL51-server-5.1.73-1.cp1150.x86_64 MySQL51-test-5.1.73-1.cp1150.x86_64 MySQL-embedded-5.5.62-1.el6.x86_64 MySQL51-devel-5.1.73-1.cp1150.x86_64

Go to the extracted directory and install the ones of 5.5 extracted recentely by tar:-
rpm -ivh MySQL-server-5.5.62-1.el6.x86_64.rpm MySQL-shared-5.5.62-1.el6.x86_64.rpm MySQL-test-5.5.62-1.el6.x86_64.rpm MySQL-client-5.5.62-1.el6.x86_64.rpm MySQL-devel-5.5.62-1.el6.x86_64.rpm MySQL-embedded-5.5.62-1.el6.x86_64.rpm

Check the mysql version:-
mysql --version

It should be upgraded to 5.5.62.

Remove or Rename the my.cnf. Not all options are compatible for 5.5, you will have to pick the required ones later:-
mv /etc/my.cnf /etc/my.5.1.cnf

Now the most important step and reason for the incremental updates. Let mysql fix the schemas of it for new version by running:-
service mysql start
mysql_upgrade

If you not running as root or have set root password for mysql, you will need to specify the user while doing upgrade
mysql_upgrade -u root -p

It should start fixing the upgrades of all your tables and says ok at the end. Restart the mysql server with:-
service mysql restart 

The mysql is now updated to 5.5 🙂

Congratulations. 

Step 2: Upgrade from MySQL 5.5 to 5.6

Just follow the exact steps of Step 1 except the rpms you should be erasing will be of 5.5 and installing new will be of 5.6. So make sure you are downloading 5.6 rpms.

rpm -e MySQL-shared-5.5.62-1.el6.x86_64 MySQL-test-5.5.62-1.el6.x86_64 MySQL-server-5.5.62-1.el6.x86_64 MySQL-devel-5.5.62-1.el6.x86_64 MySQL-embedded-5.5.62-1.el6.x86_64 MySQL-client-5.5.62-1.el6.x86_64

Download the 5.6 tar binaries, extract it and go to that folder.

rpm -ivh MySQL-client-5.6.44-1.el6.x86_64.rpm MySQL-devel-5.6.44-1.el6.x86_64.rpm MySQL-embedded-5.6.44-1.el6.x86_64.rpm MySQL-server-5.6.44-1.el6.x86_64.rpm MySQL-shared-5.6.44-1.el6.x86_64.rpm MySQL-test-5.6.44-1.el6.x86_64.rpm

Step 3: Upgrade from MySQL 5.6 to 5.7

Just follow the exact steps of Step 1 except the rpms you should be erasing will be of 5.6 and installing new will be of 5.7. So make sure you are downloading 5.7 rpms from mysql official site.

Note:

Make sure to kill the mysql process by if any error related to lock.

Find PID by:-
pidof mysql
Kill -9 PID

]]>
https://greencodes.net/upgrading-mysql-5-1-to-5-7-in-centos-6-7-or-any-red-hat-variations/feed/ 0
WordPress Site Security: Intrusion Prevention https://greencodes.net/wordpress-site-security-intrusion-prevention/ https://greencodes.net/wordpress-site-security-intrusion-prevention/#respond Fri, 10 Feb 2023 12:54:29 +0000 http://localhost/greencodes/?p=7473 Internet or web is always vulnerable to attackers since they are open to the world. A website or web application is brought to display to our web browsers as a result of many different services running behind it. Each service run in a specific port and they should be open to pass back and forth information in order to serve a web page request. Certain ports should be open for maintaining the websites for an authentic website maintainer, eg: 21/22 for uploading/transferring files and certain ports for serving the request of visitors, eg: 80/81/443 for serving http request. If not carefully maintained, such services become entry points where an intruder takes advantage of. Here are some common and best security practices that we will describe in order to protect such services and always keep our sites safe from intruders. We will specific with wordpress site in example steps below in terms of the way the components of it are discussed; plugins and themes. But it can be generalized to any other web sites and web applications. We will be focused more for general admin users or site maintainers rather than to secure development practices.

  1. We need to have at least some blockers for brute-force attacks. This is the type the intruders consistently try logging in with all possible combination of username/password unless its successful. This type of attempts can be detected very easily. For this type of attempts and other advanced security features we can install some free wordpress plugins, like, Wordfence security plugin (https://wordpress.org/plugins/wordfence/).
  2. Timely updation of the core wordpress version and plugin is required. Technology is evolving and intruders always tend to overcome with existing security measures. So it should be tightened more. Updating core of websites and plugins is one and only way the original developer can help us to secure the software they have provided to us. Outdated plugins which have not been updated in at least last 1.5 year should be removed and getting appropriate alternative is recommended. There might be having some security loop-hole left unmaintained. Carefully choose the plugins and themes before installing into the site.
  3. Adding Captcha or 2 factor authentication in WordPress admin login is best way that only valid users enter into the admin area. Using captcha in open word forms like contact us also helps to prevent bot submissions and annoying notifications.
  4. Changing administrative passwords of users and passwords of servers/cPanel should  be performed regularly. Periodic checking of valid admin users & Unwanted administrators access should also be removed. This prevents unwanted control of the site if somehow the site credentials got leaked, eg: via mobile phone or phishing.
  5. Regular scanning of the open ports of the site should be performed in case if any unwanted service is left open accidentally by developer or hosting provider. It can be done using some open source tools or with many online sites. The most popular software is nmap. Following table is an example scan result of a domain to find out the open ports using nmap:Command used
    nmap -sS -O -p 1-65535 -T4 yourdomain.com –vvvOutput:
    Open port : 21             ftp
    Open port : 25             smtp
    Open port : 53             domain ISC BIND
    Open port : 80             http nginx
    Open port : 110           pop3 Dovecot pop3d
    Open port : 143           imap
    Open port : 443           https
    Open port : 465           smtp
    Open port : 587           smtp
    Open port : 993/tcp     imap Dovecot imapd
    Open port : 995/tcp     pop3 Dovecot pop3d
    Open port : 2082/tcp
    Open port : 2083/tcp
    Open port : 2095/tcp
    Open port : 2525/tcp
    Open port : 2096/tcp
    Open port : 18765/tcp   The above open ports are for standard services and doesn’t look to be vulnerable but the problem here is anyone can easily scan over them. Ports are for services and if in any case, if sensitive ports are left open, they are vulnerable and become target to automated port scanning malware script that are always running to seek out someone’s mistake. A secure server or hosting provider should block such port scanning. This can also be considered as a measure of how seriously a hosting provider take security issues.
  6. Scanned the website with common popular online vulnerability scanner sites especially to check if there are any cross site scripting, ssl signature issues, loopholes or thing like that if there in the site to the public. No information should be shared in such sites though, they should  just be given url and ask to check if they can find any holes in the site/server/ssl. This should be done especially after any updates are made to the site by the developer or by plugin/theme/core engine update.
    Some popular examples at the time of writing:
    https://scanmyserver.com,
    https://www.ssllabs.com,
    https://app.webinspector.com/,
    https://pentest-tools.com/website-vulnerability-scanning/xss-scanner-online
    https://sitecheck.sucuri.net.
  7. Choose hosting plan that give complete ftp/ssh and access logs. This will be helpful to track down the intruders and find the cause of it. Mostly dedicated servers like aws ec2 instance give this access. Shared hosting rarely have this option to shared hosting accounts. Make sure the hosting has firewall and software to deal with most common attacks like ddos.
  8. Make sure the hosting regularly scan the scan the site files and databases and the anti malware scanners are updated with the most common type of vulnerability detection pattern or database.
  9. All the sql dumps and zipped files as backup of the site should not reside in web root (inside pubic_html) or in inner folder of it unless they are protected by external access through apache module rules like .htaccess. Anyone can download those databases/files easily through website url via normal scanning since they are publicly accessible. The intruders not only get your sensitive data from database dumps and private files but also know the internals of the system and find out the weak areas for later intrusion attempts to production data.
  10. Get automated backup of whole files and database in at least every 15 days interval so that if any section of the database or file gets infected, these can be replaced.
  11. Always have SSL (https) installed in your site, especially if it involves user data pass through the network. This prevents header tempering and Eavesdropping attack.
  12. It is always a best practice to put your website behind a reverse proxy for availability and security (hiding the actual ip address).
]]>
https://greencodes.net/wordpress-site-security-intrusion-prevention/feed/ 0
NLP for Nepali Text – Console Printing & DB Handling https://greencodes.net/nlp-for-nepali-text-console-printing-db-handling/ https://greencodes.net/nlp-for-nepali-text-console-printing-db-handling/#respond Fri, 10 Feb 2023 12:53:19 +0000 http://localhost/greencodes/?p=7471 Nepali language uses non-latin or Devanagari font. So unlike regular english language, dealing with text like Nepali requires special tools and techniques.  The struggle starts with the following two things:

  • Unable to print the text in console (linux terminal /windows command line). They are unreadable.
  • Reading/writing text in database

Printing Nepali text in Console/Terminal
While doing development or running some machine learning libraries, we frequently need to print out the text in terminal. For nepali text, getting them printed out in terminal is challenging. But there are solutions to it.

There are many different solutions to print unicode characters to display in format of UTF-16 and UTF-8 for languages like C or C++.
 In C++,
_setmode(_fileno(stdout), _O_U16TEXT);

This settings works but not to all languages like Nepali, Arabic or Hebrew. It was not helpful since it did not correctly display all Nepali text. Furthermore, my work was also requiring to print out Nepali text from python language interpreter into the terminal. For it, in linux terminal, I tried to setup all languages and locals and managed to display Nepali text but it also had limitations of displaying all characters correctly. Not all words were corrected displayed and looked like I was still lacking the actual fonts (tried more than 10 that should have supported devanagari font). 

So instead of wasting my time in trying with every available fonts and settings, I decided to to with an awesome new terminal called Konsole. You can download it from here, https://konsole.kde.org/. I was able to install it so easily with a single line command and get it running into my Ubuntu 18 machine straight away. 

sudo apt-get install konsole

It was of the version 4:17.12.3 at the time of my experimentation. After the installation, Just run it from GUI and we will be presented with terminal similar to linux inbuilt terminal (For linux variations having GUI). All nepali texts were correctly displayed and another interesting feature of it was it has all the features and functionalities that a normal terminal has. So you can run any command with it and play along with any unicode non-latin texts.

Reading-Writing Nepali text in Database
Another challenge in NLP work for Nepali text is properly storing and fetching data in/out from database. I mostly worked with MySQL/Mariadb for it so typical example will be for this database but the concept will be equally applicable to other data storage technologies. 

Storage
The first and most important setup to do is to make sure the mysql character set and collation is set to utf8. Personally I prefer utf8_general_ci. This is how we can do it after logging into mysql terminal or from phpmyadmin SQL Query input. There are various ways to do it like via my.cnf of db config file etc but the simplest way is to run straight query to the engine for the particular database or table.

ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;

This will change the character set and collation of your whole database. Do not forget to replace the dbname by your actual database name. 

To do this only for particular table:

ALTER TABLE tablename CHARACTER SET utf8 COLLATE utf8_general_ci;

Reading/Writing from popular programming language

Python
Python handles nicely the encodings without any extra parameters while reading from mysql database. Install mysql connector through pip and import it. 

pip install mysql-connector-python

You can choose the specific version if you like

pip install mysql-connector-python==8.0.11

import mysql
import mysql.connector
mydb = mysql.connector.connect(
 host="localhost",
 user="manoj",
 passwd="pass",
 database="db"
)

mycursor = mydb.cursor()
mycursor.execute("SELECT fields FROM table")
result = mycursor.fetchall()

And do the straight query as above (not focused here on best practices and structured way)

For writing, straight execute function will again work as long you have maintained the character encoding and collation. 

Java
For connecting mysql with java application, I used mysql.jdbc.Driver. The jar file after downloading from mysql official site was added into the CLASSPATH so that Java Virtual Machine or the Java compiler know the location of this package.

export CLASSPATH=:/home/manoj/commons-lang3-3.9.jar:.:/usr/share/java/mysql-connector-java.jar:.:/home/manoj/commons-text-1.6.jar

Note: Had to use commons-lang and commons-text packages as well for text processing.

I think had to explicitly define the characterEncoding while connecting to db. Since I was in local and no SSL was setup for local connection, set the useSSL to False. 

String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/lda?characterEncoding=UTF-8&useSSL=false";
try {
        Class.forName(myDriver);
} catch (Exception ex) {
        System.out.println("could not connect to mysql. exiting.");
}

Connection conn = DriverManager.getConnection(myUrl, "root", "manoj");

Make sure your mysql is running on 3306 port and db username/password and db name matches to yours.

I was able to get the Nepali text by simple fetch query

String query = "SELECT * FROM table";
// create the java statement
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);

For inserting the data, I was able to do it once the connection was made with defined characterEncoding.

query = "INSERT INTO ……..";
st.addBatch(query);
st.executeBatch();

PHP
The character set of mysql had to be set to utf8 to read and write in PHP.

// Create connection
$conn = new mysqli(‘localhost’, ‘manoj’, ‘db’, ‘db’);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}

//set character set
mysqli_query($conn, "set names 'utf8'");
$sql = "SELECT * from table";
$result = mysqli_query($conn, $sql);

The same connection object $conn was able to insert data without any further processing specific to character encoding. 

Note: All of the above examples assume you have already set the character and collate to utf-8 in your mysql database.

]]>
https://greencodes.net/nlp-for-nepali-text-console-printing-db-handling/feed/ 0
Troubleshooting DNS Issues with dig (Domain Information Groper) https://greencodes.net/troubleshooting-dns-issues-with-dig-domain-information-groper/ https://greencodes.net/troubleshooting-dns-issues-with-dig-domain-information-groper/#respond Fri, 10 Feb 2023 12:51:16 +0000 http://localhost/greencodes/?p=7466
  • By default, it queries A record.
    An A record is used to find the IP address of a computer connected to the internet from a domain name. From Linux terminal,

    manoj@local: dig greencodes.net
    
    ; <<>> DiG 9.11.3-1ubuntu1.8-Ubuntu <<>> greencodes.net
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 29043
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
    
    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 65494
    ;; QUESTION SECTION:
    ;greencodes.net.               IN     A
    ;; ANSWER SECTION:
    greencodes.net.       600      IN     A    43.255.154.30
    
    ;; Query time: 118 msec
    ;; SERVER: 127.0.0.53#53(127.0.0.53)
    ;; WHEN: Mon Jul 01 12:18:18 +0545 2019
    ;; MSG SIZE  rcvd: 59

    Don’t waste time looking other info but except the Question and Answer Section.
    This extra info can be removed by +short

    manoj@local:dig greencodes.net +short
    43.255.154.30
  • Sometimes there might be an issue with your ISP or with router. Most commonly if the DNS cache is still not cleared, the routers nearest to your computer might give old or non-updated information. Since the request starts with your local computer, with information from, /etc/resolv.conf, it uses the DNS server listed in that file. Many routers act as a DNS server or at least the DNS server of our ISP. To change the DNS server while doing query, so that a cached copy is not replied, we can explicitly define the DNS server with @DNS_SERVER as follow:
    dig @8.8.8.8 greencodes.net +short

    Here 8.8.8.8 is the ip address of Google DNS server and we explicitly used it to query of DNS question. The router or local ISP DNS server will not be used to query to reach out to the server.

  • A Start of Authority record (abbreviated as SOA record) is a type of resource record in the Domain Name System (DNS) containing administrative information about the zone, especially regarding zone transfers.
    dig @8.8.8.8 greencodes.net SOA
  • To get MX record which gives the information about where and how the emails are hosted, we can pass MX.
    dig greencodes.net MX
  • ]]>
    https://greencodes.net/troubleshooting-dns-issues-with-dig-domain-information-groper/feed/ 0
    React JS – Quickstart for jQuery Guys https://greencodes.net/react-js-quickstart-for-jquery-guys/ https://greencodes.net/react-js-quickstart-for-jquery-guys/#respond Fri, 10 Feb 2023 12:49:58 +0000 http://localhost/greencodes/?p=7463
  • It’s a library, not a complete framework. So it’s lightweight and best library to hook into existing project (PHP/Python/Ruby) which need reactive DOM due to its virtual lightweight DOM feature. Example usage: updating a huge page by simple javascript can crash the browser. Here comes the React JS.
  • Dom elements bound with internal react state objects
  • This automatically detects the changes in the object state values and updates the value of element bound to it. 
  • Each element in a component must have unique key=”” and that corresponds to the state object
    • Main file in index.js which loads the main component
    • Each component then loads the corresponding sub component. Component loading is done by including the jsx file
    • Jsx file notation is like html notation. Each jsx file has render() method and state() property.
    • When loading a component, it calls the render() method internally
    • Variables are put within {  } notation.
    • It’s not a template engine. So all logic should be written in pure JS notation.
    • Components are reusable.
    • Normally main component starts at index.js. This includes the main App which then can include the child components. Each child component then include sub child components are so on. So any section of a page of project that we want to make reactive or to use react, its rending starts from index.js.
    • Multiple subcomponent of a component if needed to include, we can use 
    <React.Fragment>
    
    </React.Fragment>
    • To include a component, need to import the jsx file and the classname of it like:

               import ComponentName from “PATH_TO_COMPONENTJSX_FILE/JSX_FILE_NAME”;

    • Parent component can pass the state variables to child components via props. If need to pass the state variables to the same level component, need to lift the state property up. A parent can pass the state to all the children.
      The props can be accessed by child via,

              this.props.passedEventName

              So altogether, references are passed through component include block downwards.

    • Instead of using class, a simple stateless functional component can also be used so that a simple component doesn’t neccessarily need to have class. 
    const NavBar = () => {
    
          return (
    
               <nav className=”navbar”>.....</nav>
    
         );
    
    };

             This should be exported.

             export default NavBar;

    • Lifecycle hooks of each component can be used to hook certain events. There are three life cycle phases: mount, update and unmount. Each has its own hook. Following are the most commonly used lifecycle hooks:
    • Constructor of the parent class is called using
      super()
    class App extends Component {
    
    constructor(){
    
         super();
    
       }
    
    }
    • ComponentDidMount is the best place to get data from server by making ajax request. Can simply call it inside the component class as a function like
    ComponentDidMount(){
    
       //script to run after mounting the component
    
    }
    
    
    
    • Render method is the method where we play along with our html doms to manipulate. When a component is rendered, all its components are rendered recursively.
    • Lifecycle hooks can not be used in stateless functional components
    • ComponentDidUpdate() of  Update phase is the best place to detect any requirement like if we need to load more data by calling ajax to server.
    • componentWillUnmount() can be used to remove any event listener or other cleanups for that particular dom before deleting it from dom tree.
    ]]>
    https://greencodes.net/react-js-quickstart-for-jquery-guys/feed/ 0
    Upgrading cPanel/WHM – Dealing with conflicting rpms https://greencodes.net/upgrading-cpanel-whm-dealing-with-conflicting-rpms/ https://greencodes.net/upgrading-cpanel-whm-dealing-with-conflicting-rpms/#respond Fri, 10 Feb 2023 12:48:57 +0000 http://localhost/greencodes/?p=7460 While running the cPanel version update from its whm web interface, it is most likely to encounter conflicting rpms error if there are any manual rpms updates done and same are also accounted to get updated by cPanel. Of Course the manual update was needed because that particular service was not updated correctly by its built in graphical interface. This is because the cPanel/WHM has their own set of packaging for many of their services to include their further customization to communicate with their other custom dependent packages. In this particular example we will see how they provide mysql service in centos server.

    The rpms packaged by MySQL team works well for RHEL and variations of it like centos. cPanel has their own packaging for it though. So if we install rpms directly from third party like mysql, they will get conflict with their custom rpms that they manage to communicate. 

    When such an issue comes, after you are done with regular updates in normal way, run this

    /usr/local/cpanel/scripts/check_cpanel_rpms

    This will check which rpms are missing from the system, which ones got conflict and which ones need repair or reinstall. They have managed excellent scripts to do all this checking. If any of conflicts as below is encountered:

    file /usr/share/mysql/mysql_system_tables.sql from install of MySQL56-server-5.6.35-1.cp1156.x86_64 conflicts with file from package MySQL-server-5.6.44-1.el6.x86_64

    If we try out some updates from the WHM GUI, errors like this will be shown:

    Problems were detected with cPanel-provided files which are RPM controlled…

    The solution for issues like above it is very simple. Just remove your conflicting rpm packages by

    rpm -e MySQL-server-5.6.44-1.el6.x86_64

    We are safe here to do so because conflicting package is of almost the same mysql version and we don’t need to do mysql_upgrade for the schemas to update. If the version is different in major releases like 5.1.X, 5.5.X, 5.6.X and 5.7.X, we will need to make sure the rpms are updated the upgrade of schema is performed by running

    mysql_upgrade

    With username and password.

    After that just remove those conflicting rpms and let intelligent cPanel script check missing rpms and perform an install or repair for you by running

    /usr/local/cpanel/scripts/check_cpanel_rpms --fix

    This will install those missing rpms from their own server that exactly match with their custom dependant package. At  the other side your service is also updated. 

    ]]>
    https://greencodes.net/upgrading-cpanel-whm-dealing-with-conflicting-rpms/feed/ 0
    Angular for jQuery Professionals – Part 1 https://greencodes.net/angular-for-jquery-professionals-part-1/ https://greencodes.net/angular-for-jquery-professionals-part-1/#respond Fri, 10 Feb 2023 12:47:47 +0000 http://localhost/greencodes/?p=7457
  • Clean structure, reusable code and testable components
  • One common way to start the angular application development is via NodeJS angular CLI app. This will give ng command to create and maintain the project files
  • To start a new project

    ng new project-name 

    • The Angular CLI has its own lightweight web server that angular compiles. By default, the port 4200 is used by angular web server.

    ng serve

    • The root has node_modules folder, which stores all the third party libraries. The src folder has the actual source codes of the project.
    • The execution starts at main.ts file of the root. The html block that is main.ts will serve is index.html in the root. Package.json file in the root lists out all the dependencies and modules. The typescript compiler setting is in tsconfig.json file there in the root. Typescript compiler converts the typescript to javascript so that web-browsers can understand them.
    • The tiny web server of angular CLI uses webpack that automatically bundles all the js and css files. That includes compression and merging to a single file. So unlike the traditional CMS like wordpress which we have to do some extra work for it, here in angular, It does this automatically. If any html of typescript code is changed, the web server automatically detects it,restarts the server and refreshes the browser automatically.
    • AngularJS first came in 2010. It was later updated with typescript implementation and more structured and easy for developers. They call it Angular. So the major change is only from version 1 and later. The Angular 2 and later are just minor updates and fixes. To simply term it, AngularJS is for version 1 and Angular simply denotes version 2 and later.
    • VSCode is better for Angular applications in terms of auto correction, auto import plugin, shortcuts and syntax highlighting (actually to most of all other javascript frameworks).

    TypeScript Fundamentals

    Angular uses TypeScript for scripting. Here are some fundamentals of it:

    • It’s an extension of javascript. Every script of javascript are a valid typescript. So it can be termed as superset of javascript.
    • It has type casting before declaring variables, though not necessarily. Its object oriented i.e it uses classes, constructors, private/public methods etc.
    • Typescript transpiler should be installed through npm

    npm install typescript

    The transpilation can be done by running the command

    tsc filname.ts

    This creates a .js file in the same folder with same name but as .js extension. When compiling the angular application, this happens automatically under the hood so that browsers can understand.

    Things that are in Typescript but not in Javascript

    • By default, Typescript generates ES5, which is the oldest version of javascript, supported by all browsers. (later version are ES2016, ES2017…). Let keyword is supported after 2015 version, which may not be supported by some older browser versions. 
    • Typescript compiler reports error but still tries to generate valid javascript code
    • Type Assertions i.e to explicitly tell the compiler the type of variable  can be done by two ways 

    let message;

    message = ‘abcd’

    let ct = (<string>message);

    Or

    let ct = (message as string); 

    • To define a function, it is not necessary to write the word function, instead can use arrow function
    let c = function(p){
    
    console.log(p)
    
    }

    The above function in typescript can be replaced with arrow function as

    let c = (p) => {
    
    console.log(p)
    
    }

    This way, the code is cleaner.

    • If you are familiar with PHP, the classes, methods and properties usage are exactly the same. Initialize the class with new keyword and call the members with. The properties inside class is accessible via this keyword.
    • Declaring constructor function is absolutely similar to PHP. the constructor() is reserved function inside the class. Adding ? in constructor parameter make it optional.
    class human{
    leg: ‘2’;
    hand: ‘3’
    
    constructor(leg ?: number){
    }
    }
    • The access modifiers are private, public and protected. The usage and meaning are exactly the same way. 
    class human{
    private leg: ‘2’;
    public hand: ‘3’
    
    constructor(leg ?: number){
    }
    }
    
    let John = new human();
    • The access modifiers can be used directly inside constructor
    • To export the class to use outside of the file, use export keyword
    export class human{
    private leg: ‘2’;
    public hand: ‘3’
    
    constructor(leg ?: number){
    }
    
    }

    To import

    import {CLASS_NAME} from ‘RELATIVE_PATH/MODULE_OR_FILENAME’;

    MODULE_OR_FILENAME should be without .ts or without typescript extension.

    • Class, method, attributes etc can be exported from a component (a file) and be used in other component (file) like the way stated above.
    • Each component has html markup. The custom element is defined and attached inside the component.
    • Components can be generated using angular CLI
      ng g c hero
    import { Component, NgModule, OnInit } from '@angular/core';
    
    import { BrowserModule } from '@angular/platform-browser';
    
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    class Hero {
    
      id: number;
    
      name: string;
    
    }
    
    
    @Component({
    
      selector: 'app-root',
    
      template: `
    
          <h1>{{title}}</h1>
    
          <pre>{{heroes | json}}</pre>
    
        `,
    
      styleUrls: ['app/app.component.css']
    
    })
    
    
    @NgModule({
    
      imports: [BrowserModule],
    
      declarations: [AppComponent],
    
      exports: [AppComponent],
    
      bootstrap: [AppComponent]
    
    })
    
    export class AppModule {}
    
    platformBrowserDynamic().bootstrapModule(AppModule);
    
    const HEROES: Hero[] = [
    
      { id: 1, name: 'Bombasto' },
    
      { id: 2, name: 'Tornado' },
    
      { id: 3, name: 'Magneta' }
    
    ];
    
    
    function getHeroes(): Promise<Hero[]> {
    
      return Promise.resolve(HEROES); // TODO: get hero data from the server;
    
    }

    It will then automatically generate all the basic necessary files for you in a separate directory on the current directory. It will also automatically update app.module.ts file, which is the main file to register all the modules in the application

    • The beauty of Angular is the data-binding. The dom value of a variable is automatically updated if the variable value is updated. This is done internally by the angular framework. Variables can be displayed in the template by using the two curly braces:

    {{ the-variable }}

    This curly brace also accepts strings to concatenate with the variable using + operator as in normal javascript concatenation. This even accepts the function call from there that is defined inside the class of the component.

    • Backticks can be used in template string (string implementation, not .html template) to make multiline 
    • The event handling is done by old angular way, eg: for button click

    <button (click)=”myFunc()” ></button>

    myFunc is the function defined inside the component class for this specific component.

    Input field can be bound with # method. Can be passed into the function on click event like this:

    <input type=”text” #username />

    <button (click)=”myFunc(username.value)” ></button>

    This will need to import forms module

    ]]>
    https://greencodes.net/angular-for-jquery-professionals-part-1/feed/ 0