Thursday, April 29, 2021

Git diff command in detail

Diff command takes two inputs and reflects the differences between them. It is not necessary that these inputs are files only. It can be branches, working trees, commits and more. 


Below is an output 


diff --git a/test.html b/test.html

index 0b3f252..d629d58 100755

--- a/test.html

+++ b/test.html

@@ -178,8 +178,8 @@



  1. The first line shows the file names that have been considered as the input in git diff. You can see that they have been marked by a and b along with the two different file state that has been taken as input.
  2. This line is not of use. This shows the metadata related to the command and the execution of it on the files. this is the object hash value required by Git for internal use.
  3. This line defines the symbol, called a legend, to tell you what is used to describe the first file and what is used to describe the second file. As you can see, – is used in front of the first file and + is used in front of the second file. So whenever diff shows you the changes related to the first file, they will be marked by – and the changes in the second file will be marked by the symbol +.
  4. The fourth line shows you symbol @@ and symbols ahead of it. They are called chunks. Chunks in git diff define the change’ summary. In our image below the following chunk can be seen @@ -178,8 +178,8 @@
  5. This means that line 178 and 8 lines followed by it are displayed with the changes + a bit of context 



Chunk

A diff doesn't show the complete file from beginning to end: you wouldn't want to see everything in a 10,000 lines file, when only 2 lines have changed. Instead, it only shows those portions that were actually modified. Such a portion is called a "chunk" (or "hunk"). In addition to the actual changed lines, a chunk also contains a bit of "context": some (unchanged) lines before and after the modification so you can better understand in what context that change happened.

Chunk Header

Each of these chunks is prepended by a header. Enclosed in two "@" signs each, Git tells you which lines were affected. In our case the following lines are represented in the first chunk:

  • From file A (represented by a "-"), 6 lines are extracted, beginning from line no. 34
  • From file B (represented by a "+"), 8 lines are displayed, also starting from line no. 34

The text after the closing pair of "@@" aims to clarify the context, again: Git tries to display a method name or other contextual information of where this chunk was taken from in the file. However, this greatly depends on the programming language and doesn't work in all scenarios.


 

Changes

Each changed line is prepended with either a "+" or a "-" symbol. As explained, these symbols help you understand how exactly version A and B look: a line that is prepended with a "-" sign comes from A, while a line with a "+" sign comes from B.
In most cases, Git picks A and B in such a way that you can think of A/- as "old" content and B/+ as "new" content.

Let's look at our example:

  • Change #1 contains two lines prepended with a "+". Since no counterpart in A existed for these lines (no lines with "-"), this means that these lines were added.
  • Change #2 is just the opposite: in A, we have two lines marked with "-" signs. However, B doesn't have an equivalent (no "+" lines), meaning they were deleted.
  • In change #3, finally, some lines were actually modified: the two "-" lines were changed to look like the two "+" lines below.






References:

https://www.toolsqa.com/git/git-diff/

Sunday, April 25, 2021

Android WebView go to a specific page in history

Below code will be helpful for this 


