Tuesday, December 31, 2019

What is Virtual Environment Wrapper



virtualenvwrapper is a set of extensions to Ian Bicking’s virtualenv tool. The extensions include wrappers for creating and deleting virtual environments and otherwise managing your development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies.

Below are the features

Organizes all of your virtual environments in one place.
Wrappers for managing your virtual environments (create, delete, copy).
Use a single command to switch between environments.
Tab completion for commands that take a virtual environment as argument.
User-configurable hooks for all operations (see Per-User Customization).
Plugin system for creating more sharable extensions (see Extending Virtualenvwrapper).

pip install virtualenvwrapper


$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1
Installing
setuptools..........................................
....................................................
....................................................
...............................done.
virtualenvwrapper.user_scripts Creating /Users/dhellmann/Envs/env1/bin/predeactivate
virtualenvwrapper.user_scripts Creating /Users/dhellmann/Envs/env1/bin/postdeactivate
virtualenvwrapper.user_scripts Creating /Users/dhellmann/Envs/env1/bin/preactivate
virtualenvwrapper.user_scripts Creating /Users/dhellmann/Envs/env1/bin/postactivate  New python executable in env1/bin/python
(env1)$ ls $WORKON_HOME
env1 hook.log

Now we can add softwares into this virtual environment

(env1)$ pip install django
Downloading/unpacking django
  Downloading Django-1.1.1.tar.gz (5.6Mb): 5.6Mb downloaded
  Running setup.py egg_info for package django
Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.6/django-admin.py from 644 to 755
    changing mode of /Users/dhellmann/Envs/env1/bin/django-admin.py to 755
Successfully installed django



References:
https://virtualenvwrapper.readthedocs.io/en/latest/

What is a typical format for Changelog file


What is a typical format for Changelog file

What is a change log:
A changelog is a file which contains a curated, chronologically ordered list of notable changes for each version of a project.

Why keep a changelog?
To make it easier for users and contributors to see precisely what notable changes have been made between each release (or version) of the project.

Who needs a changelog?
People do. Whether consumers or developers, the end users of software are human beings who care about what's in the software. When the software changes, people want to know why and how.

# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Example is below.

## [Unreleased]

