Category Archives: Uncategorized

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.

Source: [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 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.

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!

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

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 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:

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

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

 

InlineCallbacks

Twisted features a decorator named inlineCallbacks which allows you to work with deferreds without writing callback functions.

This is done by writing your code as generators, which yield deferreds instead of attaching callbacks.

Consider the following function written in the traditional deferred style:

import txredisapi as redis

from twisted.internet import defer
from twisted.internet import reactor

def main():
    rc = redis.Connection()
    print rc
    rc.addCallback(onSuccess)
    rc.addErrback(onFail)


def onSuccess(result):
    print "Success : "
    print result


def onFail(result):
    print "Fail : "
    print result


if __name__ == '__main__':
    main()
    reactor.run()

using inlineCallbacks, we can write this as:

from twisted.internet.defer import inlineCallbacks

import txredisapi as redis

from twisted.internet import defer
from twisted.internet import reactor


@defer.inlineCallbacks
def main():
    rc = yield redis.Connection()
    print rc

    yield rc.set("abc", "pqr")
    v = yield rc.get("abc")
    print "value : ", repr(v)

    yield rc.disconnect()


if __name__ == "__main__":
    main()
    reactor.run()

Instead of calling addCallback on the deferred returned by redis.Connection, we yield it. this causes Twisted to return the deferred‘s result to us.

Though the inlineCallbacks looks like synchronous code, which blocks while waiting for the request to finish, each yield statement allows other code to run while waiting for the deferred being yielded to fire.

inlineCallbacks become even more powerful when dealing with complex control flow and error handling.

WebRTC

WebRTC provides Real-Time Communications directly from better web browsers and devices without requiring plug-ins such as Adobe Flash nor Silverlight.

FreeSWITCH is a WebRTC gateway because it’s able to accept encrypted media from browsers, convert it, and exchange it with other communication networks  that use different codecs and encryptions, for example, PSTN, mobile carriers, legacy systems, and others. FreeSWITCH can be a gateway between your SIP network and applications and billions of browsers on desktops, tablets, and smartphones.

Configuration :

Look for the following in sofia profile and uncomment them:

    <!--uncomment for sip over websocket support-->
    <!--<param name="ws-binding"  value=":5066"/>-->

    <!--uncomment for sip over secure websocket support-->
    <!-- You need wss.pem in /usr/local/freeswitch/certs for wss -->
    <!--<param name="wss-binding" value=":7443"/>-->

Clients :

How it works :

By default, Sofia will listen on port 7443 for WSS clients. You may want to change this port if you need your clients to traverse very restrictive firewalls. Edit /usr/local/freeswitch/conf/sip-profiles/internal.xml and change the “wss-binding” value to 443. This number, 443, is the HTTPS (SSL) port, and is almost universally open in all firewalls.Remember that if you use port 443 for WSS, you cannot use that same port for HTTPS, so you will need to deploy your secure web server on another machine.

Example :

SIP signaling in JavaScript with SIP.js (WebRTC client)

Let’s carry out the most basic interaction with a web browser audio/video through WebRTC. We’ll start using SIP.js.

A web page will display a click-to-call button, and anyone can click. That call will be answered by our company’s PBX and routed to our employee extension (1000). Our employee will wait on a browser with the “answer” web page open, and will automatically be connected to the incoming call.

call.html :

<html>
<head>
<title>Call</title>
</head>
    <body>
        <button id="startCall">Start Call</button>
        <button id="endCall">End Call</button>
        <br/>
        <video id="remoteVideo"></video>
        <br/>
        <video id="localVideo" muted="muted" width="128px" height="96px"></video>

<script src="js/sip-0.7.0.min.js"></script>
<script src="call.js"></script>
</body>
</html>

call.js :

var session;

var endButton = document.getElementById('endCall')
endButton.addEventListener("click", function(){
    session.bye();
    alert("Call Ended");
}, false);

var startButton = document.getElementById('startCall');
startButton.addEventListener("click", function(){
    session = userAgent.invite('sip:1000@172.16.30.128', options);
    alert("Call Started")
}, false);

var userAgent = new SIP.UA({
    uri: 'sip:1000@172.16.30.128',
    wsServers: ['ws://172.16.30.128:5066'],
    authorizationUser: '1000',
    password: '1234'
});

var options = {
    media: {
        constraints: {
            audio: true,
            video: true
        },
        render: {
            remote: document.getElementById('remoteVideo'),
            local: document.getElementById('localVideo')
        }
    }    
};

answer.html :

<html>
<head>
    <title></title>
</head>
<body>
    <button id="endCall">End Call</button>
    <br/>
    <video id="remoteVideo"></video>
    <br/>
    <video id="localVideo" muted="muted" width="128px" height="96px"></video>

<script src="js/sip-0.7.0.min.js"></script>
<script src="answer.js"></script>
</body>
</html>

answer.js :

var session;
var endButton = document.getElementById('endCall');
    endButton.addEventListener("click", function () {
        session.bye();
        alert("Call Ended");
    }, false);

var userAgent = new SIP.UA({
        uri: 'sip:1000@172.16.30.128',
        wsServers: ['ws://172.16.30.128:5066'],
        authorizationUser: '1000',
        password: '1234'
    });

userAgent.on('invite', function (ciapalo) {
        session = ciapalo;
        session.accept({
            media: {
            constraints: {
            audio: true,
            video: true
            },
            render: {
                remote:
                document.getElementById('remoteVideo'),
                local:
                document.getElementById('localVideo')
            }
        }
    });
});

How it works :

Our employee (the callee, or the person who will answer the call) will sit tight with the answer.html web page open on their browser.

Our customer (the caller, or the person who initiates the communication) will visit the call.html webpage and then click on the Start Call button. This clicking will activate the JavaScript that creates the communication session using the invite method of the user agent, passing as an argument the SIP address of our employee.

use this to see if ws and wss work :

sofia status profile internal

How Implement Multiservice in Twisted.

Multiservice module is service collection provided by twisted, which is useful for creating a new service and combines with two or more existing services.

The major tools that manages Twisted application is a command line utility called twistd. twistd is a cross-platform, and is the recommended tool for running twisted applications.

The core component of the Twisted Application infrastructure is the

twisted.application.service.Application

object. which represents your application. Application acts as a container of any “Services” that your application provides. This will be done through Services.

Services manages application that can be started and stopped. In Application object can contain many services, or can even hierarchies of Services using “Multiservice” or your own custom IServiceCollection implementations.

Multiservice Implementaion:

To use multiserivce, which implements IService. For this, import internet and service module.

from twisted.application import internet, service

 

Example :

from twisted.application import internet,service
from serviceone import getServiceOne
from servicesecond import getServiceSecond
from twisted.web.server import Site

agentService = service.MultiService()
agentService.addService(getServiceOne())
agentService.addService(getServiceSecond())
application = service.Application("Receive Request")
agentService.setServiceParent(application)

To run, Save above code in a file as serviceexample.tac . Here, “tac ” file is regular python file. Twisted application infrastructure, protocol implementations live in a module, services, using those protocols are registered in a Twisted Application Configuration(TAC) file and the reactor and configuration are managed by an external utility.

Here, I use multiservice functionality from service. agentservice create object of multiservice. Then add services using add service method. In service, you can add web servers, FTP servers and SSH clients. After this, set application name and pass application to serviceparent method.

now, add service on port 8082 as :

from twisted.web.server import Site, NOT_DONE_YET
from twisted.web.resource import Resource
import logging
from twisted.application import internet

log = logging.getLogger("State Home")

class StateHome(Resource):
    isLeaf = True


    def reqComplete(self, req):
        req.write("Successfully Called.")
        req.finish()

    def render_GET(self, request):
        log.info("Run Render Get Method.")
        self.reqComplete(request)
        return NOT_DONE_YET

def getServiceOne():
    root = StateHome()
    factory = Site(root)
    return internet.TCPServer(8082, factory)

add another service same as above on port 8083 as:

from twisted.web.server import Site, NOT_DONE_YET
from twisted.web.resource import Resource
import logging
from twisted.application import internet

log = logging.getLogger("State Home")

class StateHome(Resource):
    isLeaf = True


    def reqComplete(self, req):
        req.write("Successfully Called second service.")
        req.finish()

    def render_GET(self, request):
        log.info("Run Render Get Method.")
        self.reqComplete(request)
        return NOT_DONE_YET

def getServiceSecond():
    root = StateHome()
    factory = Site(root)
    return internet.TCPServer(8083, factory)

To run serviceexample.tac file using twistd program, use command twistd -y serviceexample.tac -n. After this, open browser and enter url localhost:8082 and localhost:8083. You can see result on web page and both TCP servers are active.

Email template

Coding HTML for email can be tough. If you included video, flash, javascript or image chances it won’t show up you wanted it to.

You may have had some issues with your in email clients like Gmail or Apple Mail and Outlook.

Some comman problems are :-

  • Some email client not supported all CSS
  • Syntax improperly in tables or missing tags
  • Fonts are not displaying correctly

Troubleshoot your problem :-

If you’re having issues with columns, or rows not appearing in a table, add a border to the table to identify problems and better visualize the table structure.

If you’re seeing centered text when you prefer it left-aligned, make sure you’ve included properties like valign and align in <td> cells and <p> tags.

You may have some issues with your HTML emails looking great in email clients like Gmail or Apple Mail but rendering poorly in Outlook.

Outlook does not support many features :-

  • Animated GIF.
  • Background Images.
  • Padding for <div>, <p>, and <a> tags. Outlook ignores it. Use hspace or vspace attributes on images or tables to format your content.
  • Width for <div> and <p> tags. Outlook ignores it. Use hspace or vspace attributes on images or tables to format your content.

Email Client CSS Support:-

Open below link and check which CSS support in browser, desktop and mobile in various email client’s like outlook, yahoo, gmail.

https://templates.mailchimp.com/resources/email-client-css-support/