Force reload css


In a Developer's life the most irritating and the time wasting moment is when you change your css file but your browser caches the page or DNS and just keep hard reloading the page. And i am no exception for this so finally end up with a simple bookmarklet for my self to forcefully reload the cached,

How to use ?

you just need to Drag and Drop Force Reload CSS Bookmarklet on your browser's bookmark toolbar and that's it.

HTML Table to Excel.xls using Javascript


Showing data on the web in tabular is very common and most of the time user wants to save data.
The majority of user who plays with data are the user of Microsoft Excel so it's nice have a Download as .xls button on the page.

We can achieve this in many ways for example we can use some server side language to convert the database tables in excel format and so on.

But  today we are going to do this via JavaScript.

Before i explain you further let me show you the code first.

Dummy HTML:
<div id="tableWrap">
   <table>
      <tbody>
         <tr>
            <th>Full Name</th>
            <th>Profile</th>
            <th>expertise</th>
         </tr>
         <tr>
            <td>Aamir Khan</td>
            <td>Full Stack Developer</td>
            <td>Web & Security</td>
         </tr>
         <tr>
            <td>Nitish Kumar</td>
            <td>Marketing Manager</td>
            <td>SEO</td>
         </tr>
         <tr>


            <td>Sandeep Kumar</td>
            <td>Web Developer</td>
            <td>HTML, CSS & Jquery</td>
         </tr>
      </tbody>
   </table>
</div>



Javascript Code:

let toXls = function(){
 location.href='data:application/vnd.ms-excel,' + encodeURIComponent( document.getElementById("tableWrap").innerHTML);
    return false;

};

The Above JS code is tricking the browser by using the data:application/vnd.ms-excel to open the file with Microsoft Excel.

and BOOM we are done .

Here is the complete Example
<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>HTML Table to Excel.xls - Demo - chap09.blogspot.in </title>
   <style>
    html{
      background-color:#fff;
      color:#333;
      font:0.75em/1.5 sans-serif;
      padding:1em;
    }
    /* Tables */
    table{
      border-collapse: collapse;
      margin-bottom:1em;
      width:100%;
    }
    th{
      background-color:#27ae60;
      color:#fff;
      font-weight:900;
    }
    th,
    td{
      border:1px solid #ccc;
      padding:0.5em;
    }
    tr{
    background: #F6F6F6;
    }
    tr:nth-of-type(odd){
    background: #e9e9e9;
    }
    button{
      background: #147246;
      background-image: url("xls.png");
      background-repeat: no-repeat;
      background-size: 30%;
      border-radius: 5px;
      border: 0 none;
      color: #fff;
      cursor: pointer;
      padding: 15px 50px;
    }
   </style>
</head>
<body>
   <div id="tableWrap">
      <table>
         <tbody>
            <tr>
               <th>Full Name</th>
               <th>Profile</th>
               <th>expertise</th>
            </tr>
            <tr>
               <td>Aamir Khan</td>
               <td>Full Stack Developer</td>
               <td>Web &amp; Security</td>
            </tr>
            <tr>
               <td>Nitish Kumar</td>
               <td>Marketing Manager</td>
               <td>SEO</td>
            </tr>
            <tr>
               <td>Sandeep Kumar</td>
               <td>Web Developer</td>
               <td>HTML, CSS &amp; Jquery</td>
            </tr>
         </tbody>
      </table>
   </div>
   <p></p>
   <button id="DownloadXls">Download</button>
   <script>
      document.getElementById('DownloadXls').onclick = function(){
             location.href='data:application/vnd.ms-excel,' + encodeURIComponent( document.getElementById("tableWrap").innerHTML);
         return false;
      
      };
      
   </script>
</body>
</html>



Proof of Concept

Stand alone ajax library