public void goBackInWebView(){

    WebBackForwardList history = webView.copyBackForwardList();

    int index = -1;

    String url = null;


    while (webView.canGoBackOrForward(index)) {

          if (!history.getItemAtIndex(history.getCurrentIndex() + index).getUrl().equals("about:blank")) {

             webView.goBackOrForward(index);

             url = history.getItemAtIndex(-index).getUrl();

             Log.e("tag","first non empty" + url);

             break;

           }

           index --;


    }

   // no history found that is not empty

   if (url == null) {

      finish();

   }



references:

https://stackoverflow.com/questions/22515991/how-to-navigate-webpage-history-in-webview

Saturday, April 24, 2021

How to avoid ad violation policies

There are two ways


1. Setup as Demo Ads

2. Setup as Test Device 


When you configure your Android or iOS device as a test device, the AdMob Network sends production ads in test mode to your device using the ad unit IDs you've created in your AdMob account. 


Ads served by the AdMob Network will display a label that lets you know you’re in test mode. Look for the test mode label before clicking on an ad. 


Below are the steps to enable Test Mode 


Sign in to your AdMob account at https://apps.admob.com.

Click Settings in the sidebar.

Click the Test devices tab.

Click Add test device.  

Select the platform of your device.

Enter a device name. Consider using a name that will help you quickly identify your devices in your AdMob account.

Note: The device name will be visible to anyone who has access to your AdMob account.

Enter your Advertising ID/IDFA. Learn how to find your advertising ID/IDFA. 

Select a gesture to use to activate ad inspector:

None. If you select none, you can still activate ad inspector with an API call. Learn more. 

Shake 

Flick twice  

Click Done. 




references:

https://support.google.com/admob/answer/9691433

https://support.google.com/admob/answer/9388275?hl=en#:~:text=Test%20devices,-Test%20devices%20allow&text=You%20can%20configure%20your%20device,created%20in%20your%20AdMob%20account.


Thursday, April 22, 2021

Android WebView how to do stack navigation



@Override

public void onBackPressed() {

    if (web.copyBackForwardList().getCurrentIndex() > 0) {

        web.goBack();

    }

    else {

        // Your exit alert code, or alternatively line below to finish

        super.onBackPressed(); // finishes activity

    }

}


references:

https://stackoverflow.com/questions/16941930/pressing-back-button-exits-the-app-instead-of-navigating-backwards-in-the-webvie


Android practical challenges when adding product flavours

initially did not specify the flavorDimensions property and got the below error 


Error:All flavors must now belong to a named flavor dimension.

  The flavor 'flavor_name' is not assigned to a flavor dimension.


reading more here, 

https://developer.android.com/studio/build/build-variants


it appears that the product flavors support the same properties as defaultConfig—this is because defaultConfig actually belongs to the ProductFlavor class. This means you can provide the base configuration for all flavors in the defaultConfig block, and each flavor can change any of these default values, such as the applicationId.


After you create and configure your product flavors, click Sync Now in the notification bar. After the sync completes, Gradle automatically creates build variants based on your build types and product flavors,



After adding the below configuration to the build.gradle file, started getting the below errors 

No matching client found for package name 'com.kungfugrip.touchless.dev'


flavorDimensions "version"

    productFlavors {

        devBuild {

            applicationId 'com.kungfugrip.touchless'

            resValue "string", "override_name", "Touchless Dev"

            dimension 'version'

            applicationIdSuffix 'dev'

        }

        prodBuild {

            applicationId "com.kungfugrip.touchless"

            resValue "string", "override_name", "Touchless"

            dimension 'version'

        }

    }


And from the stack overflow link it appeared that this error is due to the application Id being not present in the google-services.json file. 


Now added a new application in firebase and gave the bundle ID as com.kungfugrip.touchlessdev. the google service json was replaced however, the app was not built still. it gave the same error message. 


This was not a major concern because the issue was the google-services.json had to be replaced under app root rather than project root!


references:

https://stackoverflow.com/questions/34990479/no-matching-client-found-for-package-name-google-analytics-multiple-productf

https://developer.android.com/studio/build/build-variants

Android multiple Build Flavors

In this article it explains pro and free version that has two different packages. 


Defining them is simple, you just have to write following in build.gradle.

To define app name for each flavor, you can write it in the following way


productFlavors {

      devVersion {

        applicationId "com.sample.android.devVersion"

resValue "string", "override_name", "Dev Version"

      }

      proVersion {

         applicationId "com.sample.android.proVersion"

resValue "string", "override_name", "Pro Version"

      }

}


And in manifest under application tag, you just need to mention string name. i.e.

android:label="@string/override_name"



references:

https://codetoart.com/blog/building-multiple-versions-of-an-android-app-product-flavors

MongoDB upsert vs drop

Based on the mongo doc, the reason --mode=upsert doesn't work in your case is by default, mongoimport uses the _id field. So --drop should be the correct answer.


--mode=upsert:


By default, mongoimport uses the _id field to match documents in the collection with documents in the import file. To specify the fields against which to match existing documents for the upsert and merge modes, use --upsertFields.


--drop:


Modifies the import process so that the target instance drops the collection before importing the data from the input.


references:

https://stackoverflow.com/questions/29775398/mongoimport-json-file-update-or-overwritte

Monday, April 19, 2021

What is React PWA?

PWA stands for a progressive web app, and it is the technology that brings web and mobile development to a new level. It is designed to bring the best user experience for the mobile users of web apps and platforms. The PWA technology allows the user to open a native-like app via a browser, to install it instantly, to make use of most native-like functions, and to use the app offline. The goal of a progressive web app developer is to make a website resemble an app installed on one’s smartphone, tablet, laptop, or PC.

The PWA technology offers six essential benefits:

A progressive web app loads faster than an ordinary website and is faster to install and start using than a mobile app. All static website assets are cached, so the page loads faster with each subsequent visit. 

Progressive web apps are much simpler to develop and use than other web or native solutions. For instance, since they can be installed from the browser, there is no need to submit them to the App Store or Google Play.

PWAs are universal — they are compatible with all devices on all operating systems if accessed through a standards-compliant browser.

If the network connection is unstable or absent, PWAs use cached data from previous sessions to ensure perfect and uninterrupted performance. The users will be able to access your app from basically anywhere.

Progressive web apps provide an excellent user experience due to their simplicity and speed, combined with all the necessary features of native solutions. Similarly to a native mobile app, a user can open the PWA by clicking the icon on the home screen. Moreover, unlike in native apps, updates are downloaded in the background.

While PWAs have no direct impact on SEO results, a properly developed PWA has the potential to decrease the bounce rate and to improve retention rates and the overall SEO performance of your web page.


Below are the steps for creating PWA

Step 1: Add a progressive web app manifest 


Let’s start with what a web app manifest is. It is a JSON file, which tells the browser about your PWA and its expected behavior when installed on the user’s desktop or mobile device. A web app manifest file should contain the name of the app, the icon to appear on the home screen, and the link that should be opened with the application launch. Such browsers as Google Chrome, Microsoft Edge, Firefox, Opera, and the Samsung browser support manifests, whereas Safari offers only partial support.

{

  "short_name": "KeenEthics",

  "name": "KeenEthics",

  "description": "Be Keen. Follow Ethics",

  "icons": [

    {

      "src": "/images/icons-192.png",

      "type": "image/png",

      "sizes": "192x192"

    },

    {

      "src": "/images/icons-512.png",

      "type": "image/png",

      "sizes": "512x512"

    }

  ],

  "start_url": "/?source=pwa",

  "background_color": "#12233d",

  "display": "standalone",

  "scope": "/",

  "theme_color": "#12233d",

}

After you have created the manifest, add it to your app. To do so, add a <link> tag to every page of your PWA. For instance:

<linkrel=”manifest” href=”/manifest.webmanifest” >


Step 2: Add service workers  

The service worker is a JavaScript file, which runs separately from the main browser thread, intercepts network requests, caches data, retrieves data from the cache, and delivers push messages. Service workers let PWAs control network requests, cache these requests to boost performance, and ensure access to the cached content offline. Also, they can get push messages from a server even if the app is not open, and thus, they can send push notifications to the user similarly to what a native app can do.

To ensure offline app performance, service workers depend on two APIs: Fetch and Cache. Fetch API is used to intercept network requests and modify the response, as well as to serve resources from the cache when the network connection is absent. Cache API is independent of the browser cache.


A few more technical nuances associated with service workers:


To avoid “man-in-the-middle” attacks, service workers run only over HTTPS. 

A service worker cannot access DOM directly, so it uses postMessage() to communicate with the page.

Service workers cannot use synchronous XHR and localStorage.


Step 3: Test your PWA


After you set up everything, it is time to check if your application adheres to the standards of PWA. There is an official tool for that provided by Google, called Lighthouse. 


The process of React progressive web app development consists of the following steps:


1) Adding a PWA manifest

