Saturday, September 8, 2018

Portable GIT > A way to access Git without installing it on Windows

This is the portable edition of Git, click below link to download it from below link provided, a command-line application that helps engineers and designers to keep all versions of a code as well as images or layout, by storing all data in a collection of snapshots taken from a small filesystem.
PortableGit-1.9.5-preview20150319
Portability advantages
Since there is no installation required, you can just download and extract the archive files to any local hard disk and directly execute Git just clicking on it. There is also the option to save it to a USB flash disk or other removable (temporary) storage unit, in order to launch it on any PC here and there easily and without previous installation. As like most installers we install on windows, Portable Git does not add new entries to the Windows registry or Start menu, thus leaving no traces behind after its removal. Because they are not installed in the system, they are just standalone.
Rich and simple-to-activate commands
As Git is a console application, all its options as well as functionalities are accessible from a Command Prompt window. Thus, it is possible to add file contents to the index, locate changes which introduced bugs via binary searches, list, create and delete branches, record changes to the repository, via commit logs, join together two or more development histories, and many others. A user name and email address can be assigned in order to restrict the access of other users.

Saturday, September 1, 2018

Extract the contents from an .ISO file without burning the .ISO to disc using third party application

We need it frequently to install ISO image file into our Windows operating system. One way is to burn ISO into USB or DVD. But there is another way, we can extract contents from an ISO file into hard drive using third party tools. Below list of some tools:
  1. IsoBuster
  2. Daemon Tools
  3. Pismo File Mount or Download from here
First I will demonstrate how we can extract an ISO file using Pismo File Mount. Download Pismo File Mount from above link. then click on an ISO file will show menu as below:
Click on very first option named "Mount" will show a folder with extract files and folders. From there you can find your installation exe file and run to install your desired software. Actually Mounting an ISO file create a virtual drive like below image. You can then Eject that virtual drive by right click on that drive and select "Eject" option from options.

Wednesday, August 22, 2018

Grails on Groovy > Way in Grails to Eager Fetch the Whole Record | Load Related Entity With Single Query

I am trying to find if there is any way in Grails to eager fetch complete records instead of a left Join.
For example, let you have domain named Tabel1 with following structure and another domain named Table3 below:
package com.pkm

class Table1 {
    Long id
    String name
    String roll

    static mapping = {
        table("table1")
    }

    static belongsTo = [
            table3: Table3
    ]

    static constraints = {
        table3 nullable: true
    }
}



package com.pkm

class Table3 {
    Long id
    String name
}
So when you get/list Table1, what will be the default behavior? It will load only Table1 data, not other associated data like Table3.
There is a procedure to load selected associated by joining them. See the below example, enabled eager face data when creating criteria:
package com.pkm

import grails.transaction.Transactional
import org.hibernate.FetchMode
import org.hibernate.sql.JoinType
import org.springframework.transaction.TransactionStatus

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        List list = Table1.createCriteria().list {
            createCriteria("table3", "j3", JoinType.LEFT_OUTER_JOIN)
            setFetchMode("j3", FetchMode.JOIN)
            order("id", "desc")
            setMaxResults(20)
        }
        list.each { Table1 table1 ->
            println("Name=${table1.name}, Table3=${table1.table3?.name}")
        }
    }
}
Now we will print the query generated:
select this_.id as id1_0_1_, this_.name as name2_0_1_, this_.roll as roll3_0_1_, this_.table3_id as table4_0_1_, j3x1_.id as id1_2_0_, j3x1_.name as name2_2_0_ from table1 this_ left outer join table3 j3x1_ on this_.table3_id=j3x1_.id order by this_.id desc limit ?
You observed that in select query, both Table1 and Table3 exists. And this is how we can implement eager face data when creating criteria builder to get data.

Saturday, August 11, 2018

Setting Up Recaptcha 2.0 with JavaScript and PHP

reCAPTCHA need to verify bots (automatic system) can't take advantage of your site. reCAPTCHA 2.0 is somewhat different than the old reCAPTCHA. In version 1.0 it required to type text but now in 2.0 it’s simply a click of a button as below image.

The term of verifying front end users is a bit different. A variable named "g-recaptcha-response" is sent through a POST request to your server-side script, and along with your reCAPTCHA secret key that you get when you sign up for your website, you need to pass that secret key along to Google to tell that the user is a bot or not to determine by system. The response from Google is a JSON response on success for failure both case, so that we will be using file_get_contents() and json_decode() to fetch and parse the response and decide that front user is valid or not.


