Monthly Archives: May 2019

Using WebSockets in Javascript

Using WebSockets in Javascript

WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Using websockets in javascriptSource: [WebSockets – A Conceptual Deep Dive](https://ably.com/topic/websockets)

Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

Following is the API which creates a new WebSocket object.

var Socket = new WebSocket(url, [protocal] );

Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.

A simple example

To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url:

var Socket = new WebSocket("ws://howto.lintel.in/");

There’s also encrypted wss:// protocol. It’s like HTTPS for websockets.

Always prefer wss://

The wss:// protocol not only encrypted, but also more reliable.

That’s because ws:// data is not encrypted, visible for any intermediary. Old proxy servers do not know about WebSocket, they may see “strange” headers and abort the connection.

On the other hand, wss:// is WebSocket over TLS, (same as HTTPS is HTTP over TLS), the transport security layer encrypts the data at sender and decrypts at the receiver, so it passes encrypted through proxies. They can’t see what’s inside and let it through.

WebSocket Attributes

Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above:-

Sr.No. Attribute & Description
1 Socket.readyState

The readonly attribute readyState represents the state of the connection. It can have the following values:-

  • A value of 0 indicates that the connection has not yet been established.
  • 1 value indicates that the connection is established and communication is possible.
  • 2 value indicates that the connection is going through the closing handshake.
  • 3 value indicates that the connection has been closed or could not be opened.

2 Socket.bufferedAmount

The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method.

WebSocket Events

Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above:-

Event Event Handler Description
open Socket.onopen This event occurs when socket connection is established.
message Socket.onmessage This event occurs when client receives data from server.
error Socket.onerror This event occurs when there is any error in communication.
close Socket.onclose This event occurs when connection is closed.

WebSocket Methods

These are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above:-

Sr.No. Method & Description
1 Socket.send()

The send(data) method transmits data using the connection.

2 Socket.close()

The close() method would be used to terminate any existing connection.

WebSocket Example

WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then “Upgrades” to a TCP socket after a HTTP handshake. After the handshake, either side can send data.

Client Side HTML & JavaScript Code

At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari.

<!DOCTYPE HTML>

<html>
   <head>
      
         function WebSocketTest() {
            
            if ("WebSocket" in window) {
               alert("WebSocket is supported by your Browser!");
               
               // Let us open a web socket
               var ws = new WebSocket("ws://localhost:1234/test");
				
               ws.onopen = function() {
                 
                  // Web Socket is connected, send data using send()
                  ws.send("Message to send");
                  alert("Message is sent...");
               };
				
               ws.onmessage = function (evt) { 
                  var received_msg = evt.data;
                  alert("Message is received...");
               };
				
               ws.onclose = function() { 
                  
                  // websocket is closed.
                  alert("Connection is closed..."); 
               };
            } 
            else {
              
               // The browser doesn't support WebSocket
               alert("WebSocket NOT supported by your Browser!");
            }
         }
      
   </head>
   
   <body>
      
       <a href="javascript:WebSocketTest()">Run WebSocket</a>
      
   </body>
</html>

How to update Route53 records after EC2 instance restart

Amazon Route 53 is a highly available and scalable cloud Domain Name System (DNS) web service. If you are not using Elastic IPs for your EC2 instances, chances are stopping and starting the server will result in different IPs after the instance comes back online. If you have A records pointing to those IPs in Route53 you will need a way to update them. After the script is executed, it will automatically gather the new Public IP and update the DNS record for it in Route53.

Edit 1:

As I am getting many comments on hosted zone parsing error… I wanted to add this

Before running script please check your host name is set to fully qualified domain name (FQDN) with this command
“`hostname -f“`

or

“`hostname -d“`

or

“`hostnamectl“`

If you don’t want to set host name system wide, feel free to modify the script manually

#!/bin/bash
# Author: Akhil Jalagam
# Description: update route53 after ec2 instance restart

HOSTNAME=$(hostname -f)
PUBLIC_IP=$(curl ident.me)
HOSTED_ZONE=$(hostname -d | awk -F"." '{print $(NF-2)".")
ZONE_ID=$(aws route53 --output json list-hosted-zones | jq --arg hosted_zone $HOSTED_ZONE. '.HostedZones[]  | select(.Name == $hosted_zone) | .Id' | awk -F"/" '{print $3}' | tr -d "\"")
RECORD_TYPE=$(aws route53 --output json list-resource-record-sets --hosted-zone-id $ZONE_ID --query "ResourceRecordSets[?Name == '$HOSTNAME.']" | jq ".[].Type" | tr -d "\"")
RECORD_SET="/tmp/updateroute53.json"

if [ -e "$RECORD_SET" ]
then
  rm -f $RECORD_SET
fi

echo "Updating resource record set"
echo "
{
    \"Comment\": \"Update record to reflect new public IP address\",
    \"Changes\": [
        {
            \"Action\": \"UPSERT\",
            \"ResourceRecordSet\": {
                \"Name\": \"$HOSTNAME.\",
                \"Type\": \"$RECORD_TYPE\",
                \"TTL\": 300,
                \"ResourceRecords\": [
                    {
                        \"Value\": \"$PUBLIC_IP\"
                    }
                ]
            }
        }
    ]
}" | tee -a /tmp/updateroute53.json

