Thursday, December 28, 2017

PHP Round up to specific number | Round to nearest number | Round to next multiple of number



<?php
#Round to the next multiple of 5, exclude the current number
function roundNumberToUp($n, $x = 5)
{
    return round(($n + $x / 2) / $x) * $x;
}
roundNumberToUp(10);    #10
roundNumberToUp(10.2);  #15
roundNumberToUp(11.5);  #15

#Round to the nearest multiple of 5, include the current number
function roundNumberToNearest($n, $x = 5)
{
    return (round($n) % $x === 0) ? round($n) : round(($n + $x / 2) / $x) * $x;
}
roundNumberToNearest(10);   #10
roundNumberToNearest(10.3); #10
roundNumberToNearest(10.5); #15
roundNumberToNearest(11.7); #15

#Round up to an integer, then to the nearest multiple of 5
function roundNumberToNearestAsInteger($n, $x = 5)
{
    return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
}
roundNumberToNearestAsInteger(10.3);    #15
roundNumberToNearestAsInteger(11.7);    #15



URL Redirect: Redirecting From of an iFrame


IFrame


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>IFrame Title</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("button").click(function() {
                window.top.location.href = 'https://pritomkumar.blogspot.com';
            });
        });
    </script>
</head>
<body>
<button type="button">Reload IFrame Parent</button>
</body>
</html>

To modify your iframe embed code, you will add the following attribute inside the opening iframe tag:
sandbox="allow-top-navigation allow-scripts allow-forms"

Container of IFrame


<style type="text/css">
    iframe {
        width: 40%;
        height: 95%;
        margin-left: calc(30%);
        border: 1px solid lightgray;
    }
</style>
<div>
    <iframe src="iframe-html.php" sandbox="allow-top-navigation allow-scripts allow-forms"></iframe>
</div>

Get Latest Record In Each MySQL Group



Table=check_group_by
id   group_by    value
-------------------------
1    1           Value 1
2    1           Value 2
3    1           Value 3
4    2           Value 4
5    2           Value 5
6    3           Value 6

Query will be as like:

SELECT id,group_by,value FROM check_group_by
WHERE id IN (
 SELECT MAX(id) FROM check_group_by GROUP BY group_by
)





SQL Fiddle Example



Friday, December 22, 2017

Get code line and file name that's executing processing the current function in PHP


function log() {
    try {
        $bt = debug_backtrace();
        $fileAndLine = "";
        for ($i = 0; $i < 10; $i++) {
            $row = $bt[$i];
            if (isset($row["file"]) && isset($row["line"])) {
                $fileAndLine = $row["file"] . "::" . $row["line"];
                $i = 50;
            }
        }
        return $fileAndLine;
    }
    catch (Exception $ex) {
        return "";
    }
}


Tuesday, December 19, 2017

Grails on Groovy: Get Retrieve MySQL Database name from DataSource | Get List of MySQL Tables | Execute MySQL Raw Query




import grails.util.Holders
import org.hibernate.SessionFactory
import org.apache.commons.lang.StringUtils

def dataSource
SessionFactory sessionFactory

String connectionURL = dataSource.targetDataSource.targetDataSource.poolProperties.url
connectionURL = StringUtils.substringAfterLast(connectionURL, '/')
connectionURL = StringUtils.substringBefore(connectionURL, '?')
println(connectionURL)

String databaseName = sessionFactory.currentSession.createSQLQuery("SELECT DATABASE()")
        .setReadOnly(true).setCacheable(false).list().first()
println(databaseName)

String query = "SELECT table_name FROM information_schema.tables WHERE table_schema='$databaseName'".toString()
List list = sessionFactory.currentSession.createSQLQuery(query)
        .setReadOnly(true).setCacheable(false).list()
println(list.size())
println(list)




Saturday, December 16, 2017

MYSQL Group Concat Select Some Selected Rows Only | Use Sort In Group Concat | Sort MySQL Rows in Group Concat

Its so simple. Just need to do below thins:
SELECT SUBSTRING_INDEX(GROUP_CONCAT(x.id ORDER BY x.nx DESC), ',', 2) as row_name from some_table GROUP BY some_field
It will select First two values only.
It total value of GROUP_CONCAT is "1,2,3,4,5" Then Using SUBSTRING_INDEX would be like "1,2"
You can use DISTINCT in GROUP_CONCAT function like
SUBSTRING_INDEX(DISTINCT(GROUP_CONCAT(x.id ORDER BY x.nx DESC)), ',', 2)