2) Adding service workers, deciding on what should be cached and at which point

3) Testing your PWA with Lighthouse


references:

https://keenethics.com/blog/react-pwa-tutorial

Thursday, April 15, 2021

Javascript Useful code segments

 Inorder to change the elements of array in one line, it is something like below 


let sample = [30,40,50].map( (deg) => (Math.pi / 180) * deg)

this results in the array like this 

[0.5235987755982988, 0.5235987755982988, 0.6981317007977318]

Wednesday, April 14, 2021

How to write a Lets encrypt / Certbot

Write like below to file

cp -f <in_path>cert.pem <out_path>cert.pem

cp -f <in_path> fullchain.pem <out_path> fullchain.pem 

cp -f <in_path> privkey.pem <out_path> privkey.pem 


#for nginx merge the chain and cert to a single file.

cat cert.pem fullchain.pem >newcert.pem


This file needs execute permission, give the permission like below

sudo chmod +x post-renew.sh 



references:

Sunday, April 11, 2021

Adding Cron Job to AWS EC2 instance

Cron Jobs are nothing but Scheduled tasks in software environment which will be running at a specified frequency.

Examples:

Sending notifications to the users.

Sending registered users list to the specified email id..etc.

Writing Cron Jobs are different in Cloud Servers than writing in Shared hosting.