## [1.0.0] - 2017-06-20
### Added
- New visual identity by [@tylerfortune8](https://github.com/tylerfortune8).
- Version navigation.
- Links to latest released version in previous versions.
- "Why keep a changelog?" section.

### Changed
- Start using "changelog" over "change log" since it's the common usage.
- Start versioning based on the current English version at 0.3.0 to help
translation authors keep things up-to-date.

### Removed
- Section about "changelog" vs "CHANGELOG".



References:
https://keepachangelog.com/en/1.0.0/

DNS - What are various records

DNS - What are various records

Stored in authoritative DNS servers are the DNS records, these records provide information about a domain including its associated IP address for each domain. It is mandatory for all domains to have a few necessary DNS records to be able to access a website using a domain name.

Below are few common types of records

1. A record

A (Address) Record An A record points a domain name to an IP address. For example, when you type www.google.com in a web browser, it will translate to 172.217.12.46 . This record links your website’s domain name to an IP address that points to where the website’s files live.

2. CNAME record
A CNAME record forwards one domain name to another domain name. This record does not contain an IP address. Utilize this type of record only when there are no other records on that domain name. Otherwise, conflict is introduced by any other records interfering. An example, a CNAME can just go from www.google.com to google.com and not to any additional domain name such as gmail.com.

3. MX Record (Mail Exchanger)

This type of record routes all email messages to a specified mail server on behalf of a recipient’s domain to a designated mail host. The MX records use a priority number when there is more than one MX record entered for any single domain name that is using more than one mail server. The priority number specifies the order of access to the listed mail servers. Counterintuitively, the lower number is the higher priority. For example, the priority number of 10 set within the MX record will receive the email messages first. The MX record with the priority number of 20 will be a backup if the MX record with the priority of 10 is unavailable.

4. TXT record
Utilized for information and verification purposes the TXT record discloses information to other services about your domain such as what services the domain is using. Sender Policy Framework (SPF) records are added as TXT records to help identify if email messages are coming from a trusted source.

5. NS (Name Server) Record

Name servers are servers usually owned by a web hosting company, such as Liquid Web, that are used to manage domain names associated with their web hosting customers. The NS records are created to identify the name servers for each domain name in a given DNS zone.

6. SOA (Start of Authority) Record




References :

DNS - Zone and Zone files

DNS - Zone and Zone files

A DNS zone is an administrative space within the Domain Name System (DNS). A DNS zone forms one part of the DNS namespace delegated to administrators or specific entities. Each zone contains the resource records for all of its domain names.

A DNS zone file is a text file stored on a DNS server that contains all the DNS records for every domain within that zone. It is mandatory for the zone file to have the TTL (Time to Live) listed before any other information. The TTL specifies how long a DNS record is in the DNS server’s cache memory. The zone file can only list one DNS record per line and will have the Start of Authority (SOA) record listed first. The SOA record contains essential domain name information including the primary authoritative name server for the DNS Zone.

A sample

references
https://www.liquidweb.com/kb/understanding-the-dns-process/

What Are Authoritative & Recursive name servers

What Are Authoritative & Recursive name servers

An authoritative name server is a DNS server that stores DNS records (A, CNAME, MX, TXT, etc.) for domain names. These servers will only respond to DNS queries for locally stored DNS zone files.  For example, if a DNS server in my network has a stored A record for example.com, then that DNS server is the authoritative server for the example.com domain name.

Recursive Nameserver

A recursive name server is a DNS server that receives DNS queries for informational purposes. These types of DNS servers do not store DNS records. When a DNS query is received, it will search in its cache memory for the host address tied to the IP address from the DNS query. If the recursive name server has the information, then it will return a response to query sender. If it does not have the record, then the DNS query will be sent to other recursive name servers until it reaches an authoritative DNS server that can supply the IP address.


References:
https://www.liquidweb.com/kb/understanding-the-dns-process/

DNS Lookup process - things involved

DNS Lookup process - things involved

Step 1: Requesting Website Information

First, you visit a website by typing a domain name into a web browser.  Your computer will start resolving the hostname, such as www.liquidweb.com. Your computer will look for the IP address associated with the domain name in its local DNS cache, which stores DNS information that your computer has recently saved.  If it is present locally, then the website will be displayed. If your computer does not have the data stored, then it will perform a DNS query to retrieve the correct information.

Step 2: Contact the Recursive DNS Servers
If the information is not in your computer’s local DNS cache, then it will query the recursive DNS servers from your (ISP) Internet service provider. Recursive DNS servers have their local DNS cache, much like your computer. Given that many of the ISP’s customers are using the same recursive DNS servers, there is a chance that common domain names already in its cache. If the domain is cached, the DNS query will end here and the website displayed to the user.

Step 3: Query the Authoritative DNS Servers

If a recursive DNS server or servers do not have the information stored in its cache memory, the DNS query continues to the authoritative DNS server that has the data for a specific domain. These authoritative name servers are responsible for storing DNS records for their respective domain names.

Step 4: Access the DNS Record
For our example, to find out the IP address for www.liquidweb.com, we will query the authoritative name server for the address record (A record). The Recursive DNS server accesses the A record for www.liquidweb.com from the authoritative name servers and stores the record in its local DNS cache. If other DNS queries request the A record for www.liquidweb.com, the recursive server will have the answer and will not have to repeat the DNS lookup process. All DNS records have a time-to-live value, which shows when a DNS record will expire. After some time has passed, the recursive DNS server will ask for an updated copy of the DNS record.


Step 5: Final DNS Step
The Recursive DNS server has the information and returns the A record to your computer. Your computer will store the DNS record in its local DNS cache, will read the IP address from the DNS record, and pass this information to your browser. The web browser will connect to the web server associated with the A records IP and display the website.

The entire DNS lookup process, from start to finish, takes only milliseconds to complete. For a more profound understanding let’s break down the previously mentioned DNS components that are relevant to the DNS lookup process.


References:
https://www.liquidweb.com/kb/understanding-the-dns-process/

WebRTC Do we need to have a Media server ?

WebRTC Do we need to have a Media server ?

Chrome 65 includes an upper limit to that which is used for garbage collection purposes. Chrome is not going to allow more than 500 concurrent peer connections to exist.

Assume we want to broadcast a video at a low VGA resolution. We checked and decided that 500kbps of bitrate offers good results for our needs.

Broadcasting our stream to 10 people requires bitrate of 5mbps uplink.

f we’re on an ADSL connection, then we can find ourselves with 1-3mbps uplink only, so we won’t be able to broadcast the stream to our 10 viewers.

For the most part, we don’t control where our broadcasters are going to be. Over ADSL? WiFi? 3G network with poor connectivity? The moment we start dealing with broadcast we will need to make such assumptions.

When we use WebRTC for a broadcast type of a service, a lot of decisions end up taking place in the media server. If a viewer has a bad network, this will result with packet loss being reported to the media server. What should the media server do in such a case?

While there’s no simple answer to this question, the alternatives here include:

Asking the broadcaster to send a new I-frame, which will affect all viewers and increase bandwidth use for the near future (you don’t want to do it too much as a media server)
Asking the broadcaster to reduce bitrate and media quality to accommodate for the packet losses, affecting all viewers and not only the one on the bad network
Ignoring the issue of packet loss, sacrificing the user for the “greater good” of the other viewers
Using Simulcast or SVC, and move the viewer to a lower “layer” with lower media quality, without affecting other users

The alternative is to use a Media server



References
https://bloggeek.me/media-server-for-webrtc-broadcast/

WebRTC Media Servers and Open Source Options

WebRTC Media Servers and Open Source Options

Mesh Architecture : multiple participants using peer to peer communication it stops being practical as the number of participants increase, since it is required that a peer sends his/her video/audio stream to every participant, while receiving a video/audio stream per participant. In practice, even under optimal network conditions, a mesh video call doesn’t work well beyond five participants.


SFU: Single Forwarding Unit : meaning its main purpose is to forward media streams between clients.

MCU:  is used to address a media server that not only forwards, but can operate on the media streams that go through it (e.g. mixing all video or audio streams into a single one)

Video recording is possible if the video goes through media servers

Another advantage of using a media server is communicating with systems beyond  what web technologies allow, such as the PSTN via SIP trunking or streaming through RTMP to services that support it, like Facebook Live and YouTube Live Streaming.

Below are the Open source media servers available .

Jitsi

Jitsi is not only a WebRTC media server, but has a whole platform built around it. The Jitsi family of products include Jitsi Videobridge (Media Relay, SFU), Jitsi Meet (Conference web client), Jicofo (Jitsi Conference Focus), Jigasi (Jitsi Gateway to SIP) and Jitsi SIP Phone. The most appealing feature of the Jitsi platform is that it includes everything for a communication platform to be up and running in a matter of a few hours.  It also implements its own signaling using Jingle (XMPP) and a fully featured web interface. Sadly, however, one of the biggest pain points is implementing media recording, as there’s no solid, easy to use solution.


Kurento Media Server

This is one of the most versatile solutions out there. It not only is a media server, but is a toolkit to build one. The main advantage of Kurento is its versatility by introducing the concept of a Media Workflow, that allows to define, in code, how and where the media flows. This allows a WebRTC developer to compose and integrate very interesting features such as computer vision (e.g. recognize QR codes, face detection), real-time media modification and interop with RTP (VoIP) services. Kurento can also be configured to function as SFU or MCU, or both, in a single instance.

Janus WebRTC Gateway
While its description doesn’t mention “media server” anywhere, Janus can be setup as an SFU pretty easily. One of its most notable features is its plugin architecture, that allows to augment the service’s core capabilities.

mediasoup
A relatively new and interesting media server, what makes it different from the rest is that it’s designed to be a library (for Node) allowing it to be integrated in bigger applications.


References:
https://webrtc.ventures/2017/11/a-guide-to-webrtc-media-servers-open-source-options/

What are three major Python GUI Frameworks?

What are three major Python GUI Frameworks?

PyQt

PyQt implements the popular Qt library, and so if you are familiar with Qt development in another language, perhaps from developing native applications for KDE or another Qt-using desktop environment, you may already be familiar with Qt. This opens up the possibility of developing applications in Python which have a familiar look and feel across many platforms, while taking advantage of the tools and knowledge of the large Qt community.

Tkinter

If there were a single package which might be called the "standard" GUI toolkit for Python, it would be Tkinter. Tkinter is a wrapper around Tcl/Tk, a popular graphical interface and language pairing first popularized in the early 90s. The advantage of choosing Tkinter is the vast number of resources, including books and code samples, as well as a large community of users who may be able to help you out if you have questions. Simple examples are easy to get started with and fairly human-readable.

WxPython

WxPython brings the wxWidgets cross-platform GUI library from its native C++ to Python. WxPython is a slightly more modern approach to, which looks a little more native than Tkinter across different operating systems as it does not attempt to create its own set of widgets (although these can be themed to look much like native components). It's fairly easy to get started with as well, and has a growing developer community. You may need to bundle wxPython with your applications, as it is not automatically installed with Python.





References:
https://opensource.com/resources/python/gui-frameworks

Docker installing on Mac machine

Docker installing on Mac machine

To download Docker Desktop, go to Docker Hub and sign in with your Docker ID

Had to do a signup with docker and get an account, which then gave link to download the docker from

https://hub.docker.com/?overlay=onboarding

Now installed the Docker for Mac from this link below

https://docs.docker.com/docker-for-mac/

$ docker run hello-world

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
ca4f61b1923c: Pull complete
Digest: sha256:ca0eeb6fb05351dfc8759c20733c91def84cb8007aa89a5bf606bc8b315b9fc7
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.
...

It ran the docker successfully with the above.

Great, similarly we can start ngnix server also like below

docker run --detach --publish=80:80 --name=webserver nginx

References:
https://docs.docker.com/docker-for-mac/install/

What is Docker

What is Docker

Docker is said to be industry leader container runtime. Docker Engine powers millions of applications worldwide, providing a standardized packaging format for diverse applications.

Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. By doing so, thanks to the container, the developer can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code.

For developers, it means that they can focus on writing code without worrying about the system that it will ultimately be running on. It also allows them to get a head start by using one of thousands of programs already designed to run in a Docker container as a part of their application. For operations staff, Docker gives flexibility and potentially reduces the number of systems needed because of its small footprint and lower overhead.

Docker Engine is the industry’s de facto container runtime that runs on various Linux (CentOS, Debian, Fedora, Oracle Linux, RHEL, SUSE, and Ubuntu) and Windows Server operating systems. Docker creates simple tooling and a universal packaging approach that bundles up all application dependencies inside a container which is then run on Docker Engine. Docker Engine enables containerized applications to run anywhere consistently on any infrastructure, solving “dependency hell” for developers and operations teams, and eliminating the “it works on my laptop!” problem.

Below are few key features of Docker

1. Powered by containered

Built on the leading open source container runtime, a graduated project of the Cloud Native Computing Foundation (CNCF). Containerd implements Kubernetes Container Runtime Interface (CRI) and is widely adopted across public clouds and enterprises.

2. FIPS 140-2 Encryption

The only container runtime that has been validated by NIST for its encryption, forming a secure and compliant foundation for deploying containerized applications. Part of a “secure by design” engineering philosophy

3. Enforce Signed Images
Validate the provenance of containers by enforcing proper digital signing of images before being deployed. Prevents a user from using a container image from an unknown source or building a container image from a base layer from an unknown source.

4. Integrated BuildKit

BuildKit is an open source tool that takes the instructions from a Dockerfile and ‘builds” a Docker image. This process can take a long time so BuildKit provides several architectural enhancements that makes it much faster, more precise and portable.

5. Docker CLI

The most popular way to interface with Docker containers is the Docker CLI - a simple, yet powerful client that greatly simplifies how you manage container instances through a clear set of commands.

6. Certified Plugins

Integrate Docker Engine with your preferred networking, storage, and logging tools through validated and certified plugins. The plugin architecture extends capabilities of Docker Engine to 3rd party provided tools.



References:
https://www.docker.com/products/container-runtime#/download

Python - Image Processing with SciPy – scipy.ndimage

Python - Image Processing with SciPy – scipy.ndimage

scipy.ndimage is a submodule of SciPy which is mostly used for performing an image related operation
ndimage means the "n" dimensional image.
SciPy Image Processing provides Geometrics transformation (rotate, crop, flip), image filtering (sharp and de nosing), display image, image segmentation, classification and features extraction.
MISC Package in SciPy contains prebuilt images which can be used to perform image manipulation task

This code actually brought up a window and showed the Panda image.

from scipy import misc
from matplotlib import pyplot as plt
import numpy as np
#get face image of panda from misc package
panda = misc.face()
#plot or show image of face
plt.imshow( panda )
plt.show()

References:
https://www.guru99.com/scipy-tutorial.html

SciPy special function packages

SciPy special function packages

scipy.special package contains numerous functions of mathematical physics.
SciPy special function includes Cubic Root, Exponential, Log sum Exponential, Lambert, Permutation and Combinations, Gamma, Bessel, hypergeometric, Kelvin, beta, parabolic cylinder, Relative Error Exponential, etc..


References:
https://www.guru99.com/scipy-tutorial.html


SciPy Linear Algebra

Linear Algebra of SciPy is an implementation of BLAS and ATLAS LAPACK libraries.
Performance of Linear Algebra is very fast compared to BLAS and LAPACK.
Linear algebra routine accepts two-dimensional array object and output is also a two-dimensional array.

This is how the linear algebra calculation is done.

from scipy import linalg
import numpy as np
# define square matrix
two_d_array = np.array([ [4,5], [3,2] ])
#pass value to function inv()
linalg.inv( two_d_array )

References:
https://www.guru99.com/scipy-tutorial.html

Python SciPy Basic program

Python SciPy Basic program 

SciPy is an Open Source Python-based library, which is used in mathematics, scientific computing, Engineering, and technical computing.

To install SciPy, below was the instruction

sudo port install py35-scipy py35-numpy

(PyLearning) mymachine-M-91RJ:PyLearning mymachine$ Python3 -m pip install --user numpy scipy
Collecting numpy
  Downloading https://files.pythonhosted.org/packages/ea/f4/acaa005b20777fc56a1dc0cae228ab2cb5a7f09a7e7fcb6d4619ce24a1b7/numpy-1.17.3-cp37-cp37m-macosx_10_9_x86_64.whl (15.1MB)
    100% |████████████████████████████████| 15.1MB 2.1MB/s
Collecting scipy
  Downloading https://files.pythonhosted.org/packages/d5/06/1a696649f4b2e706c509cb9333fdc6331fbe71251cede945f9e1fa13ea34/scipy-1.3.1-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (27.7MB)
    100% |████████████████████████████████| 27.7MB 1.1MB/s
Installing collected packages: numpy, scipy
  The scripts f2py, f2py3 and f2py3.7 are installed in '/Users/mymachine/Library/Python/3.7/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

It was giving this error. As a result, executing the below steps was able to resolve this error and

#run these using python3 instead of python.
#to install scipy and numpy for python3, follow the below steps
#pip3 install numpy
#pip3 install scipy

import numpy as np
from scipy import io as sio
array = np.ones((4, 4))
sio.savemat('example.mat', {'ar': array})
data = sio.loadmat('example.mat', struct_as_record=True)
print(data['ar'])


References:
https://www.guru99.com/scipy-tutorial.html

Android OK HTTP Certificate Pinning Helper



The easiest way to pin a host is turn on pinning with a broken configuration and read the expected configuration when the connection fails. Be sure to do this on a trusted network, and without man-in-the-middle tools like Charles or Fiddler.
For example, to pin https://publicobject.com, start with a broken configuration:

String hostname = "publicobject.com";
     CertificatePinner certificatePinner = new CertificatePinner.Builder()
         .add(hostname, "sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=")
         .build();
     OkHttpClient client = new OkHttpClient();
     client.setCertificatePinner(certificatePinner);

     Request request = new Request.Builder()
         .url("https://" + hostname)
         .build();
     client.newCall(request).execute();


As expected, this fails with a certificate pinning exception:
 

 javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
   Peer certificate chain:
     sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=: CN=publicobject.com, OU=PositiveSSL
     sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=: CN=COMODO RSA Domain Validation Secure Server CA
     sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=: CN=COMODO RSA Certification Authority
     sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=: CN=AddTrust External CA Root
   Pinned certificates for publicobject.com:
     sha1/AAAAAAAAAAAAAAAAAAAAAAAAAAA=
   at com.squareup.okhttp.CertificatePinner.check(CertificatePinner.java)
   at com.squareup.okhttp.Connection.upgradeToTls(Connection.java)
   at com.squareup.okhttp.Connection.connect(Connection.java)
   at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java)