Friday, December 8, 2017

Mysql GROUP_CONCAT of first n rows || Selecting first and last values in a group || Select first and last row from group_concat when grouping sortable days




select s.id,count(e.id) as total,
substring_index(group_concat(e.id order by e.id asc),',',5) as group_value
from students s left join exams e on s.id=e.student_id
group by s.id
order by count(e.id) desc




Thursday, December 7, 2017

PHP Call Static Function Method Dynamically Based on __callStatic Method



<?php
abstract class ParentClass {
    public static function __callStatic($method, $args) {
        echo "Method=".$method.",Args=".json_encode($args)."\r\n<BR/>";
    }
}

class ChildClass extends ParentClass {
    public static function x1() {
        $args = func_get_args();
        call_user_func_array(
            array(parent::class, __FUNCTION__), $args
        );
    }
}

ChildClass::x1("x1", 10, 20);
ChildClass::x2("x2", 30, 40);


And output would be like:


Method=x1,Args=["x1",10,20] 
Method=x2,Args=["x2",30,40] 

Sunday, December 3, 2017

GRAILS GROOVY | GString Template Engine | Parse Simple String AS GString Template | String GSP Parser




def gEngine = new groovy.text.GStringTemplateEngine()
def binding = ["a": "a"]
String testVar = gEngine.createTemplate("MY ENGINE STRING AS=\${a}").make(binding).toString()
println(testVar)

Saturday, December 2, 2017

jQuery.noConflict() | Avoiding Conflicts with Other Libraries


(function() {
    function loadJQuery() {
      var startingTime = new Date().getTime();
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      script.onload = function() {
        var $j = jQuery.noConflict();
        jQuery = $;
        $(function() {
              var endingTime = new Date().getTime();
              var tookTime = endingTime - startingTime;
              window.alert("jQuery previous version=" + $.fn.jquery + ", version=" + $j.fn.jquery);
          });
      };
      document.getElementsByTagName("head")[0].appendChild(script);    
    }
    loadJQuery();
})();


Check here for JSFiddle

Load jQuery with Javascript and use jQuery | Load jQuery dynamically




(function() {
    function loadJQuery() {
      var startingTime = new Date().getTime();
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      script.onload = function() {
        var $ = window.jQuery;
        $(function() {
              var endingTime = new Date().getTime();
              var tookTime = endingTime - startingTime;
              window.alert("jQuery is loaded, after " + tookTime + " milliseconds!, version=" + $.fn.jquery);
          });
      };
      document.getElementsByTagName("head")[0].appendChild(script);    
    }
    if (window.jQuery) {
     alert("JQuery loaded");
    }
    else {
     alert("JQuery not loaded");
      loadJQuery();
    }
})();


Check here for JSFiddle



GIT | View Changed Details For Files By Commits | View List Of Files Changed During Different Commits

This below command will show changes made during last 3 commits for specific file defined
git diff HEAD~3..HEAD -- project/location/file.name
This command will list files changes made during last 3 commits
git diff --name-status HEAD~3..HEAD
This command will list files changes made during last 3 commits with changes
git diff HEAD~3..HEAD
Below command will show history of commits:
git log -3
git log -2
Below command will show difference between two commits:
git diff old_commit new_commit
git diff 5300b....4ea31a 754e8d....c33
git diff --name-status 5300b....4ea31a 754e8d....c33

MySQL Table Create Index Remove Index List Index | Primary Indexing | Unique Indexing | Field Indexing | FullText Indexing




/* Primary INDEXING */
ALTER TABLE `TABLE_NAME` ADD PRIMARY KEY (`ID`);

/* General INDEXING (1 or more field) */
ALTER TABLE `TABLE_NAME` ADD INDEX `INDEX_NAME` (`FIELD_1`, `FIELD_2`);

/* Unique INDEXING (1 or more field) */
ALTER TABLE `TABLE_NAME` ADD UNIQUE `INDEX_NAME` (`FIELD_1`, `FIELD_2`);

/* Fulltext INDEXING (1 or more field) */
ALTER TABLE `TABLE_NAME` ADD FULLTEXT `INDEX_NAME` (`FIELD_1`, `FIELD_2`);

/* Remove INDEXING */
DROP INDEX `INDEX_NAME` ON `TABLE_NAME`;