CHANGE_ID=$(aws route53 --output json change-resource-record-sets --hosted-zone-id $ZONE_ID --change-batch file:///$RECORD_SET | jq ".ChangeInfo.Id" | awk -F"/" '{print $3}' | tr -d "\"")
CHANGE_STATUS=$(aws route53 --output json get-change --id $CHANGE_ID | jq ".ChangeInfo.Status" | tr -d "\"")
declare -i COUNT=0

while [ "$CHANGE_STATUS" == "PENDING" ]
do
  COUNT=COUNT+1
  if [ "$COUNT" -ge 6 ]
  then
    echo "Update timed out, exiting..."
    exit 1
  fi
  sleep 10
  CHANGE_STATUS=$(aws route53 --output json get-change --id $CHANGE_ID | jq ".ChangeInfo.Status" | tr -d "\"")
done

echo "Record updated!"

*note: use “`set -ex“` option to debug the script

Setup Xamarin Environment on Mac & Visual Studio

Below I have explained how to setup Xamarin environment on mac operating system step by step.

1. Download Visual studio : 

      Download Visual Studio with below link

     https://visualstudio.microsoft.com/downloads/

      

At Microsoft website, you will have three options of  Visual Studio edition to choose from. Choose one according to your need. To download Visual Studio just click on download button and an installer .dmg file will be downloaded.

2. Install Visual Studio:

   Click on downloaded dmg file and below screen will be presented

    

Select from the different Platforms you need to develop apps for on Xamarin and press the Install button. Once Visual Studio installation is complete, we need to setup environment for both Android and Apple.

3. Setup Android SDK:

    To setup Android SDK open Visual Studio and go to :-

    Tools -> SDK Manager ->Android -> Locations

    

Set path for SDK ,NDK and JDK to your local machine locations. Once correct  path is given a green tick will appear on right.This completes our Android SDK   setup.

4. Apple Setup (for both iOS and Mac apps development):

You need latest Xcode to setup Apple environment. If you have Xcode preinstalled on your machine then it automatically configures and we don’t  have to do anything. If you are installing Xcode after installation of Visual  Studio then follow below steps to setup.

a. Download latest Xcode from apple store and Install it on your machine.

b. Go to Tool -> SDK Manager -> Apple

 

Give path to your Xcode.app . You will see green check mark once the correct path is given. This completes Apple environment setup.

That is all.  Now you can start your Android and iOS development on Xamarin. Happy Coding!

How to create Gridview using Recylerview Android

First let’s understand what Gridview and Recylerview are, in Android.

Gridview

A view that shows items in two-dimensional scrolling grid is known as Gridview. GridView layout in one of the most useful layouts in android to create a scrolling grid (rows & columns).

Recylerview

Recylerview is introduced in Android 5.0 Lollipop. The Recylerview widget is a more advanced and flexible version of Listview. It is a container used to display a large number of data sets that can be scrolled very efficiently by maintaining a limited number of views.

Now let’s start implementing Gridview

First, we need to add below dependency in build.gradle file at app level module.

dependencies {
      implementation 'com.android.support:recyclerview-v7:28.0.0'
}

After that, we need to add Recylerview widget in your main XML file.

<android.support.v7.widget.RecyclerView
         android:id="@+id/recyclerView"
         android:layout_width="match_parent"
         android:layout_height="wrap_content" />

Now we need to create item_logo.xml for Gridview row item.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/root"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:orientation="vertical">

    <ImageView
         android:id="@+id/ivLogo"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:scaleType="centerInside"
    />

</LinearLayout>

We need to create Adapter Object. An adapter in Android carries the data from a source (e.g. List<> ) and delivers it to a layout (.xml file).  The Adapter provides access to the data items.

public class LogoGridAdapter extends RecyclerView.Adapter<LogoGridAdapter.ViewHolder> {

    private List<Logo> logoList;
    private Context mContext;


    public LogoGridAdapter(Context mContext, List<Logo> logoList) {

        this.mContext = mContext;
        this.logoList = logoList;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_logo, null));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        Logo logo = getLogo(position);

        if(logo.getLogoUrl() != null) {
            ImageUtils.displayImage(logo.getLogoUrl(), holder.ivLogo, ContextCompat.getDrawable(mContext, R.drawable.image_placeholder));
        }

    }


    private Logo getLogo(int position) {
        return logoList.get(position);
    }

    public List<Logo> getLogoList() {
        return logoList;
    }

    @Override
    public int getItemCount() {
        return logoList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
       
        LinearLayout root;
        ImageView ivLogo;

        public ViewHolder(View itemView) {
            super(itemView);
            // get logo view 
            ivLogo = (ImageView)itemView.findViewById(R.id.ivLogo);
            root =  (LinearLayout)itemView.findViewById(R.id.root);
        }
    }
}