All Most all the time in my web developement i require to make ajax requests but unfortunaly the war of browsers and the existense of the IE make me think of to use a library such as jQuery. But why? why on earth i will add bunch of unnecceray code to my page just to make simple ajax request? so finally as being a lazy programmer i end up with this code.
var ajax = {};
ajax.x = function () {
    if (typeof XMLHttpRequest !== 'undefined') {
        return new XMLHttpRequest();
    }
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"
    ];

    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
    return xhr;
};

ajax.send = function (url, callback, method, data, async) {
    if (async === undefined) {
        async = true;
    }
    var x = ajax.x();
    x.open(method, url, async);
    x.onreadystatechange = function () {
        if (x.readyState == 4) {
            callback(x.responseText)
        }
    };
    if (method == 'POST') {
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.send(data)
};

ajax.get = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};

ajax.post = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url, callback, 'POST', query.join('&'), async)
};


//Example: ajax.get('/get.php', {foo: 'bar'}, function() {});
//Example: ajax.post('/post.php', {foo: 'bar'}, function() {});

How do I add read more link in Whatsapp message ?


I received a message from a friend about my profile picture on whatsapp which has only two lines and a 'read more' link just after two lines and when i look behind that message there was  just lots of space..

that appears that adding too much space can do the trick..
i tested and its working...
i will add this post with sample text and data as soon as i get some time ...



How to convert CMYK to RGB and RGB to CMYK in Java

RGB (Red Green Blue) are the colors i guess we all know most of the web developers works with rgb and hex colors.

CMYK (Cyan, Magenta, Yellow, Black) CMYK are the colors used in printing.

Most of the Graphic softwares such as Photoshop, gimp etc are actually able to work with both models.

The point of this post is simply tell you the process of transforming RGB to CMYK or reverse.

Let's start with RGB to CMYK.

RGB to CMYK conversion formula

The R,G,B values are divided by 255 to change the range from 0..255 to 0..1

R1 = R/255
G1 = G/255
B1 = B/255

The black key (K) color is calculated from the red (R1,G1,B1)
K = 1-max(R1, G1, B1)

The cyan color (C) is calculated from the red (R1) and black (K) colors:
C = (1-R1-K) / (1-K)

The magenta color (M) is calculated from the green (G1) and black (K) colors:
M = (1-G1-K) / (1-K)

The yellow color (Y) is calculated from the blue (B1) and black (K) colors:
Y = (1-B1-K) / (1-K)

lets implement this into code
public CMYK toCMYK() {

     double c, m, y, k;
     double r = 2, g = 25, b = 255;
     double r1 =  r / 255, g1 = g / 255, b1 = b / 255;
     
     k = 1 - max(r1, g1, b1);
     c = (1 - r1 - k) / (1 - k);
     m = (1 - g1 - k) / (1 - k);
     y = (1 - b1 - k) / (1 - k);
     return new CMYK(c, m, y, k);

}


so now lets look into CMYK to RGB

CMYK to RGB conversion formula

The R,G,B values are given in the range of 0 - 255.

The red (R) color is calculated from the cyan (C) and black (K)
colors:
R = 255 × (1-C) × (1-K)

The green color (G) is calculated from the magenta (M) and black
(K) colors:
G = 255 × (1-M) × (1-K)

The blue color (B) is calculated from the yellow (Y) and black
(K) colors:
B = 255 × (1-Y) × (1-K)

And here is the code.

public RGB toRGB() {

      double r = 255 * (1 - c) * (1 - k);
      double g = 255 * (1 - m) * (1 - k);
      double b = 255 * (1 - y) * (1 - k);

      return new RGB(r, g, b);
}


All right, so now hopefully we understand the conversion, let's see everything in action

Full code

package chap09;

/**
 *
 * @author Aamir khan @hacktw
 * @version 1.2
 *
 */
public class RGBtoCMYK {

    public static void main(String argu[]) {
        new RGBtoCMYK().run();
    }//main end

    private void run() {
        RGB rgb = new RGB(255, 0, 255);
        CMYK cmyk = new CMYK(0, 1, 0, 0);

        System.out.println(rgb.toCMYK());
        System.out.println(cmyk.toRGB());
    }