Follow up by pasting the public key hashes from the exception into the certificate pinner's configuration:
 

     CertificatePinner certificatePinner = new CertificatePinner.Builder()
       .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
       .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
       .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
       .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
       .build();

Pinning is per-hostname and/or per-wildcard pattern. To pin both publicobject.com and www.publicobject.com, you must configure both hostnames.

Warning: Certificate Pinning is Dangerous!
Pinning certificates limits your server team's abilities to update their TLS certificates. By pinning certificates, you take on additional operational complexity and limit your ability to migrate between certificate authorities. Do not use certificate pinning without the blessing of your server's TLS administrator!


References:
https://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/CertificatePinner.html 

Pip how to install

Pip how to install

pip is already installed if you are using Python 2 >=2.7.9 or Python 3 >=3.4 downloaded from python.org or if you are working in a Virtual Environment created by virtualenv or pyvenv. Just make sure to upgrade pip.

To install pip, securely download get-pip.py. 1:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then run the following:

python get-pip.py

The second command I had to run in sudo mode. But, it was successful to install

References:
https://pip.pypa.io/en/stable/installing/

Installing PyQt


Python : What is PyQt

PyQt is a python binding of the open-source widget-toolkit Qt, which also functions as a cross-platform application development framework. Qt is a popular C++ framework for writing GUI applications for all major desktop, mobile, and embedded platforms (supports Linux, Windows, MacOS, Android, iOS, Raspberry Pi, and more).

PyQt is developed and maintained by Riverbank Computing, a company based in England, whereas Qt is developed by a Finnish firm called The Qt Company.

Features:
PyQt consists of more than six hundred classes covering a range of features such as

Graphical User Interfaces
SQL Databases
Web toolkits
XML processing
Networking


PyQt Versions
PyQt is available in two editions, PyQt4 and PyQt5. PyQt4 provides glue code for binding 4.x and 5.x versions of the Qt framework while PyQt5 provides a binding for only the 5.x versions. As a result, PyQt5 is not backward compatible with the deprecated modules of the older version.

Riverbank Computing also provides PyQt3D—the python bindings for the Qt3D framework. Qt3D is an application framework used to create real-time simulation systems with 2D/3D rendering.



Using Wheel files
Building and Installing from Source

Installing using Wheels