To display images we can use Glide dependency.

Glide.with(imageView.getContext()).load(imageUrl)
                .apply(new RequestOptions().placeholder(placeHolder).dontAnimate().diskCacheStrategy(DiskCacheStrategy.ALL))
                .into(imageView);

Now we need to set data into Adapter.

LogoGridAdapter mLogoGridAdapter = new LogoGridAdapter(this, logoList);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
recyclerView.setAdapter(mLogoGridAdapter);

GridLayoutManager is a Recylerview Layout Manager implementation to lay out items in a grid.

In the above code “3” is a number of columns in per row.

Output

 

 

 

 

 

 

 

 

 

 

That’s it, Happy Coding 🙂

Reference:-  https://developer.android.com/guide/topics/ui/layout/recyclerview

How to use rsync with ssh

Rsync is a fast and extraordinarily versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. It offers a large number of options that control every aspect of its behavior and permit very flexible specification of the set of files to be copied. It is famous for its delta-transfer algorithm, which reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination. Rsync is widely used for backups and mirroring and as an improved copy command for everyday use.

Rsync finds files that need to be transferred using a lqquick checkrq algorithm (by default) that looks for files that have changed in size or in last-modified time. Any changes in the other preserved attributes (as requested by options) are made on the destination file directly when the quick check indicates that the file’s data does not need to be updated.

While tar over ssh is ideal for making remote copies of parts of a filesystem, rsync is even better suited for keeping the filesystem in sync between two machines. Typically, tar is used for the initial copy, and rsync is used to pick up whatever has changed since the last copy. This is because tar tends to be faster than rsync when none of the destination files exist, but rsync is much faster than tar when there are only a few differences between the two filesystems.
To run an rsync over ssh, pass it the -e switch, like this:
[root@host]# rsync -ave ssh remote_server:/home/backups/ /home/user/server_backups/
Notice the trailing / on the file spec from the source side  On the source specification, a trailing / tells rsync to copy the contents of the directory, but not the directory itself. To include the directory as the top level of whatever is being copied, leave off the /:
[root@host]# rsync -ave ssh remote_server:/home/backups .
By default, rsync will only copy files and directories, but not remove them from the destination copy when they are removed from the source. To keep the copies exact, include the — delete flag:
[root@host]# rsync -ave ssh -- delete remote_server:~one/reports . 
If you run a command like this in cron, leave off the v switch. This will keep the output quiet (unless rsync has a problem running, in which case you’ll receive an email with the error output).
Using ssh as your transport for rsync traffic has the advantage of encrypting the data over the network and also takes advantage of any trust relationships you already have established using ssh client keys. For keeping large, complex directory structures in sync between two machines (especially when there are only a few differences between them), rsync is a very handy (and fast) tool to have at your disposal.
Dial USSD code in iOS?

How to Dial USSD code in iOS?

What is USSD?
USSD (Unstructured Supplementary Service Data) is a communications protocol used by GSM cellular telephones to communicate with the mobile network operator’s computers.

Generally, the USSD code is used by apps for start Call Forwarding, To get some system info, USSD based banking services, etc.

Previously, iOS didn’t allow to dial special chars like “*” and “#” programmatically from the iOS app, to prevent users from malicious redirecting phone calls or changing the behavior of a phone or account. So dialing codes programmatically was not possible till iOS 10.

With the launch of iOS 11 Apple enabled developers to programmatically dial USSD code from iOS app with some limitations.

 

How to dial USSD code:                                                       

Use below piece of Swift code to invoke dialing of USSD codes

let ussdCode = "tel://{your_USSD_number}"

        let app = UIApplication.shared

        if let encoded = ussdCode.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {

            let u = encoded//"tel://\(encoded)"

            if let url = URL(string:u) {

                if app.canOpenURL(url) {

                    app.open(url, options: [:], completionHandler: { (finished) in

                        if finished{

                            //Do your stuff

                        }

                    })
                }
            }
        }

When the above code gets executed, the app user will be shown a Dial prompt like below and will have to choose an action.

Note:  To dial USSD code with “#” you have to encode it like shown below else you will not get prompt for a number which contains “#”.

addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

 

If you are interested to know about the status of this call you have made to dial USSD, check below

How to Track Ongoing Call Status:

We can track Dialled call status like call dialling, running, completed using callKit framework. CallKit is a new framework that aims to improve the VoIP experience by allowing apps to integrate tightly with the native Phone UI. CallKit has many functionalities that work with VoIP calling but here we are using it only to track dialed call status.

Implement Callkit in swift to check call status as follows:

Import required Library

import CallKit

Use Protocol and Delegate method :-