    class CMYK {

        double c, m, y, k;

        public CMYK(double c, double m, double y, double k) {
            if (c > 1 || m > 1 || y > 1 || k > 1) {
                System.err.print("make sure CMYK values are in range 0-1");
                System.exit(0);
            }

            this.c = c;
            this.m = m;
            this.y = y;
            this.k = k;
        }

        public RGB toRGB() {

            /**
             * <b>CMYK to RGB conversion formula</b>
             *
             * <p>
             * The R,G,B values are given in the range of 0..255.
             *
             * The red (R) color is calculated from the cyan (C) and black (K)
             * colors:
             *
             * R = 255 × (1-C) × (1-K)
             *
             * The green color (G) is calculated from the magenta (M) and black
             * (K) colors:
             *
             * G = 255 × (1-M) × (1-K)
             *
             * The blue color (B) is calculated from the yellow (Y) and black
             * (K) colors:
             *
             * B = 255 × (1-Y) × (1-K)
             * </p>
             *
             */
            double r = 255 * (1 - c) * (1 - k);
            double g = 255 * (1 - m) * (1 - k);
            double b = 255 * (1 - y) * (1 - k);

            return new RGB(r, g, b);
        }

        @Override
        public String toString() {
            //Format the Output
            java.text.DecimalFormat p = new java.text.DecimalFormat("#.###");
            return "Cyan " + p.format(c)
                    + "nMagenta " + p.format(m)
                    + "nYellow " + p.format(y)
                    + "nBlack " + p.format(k);
        }

    }

    class RGB {

        double r, g, b;

        public RGB(double r, double g, double b) {
            if (r > 255 || g > 255 || b > 255) {
                System.err.print("make sure RGB values are in range 0-255");
                System.exit(0);
            }
            this.r = r;
            this.g = g;
            this.b = b;
        }

        /** <b>RGB to CMYK conversion formula</b>
        *
        * <p>
        * The R,G,B values are divided by 255 to change the range from 0..255 to 0..1:
        *
        * R1 = R/255
        *
        * G1 = G/255
        *
        * B1 = B/255
        *
        * The black key (K) color is calculated from the red (R1,G1,B1)
        *
        * K = 1-max(R1, G1, B1)
        *
        * The cyan color (C) is calculated from the red (R1) and black (K) colors:
        *
        * C = (1-R1-K) / (1-K)
        *
        * The magenta color (M) is calculated from the green (G1) and black (K) colors:
        *
        * M = (1-G1-K) / (1-K)
        *
        * The yellow color (Y) is calculated from the blue (B1) and black (K) colors:
        *
        * Y = (1-B1-K) / (1-K)
        * </p>
        **/
        public CMYK toCMYK() {

            double c, m, y, k;

            double r1 = r / 255, g1 = g / 255, b1 = b / 255;

            /*the black key Color (k) is Calculated from r1,g1,b1
                so k = 1- max(r1,g1,b1)
             */
            k = 1 - max(r1, g1, b1);
            //The Cyan
            c = (1 - r1 - k) / (1 - k);
            //The Magento
            m = (1 - g1 - k) / (1 - k);
            //The Yellow
            y = (1 - b1 - k) / (1 - k);

            return new CMYK(c, m, y, k);

        }

        public double max(double a, double b, double c) {

            double max = a;
            if (b > max) {
                max = b;
            }
            if (c > max) {
                max = c;
            }
            return max;

        }//max end

        @Override
        public String toString() {
            return String.format("rgb(%1.0f, %1.0f, %1.0f)", r, g, b);
        }

    }

}


output:
Cyan 0
Magenta 1
Yellow 0
Black 0
rgb(255, 0, 255)

How to use Java to Print Numbers in Hindi

An internationalized program can display information differently throughout the world.

For example, the program will display different messages in India , China, and New York. If the localization process has been fine-tuned,