Wheels are the new standard Python packaging and distribution format. Simply speaking, a wheel is a ZIP archive with a special name and .whl file extension. Wheels can be installed using pip (Python's package manager), which is included by default in the recent versions of Python.

pip install PyQt5

Trying to install the PyQtT5, it gave below error
ERROR: Could not find a version that satisfies the requirement PyQt5 (from versions: none)
ERROR: No matching distribution found for PyQt5

OK, instead of this, running the below installed Qt5

pip3 install PyQt5

This installed PyQt5 but when trying to run the app, it still says could not be found

Below is the code for demonstrating Qt capabilities

import sys
print(sys)
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(300,300)
    w.setWindowTitle('Cisco')
    w.show()
    sys.exit(app.exec_())


References:
https://www.guru99.com/pyqt-tutorial.html#1

Python : Http request

Python : Http request

import urllib.request

#pretty easy to read the http response code and to read the response data.

webrequest = urllib.request.urlopen('https://www.google.com')
print ("result code "+str(webrequest.getcode()))

data = webrequest.read();
print(data)


References:
https://www.guru99.com/accessing-internet-data-with-python.html

Python : List examp

le

#List and its methods are pretty straight forward
#Python lists can be homogeneous, meaning that they can contain the same type of objects; or heterogeneous, including different types of objects.

list =  [1, 2, 3, 8, 33]
print(list)
list = ['dog', 'cat', 'goat']
print(list)
list = ['John', 'Travis', 'Sheila']
print(list)
list = [2.2, 4.5, 9.8, 10.4]
print(list)
list = [2, 'cat', 34.33, 'Travis'] #heterogeneous list

print (list[1])


#slicing
print(list[:]) #all members in the list
print(list[1:3]) #1 to index 3 without 3
print(list[:4]); #0 to index 4 without 4

#appending to list
list_1 = [3, 5, 7, 8, 9, 20]
list_1.append(3.33)
print(list_1)

#in built functions are
numbers = [2, 5, 7, 9]
print(len(numbers))

numbers = [2, 5, 7, 9]
print(max(numbers))

numbers = [2, 5, 7, 9]
print(min(numbers))

numbers = [2, 5, 7, 9, 15]
numbers.pop(2)

values = [2, 5, 7, 9]
values.remove(2)
print(values)

values = [2, 5, 7, 10]
values.reverse()
print(values)

animals = ['cat', 'dog', 'fish', 'cow', 'goat']
fish_index = animals.index('fish')
print(fish_index)

values = [2, 5, 10]
sum_of_values = sum(values)
print(sum_of_values)

values = [1, 7, 9, 3, 5]
# To sort the values in ascending order:
values.sort()
print(values)

values = [2, 10, 7, 14, 50]
# To sort the values in descending order:
values.sort(reverse = True)
print(values)


strings = ['cat', 'mammal', 'goat', 'is']
sort_by_alphabet = strings.sort()
sort_by_length = strings.sort(key = len)
print(sort_by_alphabet)
print(sort_by_length)

#looping through lsit

list = [1,3,3,4]
for elem in list:
    elem = elem + 5
    print(elem)


#list comprehensions
# List comprehensions are Python functions that are used for creating new sequences (such as lists, dictionaries, etc.)
# using sequences that have already been created. They help to reduce longer loops and make your code easier to read and maintain.

#below is code without comprehension
list_of_squares = []
for int in range(1, 10):
    square = int ** 2
    list_of_squares.append(square)
    print('List of squares using list without comprehension: {}'.format(list_of_squares))

#below is with comprehension
list_of_squares_2 = [int**2 for int in range(1, 10)]
print('List of squares using list comprehension: {}'.format(list_of_squares_2))


References:
https://www.guru99.com/accessing-internet-data-with-python.html

Setting up network link conditioner for Software testing

Setting up network link conditioner for Software testing



References:
https://www.testdevlab.com/blog/2017/07/how-to-set-up-specific-network-conditions-for-software-testing/

If Media server has public address, do we require TURN?

If Media server has public address, do we require TURN?

Below are the three ways that the WebRTC won't work !

They don’t put a TURN server at all, relying on media servers with public IP addresses
They don’t put a TURN server at all, assuming STUN is enough for a peer to peer based service (!)
They don’t configure the TURN server they use for TCP and TLS connectivity, assuming UDP relay is more than enough



References:
https://bloggeek.me/turn-public-ip-address/

What is ICE in WebRTC?


What is ICE in WebRTC?
ICE stands for Interactive Connectivity Establishment.

It is a standard method of NAT traversal used in WebRTC
ICE deals with the process of connecting media through NATs by conducting connectivity checks.


ICE collects all available candidates (local IP addresses, reflexive addresses – STUN ones and relayed addresses – TURN ones). All the collected addresses are then sent to the remote peer via SDP.

Once the WebRTC Client has all the collected ICE addresses of itself and its peer, it starts initiating connectivity checks. These checks essentially try sending media over the various addresses until success.


The downside of using ICE is the time it takes, which can be 10s of seconds. To run faster, a new mechanism was added in WebRTC called Trickle ICE.


References
https://webrtcglossary.com/ice/

Java How to set DSCP value?

Java How to set DSCP value?




References
http://what-when-how.com/Tutorial/topic-9263u0qpr/Java-Network-Programming-290.html
https://medium.com/mindorks/improve-network-performance-of-apps-with-diffserv-bce766d3373a

What is DiffServ

What is DiffServ

Differentiated Services (DiffServ, or DS) is a protocol for specifying and controlling network traffic by class so that certain types of traffic get precedence - for example, voice traffic, which requires a relatively uninterrupted flow of data, might get precedence over other kinds of traffic. Differentiated Services is the most advanced method for managing traffic in terms of what is called Class of Service (CoS). Unlike the earlier mechanisms of 802.1p tagging and Type of Service (ToS), Differentiated Services avoids simple priority tagging and depends on more complex policy or rule statements to determine how to forward a given network packet. An analogy is made to travel services, in which a person can choose among different modes of travel - train, bus, airplane - degree of comfort, the number of stops on the route, standby status, the time of day or period of year for the trip, and so forth. For a given set of packet travel rules, a packet is given one of 64 possible forwarding behaviors - known as per hop behaviors (PHBs). A six-bit field, known as the Differentiated Services Code Point (DSCP), in the Internet Protocol (IP) header specifies the per hop behavior for a given flow of packets.


Differentiated Services and the Class of Service approach provide a way to control traffic that is both more flexible and more scalability than the Quality of Service approach.

The DiffServ architecture defines the DiffServ (DS) field, which supersedes the ToS field in IPv4 to make per-hop behavior (PHB) decisions about packet classification and traffic conditioning functions, such as metering, marking, shaping, and policing.

The RFCs do not dictate the way to implement PHBs; this is the responsibility of the vendor. Cisco implements queuing techniques that can base their PHB on the IP precedence or DSCP value in the IP header of a packet. Based on DSCP or IP precedence, traffic can be put into a particular service class. Packets within a service class are treated the same way.


References:
https://whatis.techtarget.com/definition/Differentiated-Services-DiffServ-or-DS

What is DSCP?



What is DSCP?

The six most significant bits of the DiffServ field is called as the DSCP. The last two Currently Unused (CU) bits in the DiffServ field were not defined within the DiffServ field architecture; these are now used as Explicit Congestion Notification (ECN) bits. Routers at the edge of the network classify packets and mark them with either the IP Precedence or DSCP value in a Diffserv network. Other network devices in the core that support Diffserv use the DSCP value in the IP header to select a PHB behavior for the packet and provide the appropriate QoS treatment.


ToS Byte

P2 P1 P0 T2 T1 T0 CU1 CU0
IP precedence—three bits (P2 to P0)

Delay, Throughput and Reliability—three bits (T2 to T0)

CU (Currently Unused)—two bits(CU1-CU0)


DiffServ Field

DS5 DS4 DS3 DS2 DS1 DS0 ECN ECN
DSCP—six bits (DS5-DS0)



ECN—two bits



References:
https://www.cisco.com/c/en/us/support/docs/quality-of-service-qos/qos-packet-marking/10103-dscpvalues.html

React JS - Develop Components in isolation

React JS - Develop Components in isolation


Usually, in an app, you have a lot of UI components, and each of them has many different states. For an example, a simple button component could have the following states:

In a regular state, with a text label.
In the disabled mode.
In a loading state.
Usually, it’s hard to see these states without running a sample app or some examples.

Create React App doesn’t include any tools for this by default, but you can easily add Storybook for React (source) or React Styleguidist (source) to your project. These are third-party tools that let you develop components and see all their states in isolation from your app.


Getting Started with Styleguidist
Styleguidist combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, with an environment for developing components in isolation, similar to Storybook. In Styleguidist you write examples in Markdown, where each code snippet is rendered as a live editable playground.

First, install Styleguidist:

yarn add react-styleguidist

 "scripts": {
+    "styleguide": "styleguidist server",
+    "styleguide:build": "styleguidist build",
     "start": "react-scripts start",


Analyzing the Bundle Size

Source map explorer analyzes JavaScript bundles using the source maps. This helps you understand where code bloat is coming from.

To add Source map explorer to a Create React App project, follow these steps:

yarn add source-map-explorer

"scripts": {
+    "analyze": "source-map-explorer 'build/static/js/*.js'",
     "start": "react-scripts start",
     "build": "react-scripts build",
     "test": "react-scripts test",

npm run build
npm run analyze


Using HTTPS in Development
You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using the "proxy" feature to proxy requests to an API server when that API server is itself serving HTTPS.

To do this, set the HTTPS environment variable to true, then start the dev server as usual with npm start:

set HTTPS=true&&npm start
HTTPS=true npm start

Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page.




References:
https://facebook.github.io/create-react-app/docs/developing-components-in-isolation

What is prettier


Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the Prettier's GitHub page for more information, and look at this page to see it in action.

To format our code whenever we make a commit in git, we need to install the following dependencies:

yarn add husky lint-staged prettier

husky makes it easy to use githooks as if they are npm scripts.
lint-staged allows us to run scripts on staged files in git. See this blog post about lint-staged to learn more about it.
prettier is the JavaScript formatter we will run before commits.


References:
https://github.com/prettier/prettier

Reat App Development - Basics



Debugging in the Editor
This feature is currently only supported by Visual Studio Code and WebStorm.

Visual Studio Code
You would need to have the latest version of VS Code and VS Code Chrome Debugger Extension installed.

Then add the block below to your launch.json file and put it inside the .vscode folder in your app’s root directory.

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Chrome",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}/src",
      "sourceMapPathOverrides": {
        "webpack:///src/*": "${webRoot}/*"
      }
    }
  ]
}