class viewController: UIViewController, CXCallObserverDelegate{

func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {

        if call.hasEnded == true {

            print("CXCallState :Ended")

       }

        if call.isOutgoing == true && call.hasConnected == false {

            print("CXCallState :Dialing")

        }

        if call.isOutgoing == false && call.hasConnected == false && call.hasEnded == false {

            print("CXCallState :Incoming")

        }

        

        if call.hasConnected == true && call.hasEnded == false {

            print("CXCallState : Connected")

        }

    }

}

Thats it for now folks. Happy Coding!

Single/Multiple Country Picker Plugin With Flag

Country Picker With Flag jQuery plugin

About single/multiple country picker jQuery plugin :-

This single/multiple country picker jQuery plugin allows you to easily display a list of countries with flag in your Bootstrap form.

Dependencies :-

Usage :-

Create your <select> with the .country_selector class and add option of required countries.

Improtant Notes:
For multiple country picker add multiple attribute in <select> tag.

<select class="country_selector">
   <option value="">Select a country...</option>
   <option value="AF">Afghanistan</option>
   <option value="AX">Åland Islands</option>
   <option value="AL">Albania</option>
   <option value="DZ">Algeria</option>
   <option value="AS">American Samoa</option>
   <option value="AD">Andorra</option>
   <option value="AO">Angola</option>
   <option value="AI">Anguilla</option>
   <option value="AQ">Antarctica</option>
   <option value="AG">Antigua and Barbuda</option>
   <option value="AR">Argentina</option>
   <option value="AM">Armenia</option>
   <option value="AW">Aruba</option>
   <option value="AU">Australia</option>
   <option value="AT">Austria</option>
   <option value="AZ">Azerbaijan</option>
   <option value="BS">Bahamas</option>
   <option value="BH">Bahrain</option>
   <option value="BD">Bangladesh</option>
   <option value="BB">Barbados</option>
   <option value="BY">Belarus</option>
   <option value="BE">Belgium</option>
   <option value="BZ">Belize</option>
   <option value="BJ">Benin</option>
   <option value="BM">Bermuda</option>
   <option value="BT">Bhutan</option>
   <option value="BO">Bolivia, Plurinational State of</option>
   <option value="BA">Bosnia and Herzegovina</option>
   <option value="BW">Botswana</option>
   <option value="BV">Bouvet Island</option>
   <option value="BR">Brazil</option>
   <option value="IO">British Indian Ocean Territory</option>
   <option value="BN">Brunei Darussalam</option>
   <option value="BG">Bulgaria</option>
   <option value="BF">Burkina Faso</option>
   <option value="BI">Burundi</option>
   <option value="KH">Cambodia</option>
   <option value="CM">Cameroon</option>
   <option value="CA">Canada</option>
   <option value="CV">Cape Verde</option>
   <option value="KY">Cayman Islands</option>
   <option value="CF">Central African Republic</option>
   <option value="TD">Chad</option>
   <option value="CL">Chile</option>
   <option value="CN">China</option>
   <option value="CX">Christmas Island</option>
   <option value="CC">Cocos (Keeling) Islands</option>
   <option value="CO">Colombia</option>
   <option value="KM">Comoros</option>
   <option value="CG">Congo</option>
   <option value="CD">Congo, the Democratic Republic of the</option>
   <option value="CK">Cook Islands</option>
   <option value="CR">Costa Rica</option>
   <option value="CI">Côte d\'Ivoire</option>
   <option value="HR">Croatia</option>
   <option value="CU">Cuba</option>
   <option value="CY">Cyprus</option>
   <option value="CZ">Czech Republic</option>
   <option value="DK">Denmark</option>
   <option value="DJ">Djibouti</option>
   <option value="DM">Dominica</option>
   <option value="DO">Dominican Republic</option>
   <option value="EC">Ecuador</option>
   <option value="EG">Egypt</option>
   <option value="SV">El Salvador</option>
   <option value="GQ">Equatorial Guinea</option>
   <option value="ER">Eritrea</option>
   <option value="EE">Estonia</option>
   <option value="ET">Ethiopia</option>
   <option value="FK">Falkland Islands (Malvinas)</option>
   <option value="FO">Faroe Islands</option>
   <option value="FJ">Fiji</option>
   <option value="FI">Finland</option>
   <option value="FR">France</option>
   <option value="GF">French Guiana</option>
   <option value="PF">French Polynesia</option>
   <option value="TF">French Southern Territories</option>
   <option value="GA">Gabon</option>
   <option value="GM">Gambia</option>
   <option value="GE">Georgia</option>
   <option value="DE">Germany</option>
   <option value="GH">Ghana</option>
   <option value="GI">Gibraltar</option>
   <option value="GR">Greece</option>
   <option value="GL">Greenland</option>
   <option value="GD">Grenada</option>
   <option value="GP">Guadeloupe</option>
   <option value="GU">Guam</option>
   <option value="GT">Guatemala</option>
   <option value="GG">Guernsey</option>
   <option value="GN">Guinea</option>
   <option value="GW">Guinea-Bissau</option>
   <option value="GY">Guyana</option>
   <option value="HT">Haiti</option>
   <option value="HM">Heard Island and McDonald Islands</option>
   <option value="VA">Holy See (Vatican City State)</option>
   <option value="HN">Honduras</option>
   <option value="HK">Hong Kong</option>
   <option value="HU">Hungary</option>
   <option value="IS">Iceland</option>
   <option value="IN">India</option>
   <option value="ID">Indonesia</option>
   <option value="IR">Iran, Islamic Republic of</option>
   <option value="IQ">Iraq</option>
   <option value="IE">Ireland</option>
   <option value="IM">Isle of Man</option>
   <option value="IL">Israel</option>
   <option value="IT">Italy</option>
   <option value="JM">Jamaica</option>
   <option value="JP">Japan</option>
   <option value="JE">Jersey</option>
   <option value="JO">Jordan</option>
   <option value="KZ">Kazakhstan</option>
   <option value="KE">Kenya</option>
   <option value="KI">Kiribati</option>
   <option value="KP">Korea, Democratic People\'s Republic of</option>
   <option value="KR">Korea, Republic of</option>
   <option value="KW">Kuwait</option>
   <option value="KG">Kyrgyzstan</option>
   <option value="LA">Lao People\'s Democratic Republic</option>
   <option value="LV">Latvia</option>
   <option value="LB">Lebanon</option>
   <option value="LS">Lesotho</option>
   <option value="LR">Liberia</option>
   <option value="LY">Libyan Arab Jamahiriya</option>
   <option value="LI">Liechtenstein</option>
   <option value="LT">Lithuania</option>
   <option value="LU">Luxembourg</option>
   <option value="MO">Macao</option>
   <option value="MK">Macedonia, the former Yugoslav Republic of</option>
   <option value="MG">Madagascar</option>
   <option value="MW">Malawi</option>
   <option value="MY">Malaysia</option>
   <option value="MV">Maldives</option>
   <option value="ML">Mali</option>
   <option value="MT">Malta</option>
   <option value="MH">Marshall Islands</option>
   <option value="MQ">Martinique</option>
   <option value="MR">Mauritania</option>
   <option value="MU">Mauritius</option>
   <option value="YT">Mayotte</option>
   <option value="MX">Mexico</option>
   <option value="FM">Micronesia, Federated States of</option>
   <option value="MD">Moldova, Republic of</option>
   <option value="MC">Monaco</option>
   <option value="MN">Mongolia</option>
   <option value="ME">Montenegro</option>
   <option value="MS">Montserrat</option>
   <option value="MA">Morocco</option>
   <option value="MZ">Mozambique</option>
   <option value="MM">Myanmar</option>
   <option value="NA">Namibia</option>
   <option value="NR">Nauru</option>
   <option value="NP">Nepal</option>
   <option value="NL">Netherlands</option>
   <option value="AN">Netherlands Antilles</option>
   <option value="NC">New Caledonia</option>
   <option value="NZ">New Zealand</option>
   <option value="NI">Nicaragua</option>
   <option value="NE">Niger</option>
   <option value="NG">Nigeria</option>
   <option value="NU">Niue</option>
   <option value="NF">Norfolk Island</option>
   <option value="MP">Northern Mariana Islands</option>
   <option value="NO">Norway</option>
   <option value="OM">Oman</option>
   <option value="PK">Pakistan</option>
   <option value="PW">Palau</option>
   <option value="PS">Palestinian Territory, Occupied</option>
   <option value="PA">Panama</option>
   <option value="PG">Papua New Guinea</option>
   <option value="PY">Paraguay</option>
   <option value="PE">Peru</option>
   <option value="PH">Philippines</option>
   <option value="PN">Pitcairn</option>
   <option value="PL">Poland</option>
   <option value="PT">Portugal</option>
   <option value="PR">Puerto Rico</option>
   <option value="QA">Qatar</option>
   <option value="RE">Réunion</option>
   <option value="RO">Romania</option>
   <option value="RU">Russian Federation</option>
   <option value="RW">Rwanda</option>
   <option value="BL">Saint Barthélemy</option>
   <option value="SH">Saint Helena, Ascension and Tristan da Cunha</option>
   <option value="KN">Saint Kitts and Nevis</option>
   <option value="LC">Saint Lucia</option>
   <option value="MF">Saint Martin (French part)</option>
   <option value="PM">Saint Pierre and Miquelon</option>
   <option value="VC">Saint Vincent and the Grenadines</option>
   <option value="WS">Samoa</option>
   <option value="SM">San Marino</option>
   <option value="ST">Sao Tome and Principe</option>
   <option value="SA">Saudi Arabia</option>
   <option value="SN">Senegal</option>
   <option value="RS">Serbia</option>
   <option value="SC">Seychelles</option>
   <option value="SL">Sierra Leone</option>
   <option value="SG">Singapore</option>
   <option value="SK">Slovakia</option>
   <option value="SI">Slovenia</option>
   <option value="SB">Solomon Islands</option>
   <option value="SO">Somalia</option>
   <option value="ZA">South Africa</option>
   <option value="GS">South Georgia and the South Sandwich Islands</option>
   <option value="ES">Spain</option>
   <option value="LK">Sri Lanka</option>
   <option value="SD">Sudan</option>
   <option value="SR">Suriname</option>
   <option value="SJ">Svalbard and Jan Mayen</option>
   <option value="SZ">Swaziland</option>
   <option value="SE">Sweden</option>
   <option value="CH">Switzerland</option>
   <option value="SY">Syrian Arab Republic</option>
   <option value="TW">Taiwan, Province of China</option>
   <option value="TJ">Tajikistan</option>
   <option value="TZ">Tanzania, United Republic of</option>
   <option value="TH">Thailand</option>
   <option value="TL">Timor-Leste</option>
   <option value="TG">Togo</option>
   <option value="TK">Tokelau</option>
   <option value="TO">Tonga</option>
   <option value="TT">Trinidad and Tobago</option>
   <option value="TN">Tunisia</option>
   <option value="TR">Turkey</option>
   <option value="TM">Turkmenistan</option>
   <option value="TC">Turks and Caicos Islands</option>
   <option value="TV">Tuvalu</option>
   <option value="UG">Uganda</option>
   <option value="UA">Ukraine</option>
   <option value="AE">United Arab Emirates</option>
   <option value="GB">United Kingdom</option>
   <option value="US">United States</option>
   <option value="UM">United States Minor Outlying Islands</option>
   <option value="UY">Uruguay</option>
   <option value="UZ">Uzbekistan</option>
   <option value="VU">Vanuatu</option>
   <option value="VE">Venezuela, Bolivarian Republic of</option>
   <option value="VN">Viet Nam</option>
   <option value="VG">Virgin Islands, British</option>
   <option value="VI">Virgin Islands, U.S.</option>
   <option value="WF">Wallis and Futuna</option>
   <option value="EH">Western Sahara</option>
   <option value="YE">Yemen</option>
   <option value="ZM">Zambia</option>
   <option value="ZW">Zimbabwe</option>