in Java A Locale object is an identifier for a particular combination of language and region.When creating a Locale object, you usually specify a language code and a country code. A third parameter, the variant, is optional.


So, if you got my point than this is Simple to Print Different messages in Different Languages in java.

An Example Will be Enough to take you Down there...


import java.text.NumberFormat;
import java.util.Locale;

/**
 *
 * @author Aamir Khan
 */
public class Hindi_123 {

    public static void main(String[] args) {
        //set the Locale to Hindi,India
        Locale myloc = new Locale("hi", "in");
        //pass the instace to NumberFormat to Handle the Rest
        NumberFormat nf = NumberFormat.getInstance(myloc);
        for (int i = 0; i <= 100; i++) {

            //print the Numbers
            System.out.println(nf.format(i));
        }

    }

}

How to join a list with prefix in python

Sometimes you may need to turn your list into a string and the most pythonic way of doing is by using join.
But when it comes to adding a prefix with the list its does not work properly lets give a try.

>>> animals = ['Cat', 'Dog', 'Elephant']
>>> "The".join(animals)
    'CatTheDogTheElephant'


What that's not prefix at all but that can be fixed by adding just "\n" with prefix.
Lets try.

>>> print("\nThe ".join(animals))
Cat
The Dog
The Elephant

Ok, that seems to work but if we look at the output we are missing the prefix with first output.
so how to fix that?

Well a simple way is to map all the input with prefix and convert that into string.
Lets Try.

>>> print("\n".join(map(lambda x: "The " + x, animals)))
The Cat
The Dog
The Elephant


and perfect it works.

some people prefer to use list comprehension over map and filter, so we can

>>> print("\n".join(["The " + x for x in animals]))
The Cat
The Dog
The Elephant


Note : you will have to convert list into string if the list is having data other then string

For Example:
>>> print("\n".join(map(lambda x: "prefix" + str(x), some_list)))

IMEI Validation app in JavaFX

IMEI (International Mobile Station Equipment Identity) is a unique number to identify GSM, UMTS, LTE and iDEN mobile phones.

The IMEI is basically used to identify a device. It is usually found printed inside the battery or you can dial *#06# to see your device IMEI.

The Digits are calculated with an algorithm called "Luhn algorithm" also known as "mod 10"  created by scientist Hans Peter Luhn.

It is also used to validate a variety of identification numbers, such as credit card numbers, National Provider Identifier numbers in the US etc. Which means you can use the same app to validate variety of things those using "mod 10" .

How it works ?

  1. Take the digit from the rightmost and double the value of every other digit.
  2. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the product (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9) or in simple wordsif the result in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
  3. Take the sum of all the digits.
  4. if the sum is divided by 10 then its valid else its not.

so enough theory lets jump into coding.
below is the code implemented with mod 10.




package chap09;

/**
 *
 * @author Aamir khan
 */
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.layout.VBox;
import java.util.stream.IntStream;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.application.Application;
import javafx.scene.control.TextField;

/**
 *
 *
 * @author Aamir khan
 */
public class IMEIValidaotrApp extends Application {

    //components
    IMEIField field;
    Label status;
    VBox root;
    Button checkBtn;

    //this is a bad idea use a separate css file indeed
    private final String INVALID_LABEL_CSS = "-fx-text-fill:white; "
            + "-fx-background-color: #E26868;"
            + "-fx-padding:5px;"
            + "-fx-border-width:1; -fx-border-color:#B63E5A;"
            + "-fx-font-size: 9pt;";

    private final String VALID_LABEL_CSS = "-fx-text-fill:white; "
            + "-fx-background-color: #20A286;"
            + "-fx-padding:5px;"
            + "-fx-border-width:1; -fx-border-color:#19B99A;"
            + "-fx-font-size: 9pt;";