Start your app by running npm start, and start debugging in VS Code by pressing F5 or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.


WebStorm
You would need to have WebStorm and JetBrains IDE Support Chrome extension installed.

In the WebStorm menu Run select Edit Configurations.... Then click + and select JavaScript Debug. Paste http://localhost:3000 into the URL field and save the configuration.

Start your app by running npm start, then press ^D on macOS or F9 on Windows and Linux or click the green debug icon to start debugging in WebStorm.



References:
https://facebook.github.io/create-react-app/docs/setting-up-your-editor

React Web App - Some initial notes



Create React App is an officially supported way to create single-page React applications.

There are three methods to create a new react app

1. npx create-react-app my-app
2. npm init react-app my-app
3. yarn create react-app my-app

Once the project is built, can do the following to get it running

yarn start

To build the product,
yarn build

Folder structure is like below

my-app/
  README.md
  node_modules/
  package.json
  public/
    index.html
    favicon.ico
  src/
    App.css
    App.js
    App.test.js
    index.css
    index.js
    logo.svg

For the project to build, these files must exist with exact filenames:

public/index.html is the page template;
src/index.js is the JavaScript entry point.
You can delete or rename the other files.


You may create subdirectories inside src. For faster rebuilds, only files inside src are processed by Webpack. You need to put any JS and CSS files inside src, otherwise Webpack won’t see them.

You can, however, create more top-level directories. They will not be included in the production build so you can use them for things like documentation.

Updating to new release

Create React App is divided into two packages:

create-react-app is a global command-line utility that you use to create new projects.
react-scripts is a development dependency in the generated projects (including this one).

When you run npx create-react-app my-app it automatically installs the latest version of Create React App.

Create React App creates the project with the latest version of react-scripts so you’ll get all the new features and improvements in newly created apps automatically.

In most cases bumping the react-scripts version in package.json and running npm install (or yarn install) in this folder should be enough, but it’s good to consult the changelog for potential breaking changes.



References:
https://facebook.github.io/create-react-app/docs/getting-started

CSS what is mixin?


CSS what is mixin?

Mixins allow document authors to define patterns of property value pairs, which can then be reused in other rulesets. The mixin name is a class selector that identifies the mixin being declared. The @mixin keyword must be followed by the mixin name and a declaration block.

The following lines define a mixin clearfix, and give it three property-value pairs:

@mixin .clearfix {
  overflow: hidden;
  _overflow: visible;
  zoom: 1;
}
Document authors may use mixins to group vendor prefixes and simplify their code during the time it takes for vendors to stabilize their implementations.

The following example groups various vendor prefixes for border-radius:

@mixin .rounded7px {
  -moz-border-radius: 7px;
  -webkit-border-radius: 7px;
  border-radius: 7px;
}


When you find yourself writing the same code over and over again, it feels like Sass mixins might help you out.
Sass mixins are CSS functions that you can include whenever you want.

@mixin overlay() {
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
}

The name of this mixin is overlay. You can reference this mixin in any CSS rule by using @include:

.modal-background{
  @include overlay();
  background: black;
  opacity: 0.9;
}

As usual, this .scss will be compiled into .css:

.modal-background{
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  background: black;
  opacity: 0.9;
}




References:
http://oocss.org/spec/css-mixins.html

WebRTC SimulCast and ABR


WebRTC SimulCast and ABR



References
https://bloggeek.me/webrtc-simulcast-and-abr-two-sides-of-the-same-coin/

Styles and Assets






This project setup uses Webpack for handling all assets. Webpack offers a custom way of “extending” the concept of import beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to import the CSS from the JavaScript file:

In the Button.css


.Button {
   padding : 20px;
}

In Button.js

Import React, {Component} from 'react'
Import './Button.css' //This tells web pack that the component uses this csss

Class Button extends Component {
render(){
   Return
 

}

}


This is not required for React but many people find this feature convenient. You can read about the benefits of this approach here. However you should be aware that this makes your code less portable to other build tools and environments than Webpack

In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified .css file in the build output.

If you are concerned about using Webpack-specific semantics, you can put all your CSS right into src/index.css. It would still be imported from src/index.js, but you could always remove that import if you later migrate to a different build tool.



References:
https://facebook.github.io/create-react-app/docs/using-https-in-development

Measuring Jitter accurately

Measuring Jitter accurately

References:
https://www.lightwaveonline.com/home/article/16663492/measuring-jitter-accurately

Program to calculate the Round Trip Time (RTT)



Round trip time(RTT) is the length of time it takes for a signal to be sent plus the length of time it takes for an acknowledgement of that signal to be received. This time therefore consists of the propagation times between the two point of signal.
On the Internet, an end user can determine the RTT to and from an IP(Internet Protocol) address by pinging that address. The result depends on various factors :-

    The data rate transfer of the source’s internet connection.
    The nature of transmission medium.
    The physical distance between source and destination.
    The number of nodes between source and destination.
    The amount of traffic on the LAN(Local Area Network) to which end user is connected.
    The number of other requests being handled by intermediate nodes and the remote server.
    The speed with which intermediate node and the remote server function.
    The presence of Interference in the circuit.
import time
import requests
 
# Function to calculate the RTT
def RTT(url):
 
    # time when the signal is sent
    t1 = time.time()
 
    r = requests.get(url)
 
    # time when acknowledgement of signal 
    # is received
    t2 = time.time()
 
    # total time taken
    tim = str(t2-t1)
 
    print("Time in seconds :" + tim)
 
# driver program 
# url address
url = "http://www.google.com"
RTT(url)

References:
https://www.geeksforgeeks.org/program-calculate-round-trip-time-rtt/

Android how to force device to install 64 bit version of the libraries



The below command set is very handy in doing this.

:: Command Line
# A successful install:
> adb install --abi armeabi-v7a YOUR_APK_FILE.apk
Success