</select>

Add CSS class under <head> tag.

.country_selector {
   cursor: text;
}
.country_selector {
   width: 400px;
   float: none;
   margin: auto;
   display: inline-block;
   text-align: left;
}

.country_selector.single .selectize-input:after {
   display: none !important;
}

.country_selector .selectize-input .item .flag-icon, .country_selector .selectize-dropdown .option .flag-icon{
   margin-right: 10px;
}

.country_selector.single .selectize-input, .country_selector.single .selectize-input input {
   cursor: text !important;
}

.country_selector .selectize-dropdown .option {
   cursor: pointer !important;
}

Add JS function under <script> tag in bottom or add in your JS file.

$('.country_selector').selectize({
    render: {
        option: function(data, escape) {
            return '<div class="option"><span class="flag-icon flag-icon-' + String(escape(data.value)).toLowerCase() + '"></span>' + escape(data.text) + '</div>';
        },
        item: function(data, escape) {
            return '<div class="item"><span class="flag-icon flag-icon-' + String(escape(data.value)).toLowerCase() + '"></span>' + escape(data.text) + '</div>';
        }
    },
});

Configuration :-

Refer to this documentation for more configuration.

How to Fix Freezing of Linux Kernel on Intel’s Bay Trail SoCs ( Celeron )

A patch fixes the frequent freezing at the Bay Trail has become known low-cost processors, the Celeron series on Linux. The SoCs are installed in cheap notebooks and other cheap hardware.