    private final String CHECK_BUTTON_CSS = "-fx-background-color:#c3c4c4,"
            + "linear-gradient(#d6d6d6 50%, white 100%),"
            + "radial-gradient(center 50% -40%, radius 200%, #e6e6e6 45%, rgba(230,230,230,0) 50%);"
            + "-fx-background-radius: 30; -fx-background-insets: 0,1,1;"
            + "-fx-text-fill: black;"
            + "-fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 3, 0.0 , 0 , 1 );";

    @Override
    public void init() {

        field = new IMEIField();
        field.setText("490154203237518");//for the Demo

        status = new Label();

        checkBtn = new Button("Check");
        checkBtn.setDefaultButton(true);
        //disable the button if the length is less than 15
        checkBtn.disableProperty().bind(field.textProperty().length().lessThan(15));
        checkBtn.setStyle(CHECK_BUTTON_CSS);
    }

    @Override
    public void start(Stage window) throws Exception {

        root = new VBox(status, field, checkBtn);
        root.setAlignment(Pos.CENTER);
        root.setSpacing(5.0);
        root.setStyle("-fx-padding: 10; -fx-font-size: 18;");

        window.setScene(new Scene(root, 300, 200));
        window.setTitle("IMEI Checker");
        window.setResizable(false);
        window.show();

        checkBtn.setOnAction(e -> validateIMEI());

    }

    /**
     * implementation of
     * <a href = "https://en.wikipedia.org/wiki/Luhn_algorithm Luhn algorithm">Luhn
     * algorithm</a>
     * is also known as “Modulus 10” algorithm.<br>
     * It is a simple checksum formula used to validate a variety of
     * identification numbers,<br>
     * such as credit card numbers, IMEI numbers, National Provider Identifier
     * numbers in US and Canadian Social Insurance Numbers.<br>
     * It was created by IBM scientist Hans Peter Luhn.<br>
     * Verification is done by validating check digit.<br><br>
     *
     * <p>
     * simply Double the value of every second digit from the right end (first
     * right will be check digit number). Add the individual digits comprising
     * both the products from step (1) and unaffected digits in the original
     * number. If the total modulo 10 is equal to 0, then the number is valid,
     * else it is not valid. an example of IMEI no. 490154203237518</p>
     */
    private void validateIMEI() {

        final int[] numbers = field.getText().chars().map(this::ConvertASCIIToNumer).toArray();
        boolean isValid = IntStream.range(0, numbers.length)
                .map(i -> (((i % 2) ^ (numbers.length % 2)) == 0)
                        ? ((2 * numbers[i]) / 10 + (2 * numbers[i]) % 10)
                        : numbers[i])
                .sum() % 10 == 0;

        if (isValid) {
            status.setStyle(VALID_LABEL_CSS);
            status.setText("VALID");
        } else {
            status.setText("INVALID");
            status.setStyle(INVALID_LABEL_CSS);
        }
    }

    /**
     * Returns the numeric value of the ASCII
     */
    private int ConvertASCIIToNumer(int value) {
        return Character.digit(value, 10);
    }

    /**
     * a specific class for Holding
     * <a href =
     * "https://en.wikipedia.org/wiki/International_Mobile_Station_Equipment_Identity">
     * IMEI Numbers
     * </a>
     */
    class IMEIField extends TextField {

        private final int LIMIT = 15;//A Valid IMEI Number has 15 digits

        @Override
        public void replaceText(int start, int end, String text) {
            if (validate(text)) {
                super.replaceText(start, end, text);
                onLengthListener();
            }
        }

        @Override
        public void replaceSelection(String text) {
            if (validate(text)) {
                super.replaceSelection(text);
                onLengthListener();
            }
        }

        private void onLengthListener() {
            //Stop if user type more than LIMIT
            textProperty().
                    addListener((observable, oldValue, newValue) -> {
                        if (newValue.length() > LIMIT) {
                            setText(oldValue);
                        }
                    });

        }