# If your APK does not have the 64-bit libraries:
> adb install --abi arm64-v8a YOUR_APK_FILE.apk
adb: failed to install YOUR_APK_FILE.apk: Failure [INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

# If your device does not support 64-bit, an emulator, for example:
> adb install --abi arm64-v8a YOUR_APK_FILE.apk
ABI arm64-v8a not supported on this device

References
https://developer.android.com/distribute/best-practices/develop/64-bit


Electron JS why XHR works but not fetch()





You're making a cross-origin request (your requesting domain is different than the API's domain) and browsers have special rules around that. In a Node context (i.e. via node's http/https modules), you don't have to worry about CORS and can in general do lower level work on network requests. Browsers, on the other hand, have a lot of security around CORS. When you use fetch your network request is going through Chromium's networking layer and so it's subject to those restrictions. When you use node's http/https, you're using node's. It's sort of a confusing point about Electron--a renderer process seems like a normal web context but you actually have access to all of node.js' APIs too, allowing you to things you can't do in a plain browser.

I would check and see if including an API key in that request changes the response of the API (maybe that triggers their API adding the appropriate CORS headers like Access-Control-Allow-Origin). Maybe the API wasn't meant to be called within a browser context and so a more node.js oriented approach is the way to go.

This is a great article on CORS and the ways to deal with it: https://medium.com/@baphemot/understanding-cors-18ad6b478e2b


References:
https://stackoverflow.com/questions/48969495/in-javascript-how-do-i-should-i-use-async-await-with-xmlhttprequest

How to make GET request with XHR, Promise

Define the API like this below

var remoteCode = await this.getServerResponse('https://api.myjson.com/bins/j9soc');

getServerResponse(url) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.setRequestHeader('Accept','application/json');
        xhr.setRequestHeader('Authorization','bWNkLWFkbWluOkFkbWluMUAxMjM');
        xhr.responseType = 'text';
        xhr.onload = function () {
            var status = xhr.status;
            console.log('XHR status is '+status);
            if (status == 200) {
                resolve(xhr.responseText);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
}


Refereces

Why shouldn't one use ECB encryption





The main reason not to use ECB mode encryption is that it's not semantically secure — that is, merely observing ECB-encrypted ciphertext can leak information about the plaintext (even beyond its length, which all encryption schemes accepting arbitrarily long plaintexts will leak to some extent).

Specifically, the problem with ECB mode is that encrypting the same block (of 8 or 16 bytes, or however large the block size of the underlying cipher is) of plaintext using ECB mode always yields the same block of ciphertext. This can allow an attacker to:

    detect whether two ECB-encrypted messages are identical;
    detect whether two ECB-encrypted messages share a common prefix;
    detect whether two ECB-encrypted messages share other common substrings, as long as those substrings are aligned at block boundaries; or
    detect whether (and where) a single ECB-encrypted message contains repetitive data (such as long runs of spaces or null bytes, repeated header fields or coincidentally repeated phrases in text).

There's a nice graphical demonstration of this weakness on Wikipedia, where the same (raw, uncompressed) image is encrypted using both ECB mode and a semantically secure cipher mode (such as CBC, CTR, CFB or OFB):

While this scenario is somewhat artificial (one would not usually encrypt raw images like this), it nicely demonstrates the problem with ECB mode: repetitive areas in the input image result in repetitive patterns in the encrypted output, so that many large-scale features of the image remain recognizable despite the encryption. In the real world, a cryptanalyst attacking an ECB-based encryption scheme would be more likely to look for such patterns in a hex dump of the ciphertext, but the principle is the same.

An actual case of this weakness of ECB encryption contributing to a real-world data compromise is given by the 2013 Adobe password database leak, as described in this answer. Here, one element contributing to the severity of the leak was that, instead of hashing them properly, Adobe had encrypted the passwords using ECB mode. This allowed the attackers to quickly locate passwords shared by multiple accounts, or sharing a common prefix with other passwords (like password1 and password2), and also revealed the approximate length of each password.

The ECB encryption mode also has other weaknesses, such as the fact that it's highly malleable: as each block of plaintext is separately encrypted, an attacker can easily generate new valid ciphertexts by piecing together blocks from previously observed ciphertexts.

However, the malleability is only an issue if ECB encryption is used without a message authentication code, and, in this situation, is shared (to some extent) by all other non-authenticated encryption modes, like the aforementioned CBC, CTR, CFB and OFB. Thus, it cannot really be considered a specific weakness of ECB mode, even though it does tend to be an additional issue whenever ECB mode is used.

What should I use instead?

You should use any authenticated encryption mode, such as GCM, EAX or OCB.

Personally, for short messages, I'm rather fond of SIV mode (RFC 5279), which provides an extra layer of misuse-resistance. (Many other encryption modes will break rather badly if the same IV / nonce is accidentally used to encrypt multiple messages. SIV mode retains all its security properties in this situation, except for leaking whether the encrypted messages are identical.)

You can also use any traditional semantically secure encryption mode (such as CBC or CTR), combined with a message authentication code (such as HMAC) using the Encrypt-then-MAC construction. (That is, you should first encrypt the message, then compute a MAC of the ciphertext, and append it to the ciphertext.) As long as you make sure to verify the MAC before attempting to decrypt the message, this construction will protect you from the various vulnerabilities of these modes to active (chosen-ciphertext) attacks.

For disk encryption or similar applications that require the ability modify parts of the ciphertext without re-encrypting all the data, you should use a cipher mode designed for that purpose, such as XTS. Note that such modes generally lack resistance to active attacks, and may have other weaknesses that should be understood before using them. If possible, they should be combined with some form of integrity protection, such as a MAC on a hash tree.


References:
https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption

Electron JS - CORS error



Weird CORS error issues were happening when dealing with Electron JS. When trying to do from the renderer process, always receive CORS error.

To debug this, attempted to do the request using XMLHTTPRequest, which is like this below

 var oReq = new XMLHttpRequest();
    oReq.onload = this.reqListener;
    oReq.onerror = this.reqError;
    oReq.open('get', 'https://api.myjson.com/bins/j9soc', true);
    oReq.send();

reqListener() {
    console.log('reqListener called');
    var data = JSON.parse(this.responseText);
    console.log(data);
  }
 
  reqError(err) {
    console.log('reqError called');
    console.log('Fetch Error :-S', err);
  }

The site hosted a sample JSON and that was coming properly without issues.

Now, the same attempting to do with the fetch api, This was also successful.

fetch('https://api.myjson.com/bins/j9soc')
      .then(
        function(response) {
          if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code: ' +
              response.status);
            return;
          }

          // Examine the text in the response
          response.json().then(function(data) {
            console.log('Fetch response received successfully without CORS!');
            console.log(data);
          });
        }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

Now decided to do the same from the service class and see what happens.

Surprisingly from Saga also received the response.

References

Electron js - Calling a function from another



To call a function from another, we have to use this references. For e.g.

var oReq = new XMLHttpRequest();
    oReq.onload = this.reqListener;
    oReq.onerror = this.reqError;
    oReq.open('get', './api/some.json', true);
    oReq.send();


reqListener() {
    console.log('reqListener called');
    var data = JSON.parse(this.responseText);
    console.log(data);
  }
 
  reqError(err) {
    console.log('reqError called');
    console.log('Fetch Error :-S', err);
  }

If this is omitted from the onload assignment, then it complaints that the method not found.


References

Javascript Classes Syntax, the differences from Prototype



A constructor function is initialized with a number of parameters, which would be assigned as properties of this, referring to the function itself. The first letter of the identifier would be capitalized by convention.

// Initializing a class definition
class Hero {
    constructor(name, level) {
        this.name = name;
        this.level = level;
    }
}

With classes this syntax is simplified, and the method can be added directly to the class. Using the method definition shorthand introduced in ES6, defining a method is an even more concise process.

var obj = {
  foo() {
    return 'bar';
  }
}

console.log(obj.foo());
// expected output: "bar"


References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
https://www.digitalocean.com/community/tutorials/understanding-classes-in-javascript

Electron JS Babel What is it ?





It seems imports are not implemented in either Node 6 or Chrome 51 so Electron also does not support them, according to this post: https://discuss.atom.io/t/does-electron-support-es6/19366/18

const { BrowserWindow } = require('electron').remote
// or
const { remote } = require('electron')
const { BrowserWindow } = remote

But you can use babel with the require hook: http://babeljs.io/docs/usage/require/

To be auto compile each required modules so you will be able to use imports. Of course the script given to electron (the one that require babel) is not compiled so you need to make a bootstrap:



References:
https://stackoverflow.com/questions/35374353/es6-syntax-import-electron-require

Electron JS - import statement error



'import' keyword is a part of ES6 modules syntax. Node.js doesn't provide native support for ES6 modules (basic support is actually available since Node 8.5, but it's a bit limited

/Users/user/Documents/projects/BroadCloudProvisioning/DesktopDev/Samples/yarnelectron/main.js:3
import Service from './service.js'
^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.Module._extensions..js (modul


References:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000735104-BUG-ES6-import-from-Unexpected-token-import-

Electron app development


Electron app development

- https://www.systango.com/blog/electron-js-lets-build-first-desktop-app-together/
- Electron with firebase : https://www.youtube.com/watch?v=bWS0ocfszmE
- https://www.christianengvall.se/electron-packager-tutorial/
- https://www.youtube.com/watch?v=kN1Czs0m1SU
https://medium.com/@kitze/%EF%B8%8F-from-react-to-an-electron-app-ready-for-production-a0468ecb1da3


https://blog.learningtree.com/build-your-very-own-electron-cross-platform-desktop-app-using-javascript/

Salesforce Lightning web components


Salesforce Lightning web components

Two ways to create lightning components
- Lightning web components
- Aura components

Lightning Web Components uses core Web Components standards and provides only what’s necessary to perform well in browsers supported by Salesforce. Because it’s built on code that runs natively in browsers, Lightning Web Components is lightweight and delivers exceptional performance. Most of the code you write is standard JavaScript and HTML.





References:
https://developer.salesforce.com/docs/component-library/documentation/lwc

Writing First Electron JS app




Electron enables you to create desktop applications with pure JavaScript by providing a runtime with rich native (operating system) APIs. You could see it as a variant of the Node.js runtime that is focused on desktop applications instead of web servers.



References:
https://electronjs.org/docs/tutorial/first-app

iOS In app purchase


An in-app purchase (or IAP) allows developers to charge users for specific functionality or content while using an app. Implementing IAPs is particularly compelling for several reasons:

When creating app ID, need to notice that Scroll down to the App Services section. Notice that In-App Purchase and GameCenter are enabled by default. Click Continue and then Register and Done. Next, you’ll create a matching app in App Store Connect.

Below two things are mandatory before enabling IAP in the app


    Make sure you have accepted the latest Apple Development Program License Agreement on developer.apple.com.
    Make sure you have accepted the latest Paid Applications agreement in the Agreements, Tax, and Billing section in App Store Connect.


If you see a section entitled Request Contracts containing a row for Paid Applications, then click the Request button. Fill out all the necessary information and submit it. It may take some time for your request to be approved. Sit tight!

Otherwise, if you see Paid Applications listed under Contracts In Effect, then it looks like you’ve already done this step! Nice job!

Apple can take days to approve these IAP-related agreements after you submit them. During this time, you won’t be able to display IAP products in your apps even if you implement everything correctly in code. This is a common source of frustration for folks implementing In-App Purchases for the first time. Hang in there!

Creating In-App Purchase Products

When offering IAPs you must first add an entry for each individual purchase within App Store Connect. If you’ve ever listed an app for sale in the store, it’s a similar process and includes things like choosing a pricing tier for the purchase. When the user makes a purchase, the App Store handles the complex process of charging the user and reply with data about such operation.

There are a whole bunch of different types of IAP you can add:

Below are different types of IAPs

 Consumable: These can be bought more than once and can be used up. These are a good fit for extra lives, in-game currency, temporary power-ups, and the like.
Non-Consumable: Something that you buy once, and expect to have permanently such as extra levels and unlockable content. The RazeFace illustrations from this tutorial fall into this category.

Non-Renewing Subscription: Content that’s available for a fixed period of time.

Auto-Renewing Subscription: A repeating subscription such as a monthly

We can only offer In-App Purchases for digital items, and not for physical goods or services.


Below are the few things to be entered for making an IAP product

Next, fill out the details for the IAP as follows:

    Reference Name: A nickname identifying the IAP within iTunes Connect. This name does not appear anywhere in the app. The title of the RazeFace you’ll be unlocking with this purchase is Swift Shopping, so enter that here.

    Product ID: This is a unique string identifying the IAP. Usually it’s best to start with the Bundle ID and then append a unique name specific to this purchasable
item. For this tutorial, make sure you append swiftshopping, as this will be used later within the app to look up the RazeFace to unlock. For example, you can use: com.theNameYouPickedEarlier.razefaces.swiftshopping.

    Cleared for Sale: Enables or disables the sale of the IAP. You want to enable it!
    Price Tier: The cost of the IAP. Choose Tier 1.


There’s one more step required before you can delve into some code. When testing in-app purchases in a development build of an app, Apple provides a test environment which allows you to “purchase” your IAP products without creating financial transactions.

These special test purchases can only be made by a special “Sandbox Tester” user account in App Store Connect. You’re almost at the code, I promise!



References:
https://www.raywenderlich.com/5456-in-app-purchase-tutorial-getting-started

React Native - Flex box for layout




Flexbox is designed to provide a consistent layout on different screen sizes. One will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.Flexbox works the same way in React Native as it does in CSS on the web, The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.

Sample is given below

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

export default class FlexDirectionBasics extends Component {
  render() {
    return (
      // Try setting `flexDirection` to `column`.
     
       
       
       
      !View>
    );
  }
};

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);


References:
https://facebook.github.io/react-native/docs/flexbox

React-native : Display a list view





For displaying list view, one of the good component is FlatList

Below is how to use a flat list. We can wrap it in a component like this below

We can make CustomListView as a component (i.e. extend the react Component)

In the renderer, have a Container and place the CustomList

The custom List can be just a different file that exports a CustomList which is just returning a View (not necessarily need to be another component)

This class is going to be basically exporting a function which is named as CustomList. Now, in the Custom List, it can have a View and multiple Rows for each row

Something like this below

const CustomListView = (props) => (
   
                        data={props.itemList}
                renderItem={({ item }) => (
                   
                                                    name={item.name}
                            status={item.status}
                            timestamp={item.timestamp}
                        />
                !TouchableOpacity> )
            }
                keyExtractor={item => item.key.toString()}
            />
     
    !View>
);

Now, CustomListRow is again an Exported method that returns the View which displays the given components.


References:

The redux Store



The store has the following responsibilities:

    Holds application state;
    Allows access to state via getState();
    Allows state to be updated via dispatch(action);
    Registers listeners via subscribe(listener);
    Handles unregistering of listeners via the function returned by subscribe(listener).


There will only be a single store in a Redux application. When you want to split your data handling logic, you'll use reducer composition instead of many stores.


To create a store, pass all the reducers to createStore function

import { createStore } from 'redux'
import todoApp from './reducers'
const store = createStore(todoApp)


We can optionally specify the initial state as the second argument to createStore(). This is useful for hydrating the state of the client to match the state of a Redux application running on the server.

const store = createStore(todoApp, window.STATE_FROM_SERVER)

Below snippet gives could of useful infos

1. How to subscribe for the store
2. How to accèss the state directly from store
3. How to dispatch an action to the store

import {
  addTodo,
  toggleTodo,
  setVisibilityFilter,
  VisibilityFilters
} from './actions'

// Log the initial state
console.log(store.getState())

// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
const unsubscribe = store.subscribe(() => console.log(store.getState()))

// Dispatch some actions
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))