/* List INDEXING */
SHOW INDEX FROM `TABLE_NAME`;





Friday, December 1, 2017

MYSQL : SQL For Create Table Example




CREATE TABLE `table_name` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `int_field` BIGINT(20) NOT NULL DEFAULT '0',
  `string_field` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
  `long_text_field` LONGTEXT NULL COLLATE 'utf8_unicode_ci',
  `time_stamp_field` TIMESTAMP NULL DEFAULT NULL,
  `date_field` DATE NULL DEFAULT NULL,
  `date_time_field` DATETIME NULL DEFAULT NULL,
  `tinyint_field` TINYINT(1) NOT NULL DEFAULT '0',
  `double_field` DOUBLE(30,10) NULL DEFAULT '0.0000000000',
  `enum_field` ENUM('TRUE','FALSE') NULL DEFAULT 'TRUE' COLLATE 'utf8_unicode_ci',
  `set_field` SET('XA','XB','XC') NULL DEFAULT 'XA,XB' COLLATE 'utf8_unicode_ci',
  `uuid` VARCHAR(70) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
  PRIMARY KEY (`id`),
  UNIQUE INDEX `uuid` (`uuid`),
  INDEX `int_field_index` (`int_field`),
  INDEX `int_field_index_complex` (`int_field`, `string_field`)
) COLLATE='utf8_general_ci' ENGINE=InnoDB;


Thursday, November 30, 2017

MYSQL Backup Database Using Command Line | MYSQL Import / Restore Database Using Command Line

To take backup database, you need to execute following command:

mysqldump -u root -p password db_name > /tmp/sql_file.sql


And you can import/restore database using following command:

mysql -u root -p password db_name < /tmp/sql_file.sql



Simple try & catch TagLib | Tag Library for Grails GSP views

First you have to create a TagLib as below:









With following contents:


package com.pkm.taglib

class TryCatchTagLib {
    static namespace = "ui"

    def Try = { attrs, body ->
        try {
            out << body()
            request.exception = null
        }
        catch (Throwable e) {
            request.exception = e
        }
    }

    def Catch = { attrs, body ->
        if (request.exception) {
            out << body(exception: request.exception)
            request.exception = null
        }
    }
}


And use of try-catch as below:


<ui:try>
    SOME WORK I AM TRYING
</ui:try>
<ui:catch>
    GOT EXCEPTION=${exception}
</ui:catch>


Tuesday, November 21, 2017

Grails Groovy Sample DataSource Configuration For Database Connection

You need to edit DataSource.groovy file as below:


dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    dbCreate = "update"
    username = "root"
    password = ""
    logSql = false
    loggingSql = false
    properties {
        maxActive = 1000
        maxIdle = 100
        minIdle = 50
        initialSize = 1
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        numTestsPerEvictionRun = 3
        maxWait = 10000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = true
        validationQuery = "SELECT 1"
        minEvictableIdleTimeMillis = 1800000
        timeBetweenEvictionRunsMillis = 1800000
    }
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
    format_sql = false
    use_sql_comments = false
}

// environment specific settings
environments {
    development {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    test {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    production {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
        }
    }
}
log4j = {
    debug 'org.hibernate.SQL'
    trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}



Grails Groovy Use Groovy Source Class As Singleton Bean | Custom Bean Definition | Transactional Bean



This will act as a transnational bean

First put the below settings to 'Config.groovy'

grails.hibernate.cache.queries = true
grails.databinding.convertEmptyStringsToNull = true

Need to add/modify below contents to 'BuildConfig.groovy' to enable database connection using MYSQL:

grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve
    legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

        grailsPlugins()
        grailsHome()
        mavenLocal()
        grailsCentral()
        mavenCentral()
        // uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
        //mavenRepo "http://repository.codehaus.org"
        //mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
        mavenRepo "https://oauth.googlecode.com/svn/code/maven"
    }

    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
        compile "org.springframework:spring-orm:$springVersion"
        runtime 'mysql:mysql-connector-java:5.1.29'
        runtime 'org.springframework:spring-test:4.0.5.RELEASE'
        runtime "commons-httpclient:commons-httpclient:3.1"
        runtime "org.apache.httpcomponents:httpclient:4.3.3"
        runtime 'net.oauth.core:oauth-httpclient4:20090913'
    }

    plugins {
        build ":tomcat:7.0.55"
        runtime ":hibernate4:4.3.6.1"
        compile ":rendering:1.0.0"
        compile ":browser-detection:0.4.3"
        compile ':cache:1.1.8'
        compile ":mail:1.0.5"
        compile ":asset-pipeline:1.9.9"
        compile ':quartz:1.0.2'
    }
}