The below is just a HTML form you should create to see captcha in your desired page. The div element with the class of "g-recaptcha" is the element where we want to place our Google captcha (reCAPTCHA). You need to replace data-sitekey with the key you get from google when you sign up for reCAPTCHA (https://www.google.com/recaptcha/intro/index.html).
<form method="post" enctype="multipart/form-data">
    <div class="g-recaptcha" data-sitekey="YOUR_KEY"></div>
    <button type="submit">CHECK RECAPTCHA</button>
</form>
But I will show another technique how to show reCAPTCHA using JavaScript. Below is a simple script to show how you can integrate reCAPTCHA using JavaScript. But server side validation using PHP. Use need to create an div with ID (suppose, you can create your div with other ID) captcha_container
<script src='https://www.google.com/recaptcha/api.js'></script>

var captchaContainer = grecaptcha.render('captcha_container', {
    'sitekey' : 'Your sitekey',
    'callback' : function(response) {
        console.log(response);
    }
});
Now time to validate reCAPTCHA from server side.
<?php
$url = 'https://www.google.com/recaptcha/api/siteverify';

$data = array(
    'secret' => 'YOUR_SECRET',
    'response' => $_POST["g-recaptcha-response"]
);

$options = array(
    'http' => array(
        'method' => 'POST',
        'content' => http_build_query($data)
    )
);

$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success = json_decode($verify);

if ($captcha_success->success == false) {
    echo "<p>You are a bot! Go away!</p>";
}
else if ($captcha_success->success == true) {
    echo "<p>You are not not a bot!</p>";
}

Thursday, July 12, 2018

Java > Convert text content to Image > Using Java Create An Image And Save To File With Transparent Background

For example, from the string Pritom K Mondal, I would like to generate this simple image:
package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class TextToImage {
    public static void main(String[] args) {
        String text = "Pritom K Mondal";

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        Font font = new Font("Arial", Font.PLAIN, 48);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(text) + 20;
        int height = fm.getHeight();
        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        g2d.drawString(text, 10, fm.getAscent());
        g2d.dispose();
        try {
            ImageIO.write(img, "png", new File("Image.png"));
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
And output is like below:


Grails on Groovy over Java > Email Address Validation Using Regex

Below is a sample code snippet to validate email address using REGEX
package com.pkm;

import java.util.regex.Pattern;

public class EmailValidationRegex {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+([\\.\\+]?[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static Pattern _pattern = null;

    public static void main(String[] args) {
        check("pritomkucse+regex.test@gmail.com");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm.");
        check("pkm.+invalid@no.valid");
    }

    static void check(String email) {
        System.out.println(email + " > " + valid(email).toString().toUpperCase());
    }

    static Boolean valid(String email) {
        return getPattern().matcher(email).matches();
    }

    static Pattern getPattern() {
        if (_pattern != null) return _pattern;
        _pattern = Pattern.compile(EMAIL_PATTERN);
        return _pattern;
    }
}

Friday, July 6, 2018

Grails on Groovy > GORM dirty checking of instance and properties > grails - tell me if anything is dirty > Checking for Dirty (Updated) Properties on a Grails Domain

GORM provides Grails developers lots of useful hooks, events, methods, and functionality, very important is domain events that inform you when domain objects are being created, updated, and deleted. Within these events, a common use-case is to determine if a particular domain property has changed, and to act accordingly.
Below is a code snippet of how you validate your domain before insert or update.
package com.pkm

class Table1 {
    Long id
    String name
    String roll

    static mapping = {
        table("table1")
    }

    static hasMany = [
            scores: Table2
    ]

    void beforeValidate(){
        println("BEFORE VALIDATE")
    }

    void beforeInsert(){
        println("BEFORE INSERT")
    }

    void beforeUpdate(){
        println("BEFORE UPDATE")
    }
}
Now, how can you get the actual value of that object? The actual value is modified and you want to get the persisted value. One “not so good” idea is to call refresh() which will load the object from the database again which might be a huge data retrieval in few cases. To solve this problem, GORM has given a simple method which will do the work for you:
Below is a example of how you can see which fields are updating in current transaction using below code snippet
void beforeUpdate(){
    println("BEFORE UPDATE")
    this.dirtyPropertyNames.each { String fieldName ->
        def oldValue = this.getPersistentValue(fieldName)
        def newValue = this.getProperty(fieldName)
        println("\t> VALUE CHANGED FOR $fieldName FROM $oldValue TO $newValue")
    }
}
The best place to check for dirty properties is usually in the beforeUpdate event. The beforeInsert and afterUpdate events may also seem like good choices at first, but they may not be depending on the use-case. Before inserting, all properties are dirty because they are new, so they haven't really changed they have just been created. After updating, none of the properties are dirty because the new values have already been persisted in your database. These events provide plenty of value if used correctly, but may not always be the best place to check for dirty domain properties.
One domain in particular that I always perform dirty property checks on is any User domains that my application requires. For instance, if a User object's password has changed, you may want to be alerted in the beforeUpdate event and encrypt the password before it is inserted into your database.
You also can check if an existing field is dirty or not using
this.isDirty("fieldname")
Be careful not to perform any saves on the domain within these events, as you will get a StackOverflowException. (The event calls .save(), restarting the whole event cycle, where .save() will be called again, and so on. This infinite loop will never end, and the exception will be raised.)
Otherhand you can check if entire session (hibernate session) is dirty or not. so below is an example how to check if whole hibernate session is dirty or not.
package com.pkm

import grails.transaction.Transactional
import org.springframework.transaction.TransactionStatus

import org.hibernate.SessionFactory
import grails.util.Holders

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        Table1 table1 = Table1.first()
        table1.roll = System.currentTimeMillis().toString()
        table1.save()

        SessionFactory sessionFactory = Holders.applicationContext.getBean(SessionFactory)
        Boolean isDirty = sessionFactory.currentSession.isDirty()
        println("IS SESSION DIRTY=${isDirty.toString().capitalize()}")
    }
}