// Stop listening to state updates
unsubscribe()

References
https://redux.js.org/basics/store

Redux - Spiltting Reducers



It is possible to split the todos into multiple functions for simplicity. For e.g. in the below, todoApp function.

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    case ADD_TODO:
      return Object.assign({}, state, {
        todos: [
          ...state.todos,
          {
            text: action.text,
            completed: false
          }
        ]
      })


In the above function, all of the todo list action related are taken care
While in the below, all of the visibility related items are taken care

function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case TOGGLE_TODO:
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: !todo.completed
          })
        }
        return todo
      })

Now these two reducer functions can be combined in the below form

import { combineReducers } from 'redux'

const todoApp = combineReducers({
  visibilityFilter,
  todos
})


References:

Learning PJSIP

Learning PJSIP

references:
https://codeburst.io/learning-voip-rtp-and-sip-aka-awesome-pjsip-2035fa02cf88
https://www.pjsip.org/pjmedia/docs/html/page_pjmedia_samples_siprtp_c.htm

SIP Sequence flows

SIP Sequence flows


http://www.tech-invite.com/fo-sip/tinv-fo-sip-service-13-09.html

Various Flutter challenges

Flutter Challenge Youtube
Flutter Challenge Twitter
Flutter Challenge WhatsApp

references
https://proandroiddev.com/flutter-challenge-youtube-ec5ff36eca9b
https://itnext.io/flutter-challenge-twitter-a1cb17f1e21b
https://medium.com/@dev.n/flutter-challenge-whatsapp-b4dcca52217b