Bay Trail SoCs are known to be critical in Linux. This ranges from installation problems to crashes every minute. Intel knows the problem. It stands in an errata under the abbreviation VLP52 and is classified as No Fix , so Intel does not fix it .

Affected by the freeze, which usually occurs a few minutes after booting the system, are SoCs such as J1900, Celeron N2840, Celeron N2940, Atom Z3736F and Pentium N3540. The error that caused the crash was initially suspected in the GPU, but then localized in the power management of the chip and is described in a Bugzilla bug report. The problems only occur with many users if a graphical user interface is used.

The problem occurs when the system enters sleep mode C-State 6 (C6) after an interrupt service routine (ISR) is started but before it is terminated and the program continues at the interrupted location. A previously used workaround was to set the processor to C state 1 by passing the intel_idle.max_cstate = 1 parameter to the kernel . However, this leads to increased energy consumption and thus to shorter battery life.

The patch from Wolfgang M. Reimer disables only the C-States 6 and activates the C7-Core-States at the same time . This preserves the energy-saving options. The workaround introduced in mid-July was tested by many users and showed almost all the convincing results. However, some users also report that the problems with kernel 4.7 no longer occur even without the patch on their hardware.

patch (c6off+c7on.sh):

#!/bin/sh

#title:       c6off+c7on.sh
#description: Disables all C6 and enables all C7 core states for Baytrail CPUs
#author:      Wolfgang Reimer <linuxball (at) gmail.com>
#date:        2016014
#version:     1.0    
#usage:       sudo <path>/c6off+c7on.sh
#notes:       Intended as test script to verify whether erratum VLP52 (see
#             [1]) is the root cause for kernel bug 109051 (see [2]). In order
#             for this to work you must _NOT_ use boot parameter
#             intel_idle.max_cstate=<number>.
#
# [1] http://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/pentium-n3520-j2850-celeron-n2920-n2820-n2815-n2806-j1850-j1750-spec-update.pdf
# [2] https://bugzilla.kernel.org/show_bug.cgi?id=109051