In Shared hosting, you have options to add Cron Jobs in Cron Job Manager. You can see this option in Cpanel from the Shared Hosting providers.

In Cloud servers, we have to work with CLI (Command Line Interface) to write Cron Jobs.

a. First, you have to Log in to your AWS EC2 instance

b. Run the below command

$ crontab -e

When you run Crontab command for the first time you will get some of the existed editors options to open

  /bin/ed

  /bin/nano

  /usr/bin/vim.basic

  /usr/bin/vim.tiny

Choose 1-4?

Select option 2 and enter.

Now you will get an editor to add Cron Jobs.

c. Add your every file paths/function paths which you want to schedule.

Note that you should specify single file path per line

For example:

0 10 * * * php  /var/www/public_html/api/src/cronjob/notification.php

OR

0 10 * * * /bin/php  /var/www/public_html/api/src/cronjob/notification.php


Here I am mentioning about PHP file path which sends notifications to the users on every day 10:00am.


First term is Cron expression i.e 0 10 * * *

Cron Expression Examples:


* * * * *      // Run every minute. ex: for 5 mins => */5 * * * *


0 * * * *      // Run on the hour, every hour ex: every 2hrs => * */2 * * *


0 23 * * *     // Run at 11 p.m. every day


0 0,12 * * 6   // Run at midnight and midday every Saturday


30 2 */2 * *   // Run every second day at 2.30 a.m.


5 stars are explained below:


1st star:      Minute (ranges from 0-59)


2nd star:     Hour  (ranges from 0-23)


3rd star:      Day (ranges from 1-31)


4th star:      Month(ranges from 1-12)


5th star:      Day-of-week (0-7. 0 & 7 is Sun. 1-Mon, 2-Tue…etc)


Second term is PHP command path. I.e php or /bin/php

Third term is PHP file Path i.e /var/www/public_html/api/src/cronjob/notification.php

Command path will change depends on the programming language.


d. Once you enter your Cron Job Commands you have to save it.


To save type Cntrl+x and Select ‘Y’ and Enter.


e. To check whether your Cron Jobs is saved or not, run the below command.


$crontab -l


Now you can see your Cron Job file which has all your Cron Jobs.


For testing, you can schedule a task for a minute and check.

 

references:

https://www.cumulations.com/blog/how-to-write-cron-jobs-on-amazon-web-servicesaws-ec2-server/#!