Decrypting SSL traffic


Decrypting SSL traffic

https://www.citrix.com/blogs/2015/02/20/no-private-key-no-problem-how-to-decrypt-ssl-traffic-with-session-keys/

Is TLS server cert and signing cert are the same?


Is TLS server cert and signing cert are the same?


References:
https://stackoverflow.com/questions/9527972/ssl-certificate-same-as-signing-certificate

What is Change Cipher Spec, Alert and Handshake protocol?



What is Change Cipher Spec, Alert and Handshake protocol?


References:
http://www.idc-online.com/technical_references/pdfs/data_communications/Change%20Cipher_Spec_Alert_and_Handshake_Protocol.pdf


Remote Device Lab:



Some defects will appear only certain OS versions or some form factors. If we have lab which has softwares such as deviceConnect, it would be easy to debug those. This will help to remotely connect to the device and do the debugging.

Test Automation setup : A common machine where the the test automation software can be installed and device could be connected to keep it running.
 deviceConnect seems to be having


Below are the recommended device sets as of now. The list of devices we can send as they are getting released.


1. Mac machine that can be used to upgrade OS versions and do tests. If we have with multiple OS versions

2. Windows machines from at least AMD, Intel processor versions and various OS versions available. Such as Windows 10, Windows 8. 

3. iOS devices : iPhone X , iPhone 8, iPad 12", iPad 10 inch,

4. Android devices : Google Pixel. 

These machines may require VPN or customer specific access requirements so that the application can reach the site.

SIP Early Media Authorization


Early Media Authorization


References:
https://tools.ietf.org/html/rfc5009

SIP: What is the use of P-Early-Media header



P-Early-Media header field is used  within SIP [1] messages in certain SIP networks to authorize the cut-through of backward and/or forward early media when permitted by the early media policies of the networks involved.  The P-Early-Media header field is intended for use in a SIP network, such as a 3GPP IMS [13][14] that has the following characteristics: its early media policy prohibits the exchange of early media between end users; it is interconnected with other SIP networks that have unknown, untrusted,  or different policies regarding early media; and it has the capability to "gate" (enable/disable) the flow of early media to/from user equipment.

Within an isolated SIP network, it is possible to gate early media associated with all endpoints within the network to enforce a desired early media policy among network endpoints.  However, when a SIP network is interconnected with other SIP networks, only the boundary node connected to the external network can determine which early  media policy to apply to a session established between endpoints on different sides of the boundary.  The P-Early-Media header field provides a means for this boundary node to communicate this early media policy decision to other nodes within the network.

References:
https://tools.ietf.org/html/rfc5009

Flutter Display images from internet



Images.networks {} gives ability to load the image from internet 

Also, the GIF format is supported out of the box.

Class MyApp extends StatelessWidget {

@override
Widget build (BuildContext context){
var title = 'Web Images';
return MaterialApp (title:title, home:Scafold(appbar:AppBar{title:Text(title);},body:Image.Network{}));
}
}

App can also fade in images with the below code

FadeInImage.memoryNetwork(
Placeholder:kTramsparentImage,
Image:''
)

This technique can be used for displaying loading bar as well.

For e.g.

FadeInImage.memoryNetwork(
Placeholder:'assets/loading.gif'),


References:
https://flutter.io/cookbook/images/network-image/

Flutter Lists

Flutter Lists

A sample is like below

Class MyApp extends StatelessWidget {

@override
Widget build (BuildContext context){

Final title = 'ListTitle';

Return MaterialApp(
 Title : title,
 home : Scaffold(
  appBar : AppBar(title:Text(title)),
  Body : ListView(children : [ListTitle(leading:Icon(Icons.map),title:Text('Map')),ListTitle(title:Text('Album'),leading:Icon(Icons.map))])
 )
);
}
}

References:
https://flutter.io/cookbook/lists/basic-list/


Flutter creating a horizontal list

Sample is like below

Class MyApp extends StatelessWidget {

@override
Widget build (BuildContext context)
{
  final title = 'MyApp';
  return MaterialApp( title: title, home : Scaffold (appBar: AppBar(title:Text(title)),
  Body : Container (margin: EdgeInsets.symmetric(vertical:20.0, height : 200.0, child:ListView(scrollDirection:Axis.horizontal, children:[Container(width:160.0,color:Color.red),Container(width:160,color:Color.blue)])
}

}

References:
https://flutter.io/cookbook/lists/horizontal-list/

Flutter: How to work with Long list

Flutter: How to work with Long list

Class MyApp extends StatelessWidget {

Final List items; 
MyApp({Key key, @required this.items}) : super (key:key)
{
    @override
    Widget build (BuildContext context) {
    return MaterialApp(title:title, home:Scaffold(appbar:AppBar(title:Text(title)))),body:ListView.builder(itemCount:items.length,itemBuilder:(context, index){
return ListTitle(title:Text('${items[index]}'))
})
    }
}

}

References:
https://flutter.io/cookbook/lists/long-lists/

Flutter: Implementing Swipe to Dismiss





Flutter: Implementing Swipe to Dismiss

Below are the steps to do this:

1. Create List of items
2. Wrap each item in a dismissible widget
3. Provide "Lead Behind" indicators

To create a list of items, its as usual the code is like

Final items = List.generate(20,(i) => "Item ${I+1}")

Now this can be converted into a list like below

ListView.builder(itemCount:10,itemBuilder:(context, index){ return ListTitle(title:Text($itmes[index])})

The crux is that we should have list item wrapped inside a Dismissable object

Dismissable(key:Key(item)),
onDismissed:(direction){
setState(){
items.removeAt(index)
}
Scaffold.of(context).showSnackBar(SnackBar(content:Text(${item dismissed})))
}
Background:Container(color:Colors.red);
Child:ListTitle(title:Text('$item'))

References:
https://flutter.io/cookbook/gestures/dismissible/

Flutter: Grid List

Flutter: Grid List

A sample is like below

Flutter : Handling Gestures

Below are the steps involved in this:

1. Create a UI Element
2. Wrap it with GestureDetector with the onTap callback


Class MyButton extends StatelessWidget {

@override
Widget build(BuildContext context) {
    return GestureDetector (
    onTap() {
    final snackbar = SnackBar (content:Text("Tap"))
    Scaffold.of(context).showSnackBar(snackBar)
}
child:Container(padding: EdgeInsets.all(12.0),decoration : BoxDecoration(color:Theme.of(context).buttonColor,borderRadius:BorderRadius.circular(8.0))),
child:Text("My Button");
    )

}

}

References:
https://flutter.io/cookbook/gestures/handling-taps/

Flutter: Adding Material Touch Ripples


Flutter: Adding Material Touch Ripples

Below given some guidelines for adding ripple animation when something is touched on the screen.

1. Create a Widget to tap
2. Wrap it in an InkWell widget to manage tap callbacks and ripple animations

Class MyButtpn extends StatelessWidget {
@override
Widget build(BuildContext context){
return InkWell(
onTap:() {
Scaffold.of.(context).showSnackBar(SnackBar (content : Text('Tap')),
}
child:Container(padding:EdgeInsets.all(12.0)),child:Text('Flat Button')
);
}


}


References:
https://flutter.io/cookbook/gestures/ripples/

Flutter: Navigating to new screen

Flutter: Navigating to new screen

In flutter world, everything is Widget!

1. Create new screen
2. Navigate to the new screen using Navigator.push
3. Return to the first screen using Navigator.pop.

Thats all mainly to be done.

class FirstScreen extends StatlessWidget {
@Override
Widget build(BuildContext context){
Return Scaffold(appBar:AppBar(title:Text('First Screen')))
}
}

References
https://flutter.io/cookbook/navigation/navigation-basics/