# Disable ($1 == 1) or enable ($1 == 0) core state, if not yet done.
disable() {
	local action
	read disabled <disable
	test "$disabled" = $1 && return
	echo $1 >disable || return
	action=ENABLED; test "$1" = 0 || action=DISABLED
	printf "%-8s state %7s for %s.\n" $action "$name" $cpu  
}

# Iterate through each core state and for Baytrail (BYT) disable all C6
# and enable all C7 states.
cd /sys/devices/system/cpu
for cpu in cpu[0-9]*; do
	for dir in $cpu/cpuidle/state*; do
		cd "$dir"
		read name <name
		case $name in
			C6*-BYT) disable 1;;
			C7*-BYT) disable 0;;
		esac
		cd ../../..
	done
done

 

References:

https://www.golem.de/news/intel-einfrieren-bei-intels-bay-trail-socs-durch-patch-abgefedert-1609-123546.html

5 Ways to Speed Up SSH Connections in Linux

SSH is the most popular and secure method for managing Linux servers remotely. One of the challenges with remote server management is connection speeds, especially when it comes to session creation between the remote and local machines.

There are several bottlenecks to this process, one scenario is when you are connecting to a remote server for the first time; it normally takes a few seconds to establish a session. However, when you try to start multiple connections in succession, this causes an overhead (combination of excess or indirect computation time, memory, bandwidth, or other related resources to carry out the operation).

In this article, we will share four useful tips on how to speed up remote SSH connections in Linux.

1.Use Compression option in SSH

From the ssh man page (type man ssh to see the whole thing):

 -C      Requests compression of all data (including stdin, stdout,
         stderr, and data for forwarded X11 and TCP connections).  The
         compression algorithm is the same used by gzip(1), and the
         “level” can be controlled by the CompressionLevel option for pro-
         tocol version 1.  Compression is desirable on modem lines and
         other slow connections, but will only slow down things on fast
         networks.  The default value can be set on a host-by-host basis
         in the configuration files; see the Compression option.

 

ssh -C username@example.com

2.Force SSH Connection Over IPV4

OpenSSH supports both IPv4/IP6, but at times IPv6 connections tend to be slower. So you can consider forcing ssh connections over IPv4 only, using the syntax below:

# ssh -4 username@example.com

Alternatively, use the AddressFamily (specifies the address family to use when connecting) directive in your ssh configuration file  (global configuration) or ~/.ssh/config (user specific file).

The accepted values are “any”, “inet” for IPv4 only, or “inet6”.

AddressFamily inet

3. Reuse SSH Connection

An ssh client program is used to establish connections to an sshd daemon accepting remote connections. You can reuse an already-established connection when creating a new ssh session and this can significantly speed up subsequent sessions.

You can enable this in your ~/.ssh/config file.

ControlMaster auto
ControlPath /home/akhil/.ssh/sockets/ssh_mux_%x_%p_%r
ControlPersist yes

openssh doesn’t support %x(ip address in control paths),  use my repo instead

https://github.com/akhilin/openssh-portable.git

or use %h to use hostname instead of ip address

using ip address is recommended so that even if you connect using different hostnames it uses same socket ( very useful when using ansible , pdsh )

4. Use Specific SSH Authentication Method

Another way of speeding up ssh connections is to use a given authentication method for all ssh connections, and here we recommend configuring ssh passwordless login using ssh keygen in 5 easy steps.

Once that is done, use the PreferredAuthentications directive, within ssh_config files (global or user specific) above. This directive defines the order in which the client should try authentication methods (you can specify a command separated list to use more than one method).

PreferredAuthentications=publickey

If you prefer password authentication which is deemed unsecure, use this.

ssh -o "PreferredAuthentications=password" username@example.com

5.Disable DNS Lookup On Remote Machine

By default, sshd daemon looks up the remote host name, and also checks that the resolved host name for the remote IP address maps back to the very same IP address. This can result into delays in connection establishment or session creation.

The UseDNS directive controls the above functionality; to disable it, search and uncomment it in the /etc/ssh/sshd_config file. If it’s not set, add it with the value no.