Below may be you database configuration (DataSource.groovy):

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    dbCreate = "update"
    username = "root"
    password = ""
    logSql = false
    loggingSql = false
    properties {
        maxActive = 1000
        maxIdle = 100
        minIdle = 50
        initialSize = 1
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        numTestsPerEvictionRun = 3
        maxWait = 10000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = true
        validationQuery = "SELECT 1"
        minEvictableIdleTimeMillis = 1800000
        timeBetweenEvictionRunsMillis = 1800000
    }
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
    format_sql = false
    use_sql_comments = false
}

// environment specific settings
environments {
    development {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    test {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    production {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
        }
    }
}
log4j = {
    debug 'org.hibernate.SQL'
    trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}

Now create a domain class like below:

package com.pritom

class Home {
    Long id
    String name
    String roll

    static constraints = {
        name blank: false
        roll blank: false, unique: true
    }
}

Below is the most important class which will be act as a singleton bean in our system:

package com.pritom

import org.springframework.transaction.annotation.Transactional
/**
 * Created by pritom on 21/11/2017.
 */
@Transactional(rollbackFor = [Exception, NoClassDefFoundError])
class MyBean {
    {
        println("BEAN-INITIALIZATION----------------$from------------------")
    }

    private String from = null

    void setFrom(String x) {
        this.from = x
    }

    void testPrint(String a) {
        println("Bean-class=${this.toString()}===${a}-----------$from")
        Thread.sleep(2000L)
        if (true) new Home(name: "Home-" + Home.count(), roll: String.valueOf(System.currentTimeMillis())).save()
        println("Home-count=${Home.count()}")
        if (true) throw new NoClassDefFoundError("Yeah!!!")
    }
}

We are not completed yet, need to initialize bean from resource.groovy as below:

beans = {
    myBean(MyBean) { bean ->
        bean.scope = 'singleton' // Set bean as singleton
        from = "Resource.groovy" // Set value to a field of class MyBean when initializing
    }
}

And finally test bean from some controller like below:

package com.pritom

class HomeController {
    def myBean

    def index() {
        try {
            myBean.testPrint("1")
            myBean.testPrint("2")
        }
        catch (Throwable ex) {
            println("Error=${ex.getMessage()}")
        }
        render ""
    }
}

And you can download source code from here

Monday, November 20, 2017

Query UI Tabs: Changing selected tab | Remembering Active Tab in JQuery UI Tabs | Select last tab by default on Page load, jQuery Ui Tabs | how to set a tab active in jQuery ui tab on page load | Set Jquery ui active tab on page load/reload

Query UI Tabs: Changing selected tab | Remembering Active Tab in JQuery UI Tabs | Select last tab by default on Page load, jQuery Ui Tabs | how to set a tab active in jQuery ui tab on page load | Set Jquery ui active tab on page load/reload

I'm using a basic implementation of Jquery UI Tabs that are working fine but I want to set (or reset) the active tab dynamically based on a user action.



<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Tab 1</a></li>
        <li><a href="#tabs-2">Tab 2</a></li>
        <li><a href="#tabs-3">Tab 3</a></li>
    </ul>
    <div id="tabs-1">
        First tab
    </div>
    <div id="tabs-2">
        Second tab
    </div>
    <div id="tabs-3">
        Third tab
    </div>
</div>
<div class='log'></div>



$(function ($) {
    $("#tabs").tabs({
        active: 1,
        create: function (event, ui) {
            var newIndex = ui.tab.parent().children().index(ui.tab);
            $(".log").prepend("<div>Created fired for child=" + newIndex + "</div>");
        },
        activate: function (event, ui) {
            //  Get future value
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
            $(".log").prepend("<div>Activate fired for child=" + newIndex + "</div>");
        },
        beforeActivate: function (event, ui) {
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
            $(".log").prepend("<div>Before activate fired for child=" + newIndex + "</div>");
        }
    });
});







You can manually active a tab using below code (2 is index of tab):
$("#tabs").tabs("option", "active", 2);