        /**
         * Validate input against the {@link String} and make sure input is
         * Number only
         *
         * @return true if the value is a Numeric Value <b>0-9</b>
         */
        private boolean validate(String text) {

            //furtuhre check can be done for "Empty input" or for "White Space"
            //return (" ".equals(text) || "".equals(text) ||text.matches("[0-9]"));
            return ("".equals(text) || text.matches("[0-9]"));
        }

    }

    //Mr. Main
    public static void main(String[] args) {
        launch(args);//Entry point for the FX Thread

    }

}

Lambda, Stream, Method Reference, and Multithreading All in one simple program

This code sums up Lambda, Stream, Method Reference and Multithreading all in one.


import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.IntPredicate;

/**
 *
 * @author Aamir khan
 */
public class Count {

    private String userinpt = "";
    private final List<runnable> tasks;

    public static void main(String[] args) {
        Count c = new Count();
        c.takeInput();
        c.start();
    }

    /**
    * init the list of tasks
    **/
    Count() {
    //Lambda in action
        tasks = Arrays.asList(
                () -> countVowels(),
                () -> countCons(),
                () -> countDigits(),
                () -> countWhiteSpace()
        );

    }

    /**
     * take user input used by
     * {@link #count(java.util.function.IntPredicate)};
     *
     */
    private void takeInput() {

        System.out.println("Enter your Text");
        userinpt = new Scanner(System.in).useDelimiter("\\z").next();

    }

    /***
    * submit the task to Thread pool and execute them.
    */
    private void start() {
    //Multithreading in action
        ExecutorService thread = Executors.newFixedThreadPool(tasks.size());
        tasks.forEach(thread::submit);
        thread.shutdown();
    }

    private void countVowels() {
    //Method Reference in action
        long numberOfVowels = count(this::isVowel);
        print("Total number of Vowels: " + numberOfVowels);

    }

    private void countWhiteSpace() {
        long numberOfWhiteSpaces = count(Character::isWhitespace);
        print("Total number of Spaces: " + numberOfWhiteSpaces);
    }

    private void countDigits() {
        long numberOfDigits = count(Character::isDigit);
        print("Total number of Digits: " + numberOfDigits);

    }

    private void countCons() {
        long numberOfCons = count(e -> Character.isLetter(e) && !isVowel(e));
        print("Total number of Consonants: " + numberOfCons);

    }

    /**
    * filter with given Predicate and count the filtered result
    **/
    private long count(IntPredicate filter) {
        // Stream in action    
        return userinpt.toLowerCase().chars().filter(filter).count();
    }
    
    
    
    //util methods
    public boolean isVowel(int codePoint) {
        //checking for lower case because the input will only be in lower case
        return (codePoint == 'a')
                || (codePoint == 'e')
                || (codePoint == 'i')
                || (codePoint == 'o')
                || (codePoint == 'u');

    }

    public void print(String s) {
        System.out.println(s);
    }
}

A simple string xoring program in Python

In cryptography, the simple XOR cipher is a type of additive cipher.
As the XOR operation is common in programming languages. It's pretty simple to implement it and it's also less expensive on computers.

The cipher is sometimes used for hiding information or used in cases where no particular security is required.

But, before we dive into code keep in mind that this cypher can easily be crack using a frequency analysis . But wait !, this is easy because most of the time they use the same key for xoring and if we simply generates random keys its actually pretty hard than to crack it.

So, below is the implementation of xoring in python 3.


#!/usr/bin/env python3

from os import urandom as keygen


def xor_str(data, key):
    return "".join(chr(ord(a) ^ b) for a, b in zip(data, key))


def run():
    # Note: string in Python 2.x is a bytestring
    msg = input("Enter your message: ")
    key = keygen(len(msg))

    xored = xor_str(msg, key)
    # this is how you can decrypt the data
    un_xored = xor_str(xored, key)

    # Verify that data
    if un_xored == msg:
        print("success")
        print("Encrypted:")
        print(xored)
    else:
        print("Error")


if __name__ == "__main__":
    run()