UseDNS=no

Threads usage in C programming

Threads usage in C programming

If you want to write tables from two – five at the same time and using pencils and papers we need at least four writing hands ( four people), four pencils and four papers one for each to write a table. This method is called parallelism. In this method, we obtain the result in a short time. If one person does the same task it takes four times longer. (To understand threads)

In computer C programming, this process is called threads. By using these we get efficiency in programs to solve complex issues. In the Linux environment, POSIX threads have appeared. These are called pthreads and having a library named pthread.

Types of threads:

These are generally two types.

1. Joinable threads
2. Detachable threads

Joinable threads need to join them, whereas Detachable threads run their self. In every program main function, itself is the main thread.

To create pthread in C program we using phtread_create() function. In this function, it takes four arguments.

1. thread id
2. attribute
3. function to call
4. only argument to calling function

Example 1:

Here is an example C program to demonstrate joinable.

To compile below program
gcc thread.c -o thread -lpthread

To execute the program
./thread

/* thread.c */

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void* second_thread(void* arg)
{
    int i;

    printf("second_table\n");
    for (i = 1; i <= 10; i++) {
        printf("2 X %d = %d\n", i, i*2);
        sleep(1);
    }
    pthread_exit(NULL);
}

void* third_thread(void* arg)
{
    int i;

    printf("\t\t\tthird_table\n");
    for (i = 1; i <= 10; i++) {
        printf("\t\t\t3 X %d = %d\n", i, i*3);
        sleep(1);
    }

    pthread_exit(NULL);
}

void* fourth_thread(void* arg)
{
    int i;

    printf("\t\t\t\t\t\tfourth_table\n");
    for (i = 1; i <= 10; i++) {
        printf("\t\t\t\t\t\t4 X %d = %d\n", i, i*4);
        sleep(1);
    }

    pthread_exit(NULL);
}

void* fifth_thread(void* arg)
{
    int i;

    printf("\t\t\t\t\t\t\t\t\tfifth_table\n");
    for (i = 1; i <= 10; i++) {
        printf("\t\t\t\t\t\t\t\t\t5 X %d = %d\n", i, i*5);
        sleep(1);
    }

    pthread_exit(NULL);
}

int main()
{
    pthread_t tid[4];

    printf("It is a pthread demo program!\n");
    pthread_create(&tid[0], NULL, second_thread, NULL);
    pthread_create(&tid[1], NULL, third_thread, NULL);
    pthread_create(&tid[2], NULL, fourth_thread, NULL);
    pthread_create(&tid[3], NULL, fifth_thread, NULL);

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    pthread_join(tid[2], NULL);
    pthread_join(tid[3], NULL);
    printf("Finished threds execution!\n");
    return 0;

}

The result is almost like this:

result of thread.c

result of thread.c For more information on the pthread_create function refer the below link

https://linux.die.net/man/3/pthread_create

Example 2:

Here is another program to demonstrate the detachable type.

To compile below program
gcc thread_detach.c -o thread_detach -lpthread

To execute the program
./thread_detach

/* thread_detach.c */

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void* second_thread(void* arg)
{
    int i;

    printf("second_table\n");
    for (i = 1; i <= 10; i++) {
        printf("2 X %d = %d\n", i, i*2);
        sleep(1);
    }
    pthread_exit(NULL);
}

void* third_thread(void* arg)
{
    int i;

    printf("\t\t\tthird_table\n");
    for (i = 1; i <= 10; i++) {
        printf("\t\t\t3 X %d = %d\n", i, i*3);
        sleep(1);
    }

    pthread_exit(NULL);
}

void* fourth_thread(void* arg)
{
    int i;

    printf("\t\t\t\t\t\tfourth_table\n");
    for (i = 1; i <= 10; i++) {
        printf("\t\t\t\t\t\t4 X %d = %d\n", i, i*4);
        sleep(1);
    }

    pthread_exit(NULL);
}

void* fifth_thread(void* arg)
{
    int i;

    printf("\t\t\t\t\t\t\t\t\tfifth_table\n");
    for (i = 1; i <= 10; i++) {
        printf("\t\t\t\t\t\t\t\t\t5 X %d = %d\n", i, i*5);
        sleep(1);
    }

    pthread_exit(NULL);
}

int main()
{
    pthread_t tid[4];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    printf("It is a pthread detachble demo program!\n");

    pthread_create(&tid[0], &attr, second_thread, NULL);
    pthread_create(&tid[1], &attr, third_thread, NULL);
    pthread_create(&tid[2], &attr, fourth_thread, NULL);
    pthread_create(&tid[3], &attr, fifth_thread, NULL);

    sleep(10);
    printf("Finished threds execution!\n");
    return 0;

}

The result is almost like this:

thread_detach.c

For more information on the pthread_detach function refer the below link:

https://linux.die.net/man/3/pthread_detach