Saturday, November 12, 2022

How do we kill the processes in linux/unix with a process name?

Below is the command to kill all the processes running based on a process name: ps -ef | grep {process_name} | grep -v grep | awk '{print $2}' | xargs kill


Eg: Kill all the processes that have chrome as part of the process name: ps -ef | grep chrome | grep -v grep | awk '{print $2}' | xargs kill

Monday, March 9, 2020

Calculate Network Subnet Range efficiently!

import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

import static com.varra.auth.utils.CommonUtils.ipStringToLong;
import static java.lang.Integer.parseInt;
import static java.lang.Math.pow;
import static java.util.stream.Collectors.toList;

/**
* TODO Description go here.
*
* @author Rajakrishna V. Reddy
* @version 1.0
*/
public class SubnetCalculator {

private static final Pattern CIDR_PATTERN = Pattern.compile("/");

@Accessors(chain = true, fluent = true)
@Data
@Builder(access = AccessLevel.PRIVATE)
public static class Subnet {
private final int cidr;
private final int ipCount;
private final int startIp;
private final int endIp;

public static Subnet of(final String ipWithCIDR)
{
final String[] ipWithCIDRTokens = CIDR_PATTERN.split(ipWithCIDR);
final int numericCIDR = parseInt(ipWithCIDRTokens[1]);
final int netmaskNumeric = 0xffffffff << (32 - numericCIDR);
final int numberOfIPs = (int) pow(2, 32 - numericCIDR) - 1;
final int baseIP = (int)ipStringToLong(ipWithCIDRTokens[0]) & netmaskNumeric;
return Subnet.builder().cidr(numericCIDR).ipCount(numberOfIPs).startIp(baseIP).endIp(baseIP + numberOfIPs -1).build();
}
}

/**
* Specify IP in CIDR format like: new IPv4("10.1.0.25/16");
*
* @param ipWithCIDR ""
*/
public static List<String> getAvailableIps(final String ipWithCIDR) throws NumberFormatException {
return getAvailableIpsAsIntegers(ipWithCIDR).mapToObj(CommonUtils::ipLongToString).collect(toList());
}

/**
* Specify IP in CIDR format like: new IPv4("10.1.0.25/16");
*
* @param ipWithCIDR ""
* @return IntStream Stream of ips as integers
*/
public static IntStream getAvailableIpsAsIntegers(final String ipWithCIDR) throws NumberFormatException {
final Subnet subnet = Subnet.of(ipWithCIDR);
return IntStream.range(1, subnet.ipCount()).map(i -> i + subnet.startIp());
}

public static boolean isIpWithInSubnet(final String ipWithCIDR, final String ip) throws NumberFormatException {
final Subnet subnet = Subnet.of(ipWithCIDR);
final int ipAsInt = (int) ipStringToLong(ip);
return subnet.startIp() <= ipAsInt && ipAsInt <= subnet.endIp();
}
}

Friday, February 7, 2020

Problem with github: permission denied to your own repo In Windows!! ??

Using multiple GitHub Accounts on Windows sucks by default. If you are tired of Window's Credential Manager storing only one account's credential for git:https://github.com then here is a 1-minute fix for you.

TL;DR

If you know what you're doing just:

  • delete your GitHub credentials from Windows Credential Manager
  • run git config --global credential.github.com.useHttpPath true
  • continue coding

If you need more detailed instructions and learn about the background just read on here: https://dev.to/configcat/lazy-man-s-guide-multiple-github-https-accounts-on-windows-2mad



Thursday, December 5, 2019

Problem with github: permission denied to your own repo?

 I had this problem too but managed to solve it, the error is that ur computer has saved a git username and password so if you shift to another account the error 403 will appear. Below is the solution

For Windows you can find the keys here:

control panel > user accounts > credential manager > Windows credentials > Generic credentials

Next -> remove the Github keys.

Monday, August 12, 2019

How to replace all the entries in a string in Javascript? like replaceAll?

This should do the trick by adding a new method (replaceAll) to the String prototype.

String.prototype.replaceAll = function(search, replacement){
            return this.replace(new RegExp(search, 'g'), replacement);
        };

Tuesday, August 7, 2018

How to increase the number of processes in Oracle DB

The solution to this question is to increase the number of processes :

  1. Open command prompt
  2. sqlplus / as sysdba
  3. startup force;
  4. show parameter processes; -- This shows 150 processes allocated, i will increase the count to 800 now
  5. alter system set processes=800 scope=spfile;

Tried and tested.


Monday, July 2, 2018

How to setup a beyond compare as git mergetool?

How to set up a beyond compare as git mergetool?

git config --global diff.tool bc3
git config --global difftool.bc3.path "c:/program files/beyond compare 4/bcomp.exe"
git config --global merge.tool bc3
git config --global mergetool.bc3.path "c:/program files/beyond compare 4/bcomp.exe"



If the above instructions aren't working on your system, it's possible repository local settings are overriding the global settings.
The contents of the global git config file (c:\users\username\.gitconfig) from my working test system:

[diff]
        tool = bc3
[difftool "bc3"]
        path = c:/program files/beyond compare 4/bcomp.exe
[merge]
        tool = bc3
[mergetool "bc3"]
        path = c:/program files/beyond compare 4/bcomp.exe


Monday, May 28, 2018

How to merge a branch in git

Follow the commands below to do the auto merge the branch in git:

$ git checkout -b {new-branch-name}
$ git merge --no-ff {old-branch-name}
$ git push -u origin {new-branch-name}

Friday, May 25, 2018

Concatenating and combining lists in Python

CODE:
[4, None, 'foo'] + [7, 8, (2, 3)]

or

x = [4, None, 'foo']
x.extend([7, 8, (2, 3)])
print(x)


OUTPUT:
[4, None, 'foo', 7, 8, (2, 3)]



Ternary expressions in Python

A ternary expression in Python allows you to combine an if-else block that produces
a value into a single line or expression. The syntax for this in Python is:

value = true-expr if condition else false-expr

Here, true-expr and false-expr can be any Python expressions. It has the identical
effect as the more verbose:

if condition:
    value = true-expr
else:
    value = false-expr


This is a more concrete example:

CODE:
x = 5
'Non-negative' if x >= 0 else 'Negative'

OUTPUT:
'Non-negative'

What is pass in Python

pass is the "no-op" statement in Python. It can be used in blocks where no action is to
be taken (or as a placeholder for code not yet implemented); it is only required
because Python uses whitespace to delimit blocks:

Eg:

if x < 0:
    print('negative!')
elif x == 0:
    # TODO: put something smart here
    pass
else:
    print('positive!')

How to chain comparisons in Python

CODE:
print(4 > 3 > 2 > 1)


OUTPUT:
True


What are the datetime format specifications (ISO C89 compatible) in Python

Below are the Datetime format specification (ISO C89 compatible) in Python:




Why triple quotes (" " ") are used in Python

For multiline strings with line breaks, you can use triple quotes, either ''' or " " ":

c = """
This is a long string that
spans multiple lines
"""

Standard Python scalar types

Below are the standard Python scalar types:

Type: Description
None: The Python "null" value (only one instance of the None object exists)
str: String type; holds Unicode (UTF-8 encoded) strings
bytes: Raw ASCII bytes (or Unicode encoded as bytes)
float: Double-precision (64-bit) floating-point number (note there is no separate double type)
bool: A True or False value
int: Arbitrary precision signed integer





How to check/get/set an attribute or a method in Python (Reflection)

Python allows an easy way to check whether an object contains/has an attribute or method with the specified name as follows:

1) getattr:
Gets the attribute/method with the specified name, usage as follows:
usage: getattr(obj, 'method/attribute name')
eg: 
a='RK'; 
getattr(a, 'split')


2) hasattr:
Checks whether object has the attribute/method with the specified name, usage as follows:

usage: hasattr(obj, 'method/attribute name')
eg: 
a='RK'; 
hasattr(a, 'split')


3) setattr:
Sets the attribute/method with the specified name, usage as follows:
usage: setattr(obj, 'method/attribute name', value)
eg: 
a=Employee(23)
setattr(a, 'id', 45)


Python assignments are by references

When assigning a variable (or name) in Python, you are creating a reference, have a look at below:

CODE:
a=[1,2]
b=a
print("Before append: ", b)
b.append(3)
print("Shows a & b are same references, after append to b, a: ", a)



OUTPUT:

Before append:  [1, 2]
Shows a & b are same references, after append to b, a:  [1, 2, 3]

How to get rid of `grep: warning: GREP_OPTIONS is deprecated; please use an alias or script`?

Need to have an alias for grep to make the output colored as follows and unset the GREP_OPTIONS.


alias grep="grep --color=auto"
unset GREP_OPTIONS



Monday, May 21, 2018

How to create a self signed certificate, and how to validate the JWT token using Nimbus

This post will help you to generate a self-signed certificate and show you how to validate the JWT token using Nimbus Jose JWT library.


package com.varra.samples;

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;

import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import sun.security.rsa.RSAPublicKeyImpl;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;

public class JWTTokenUtils {


/** 
* Create a self-signed X.509 Certificate
* @param dn the X.509 Distinguished Name, eg "CN=RK, L=Hyderabad, C=Hyderabad"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/ 
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
  throws GeneralSecurityException, IOException
{
  PrivateKey privkey = pair.getPrivate();
  X509CertInfo info = new X509CertInfo();
  Date from = new Date();
  Date to = new Date(from.getTime() + days * 86400000l);
  CertificateValidity interval = new CertificateValidity(from, to);
  BigInteger sn = new BigInteger(64, new SecureRandom());
  X500Name owner = new X500Name(dn);
 
  info.set(X509CertInfo.VALIDITY, interval);
  info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
  //info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
  info.set(X509CertInfo.SUBJECT, owner);
  info.set(X509CertInfo.ISSUER, owner);
  info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
  info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
  AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
  info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
 
  // Sign the cert to identify the algorithm that's used.
  X509CertImpl cert = new X509CertImpl(info);
  cert.sign(privkey, algorithm);
 
  // Update the algorith, and resign.
  algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
  info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
  cert = new X509CertImpl(info);
  cert.sign(privkey, algorithm);
  return cert;
}
public static String generateToken(RSAPrivateKey privateKey) throws Exception
{
// Create RSA-signer with the private key
final JWSSigner signer = new RSASSASigner(privateKey);
// Prepare JWT with claims set
final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
    .subject("alice")
    .issuer("Rajakrishna Reddy")
    .claim("user", "Rajakrishna Reddy")
    .claim("email", "abc@xyz.com")
    .claim("tenantId", "123")
    .expirationTime(new Date(new Date().getTime() + 60 * 1000))
    .build();
final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
public static boolean isValidToken(String token, RSAPublicKey publicKey) throws Exception
{
return SignedJWT.parse(token).verify(new RSASSAVerifier(publicKey));
}
public static boolean isValidToken(String token, String publicKey) throws Exception
{
byte[] decoded = Base64.getDecoder().decode(publicKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey generatePublic = (RSAPublicKey) kf.generatePublic(spec);
    BigInteger modulus = generatePublic.getModulus();
    BigInteger exponent = generatePublic.getPublicExponent();
    return SignedJWT.parse(token).verify(new RSASSAVerifier(new RSAPublicKeyImpl(modulus, exponent)));
//return SignedJWT.parse(token).verify(new RSASSAVerifier(publicKey));
}
public static void main(String[] args) throws Exception {
final String algorithmType = "RSA";
final String algorithm = "SHA256withRSA";
final String dn = "CN=Rajakrishna Reddy, OU=OU, O=varra, L=Hyderabad, ST=TL, C=IN";
final int days = 365;
final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algorithmType);
keyGenerator.initialize(2048);
final KeyPair kp = keyGenerator.genKeyPair();
final X509Certificate certificate = generateCertificate(dn, kp, days, algorithm);
System.out.println("X09.Certificate: "+certificate);
//final String token = generateToken((RSAPrivateKey) kp.getPrivate());
final String token = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE1MjUyNDUyMDAsInN1YiI6IkpXVCIsInVzZXJfbWV0YWRhdGEiOiJ7XCJVc2VybmFtZVwiOlwibWNzYVwifSIsImlhdCI6MTUyNTE1ODgwMH0.wbroKZfrdGPGnk3OaPWbRr56rRzkg4DFO999jmSsut8IYAthKU0f26CIjWfrNPXD5asV74JYIS49VFNkFwbWfnIFETY1CaLIIm6F6NP5cFE7LW5G-y0qNRaCJgOLaFV4z4lsQOi0KAfuFVckiL5EHxhyBks-MCQEXMWO2JIBBZjAxhIH7fmhMHsYQQUxvm8Tx1dpnbvyh9E6x5F9BNZeS2DcBCqvzCuSUAz2DbgsJ-gVyrDRJgcItiCnscZy2u3sZq3XBTK2qBiSIpS4zVZupVS0f-5v57y7BvdVX2siuu-StN5614zvON_MJRgNLdo1yA1Y5F8eJ9IZrelMWB5GZw";
final String publiKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2hg1nqteEY12r5AO/enYD14aXEUaoqgvhtcHDwEPQwf9KqGpwoeC8jQE1qHfb2K1Wm/o4ug60Kv02f7AEJiNrUuKe9MYJdTr/DhekVrE0ttJkGCjLoNiVgMZHKH557Ouf6RsWJc5QjUiqxg6azwYUuHu2U199MZzFXvAVVUQR+hh8YqQM4KIQytOpj1JhxH7hQehth9vF5kIhA+K8htIIO04UF9+8ScrBHMQgj9q0RLperVQLxGsYT8cEZIn9tv1r47jynrTS0z/Vq2uVMGRg/bRPuo598++XUIglM92Ehbih87j//ATcHtsabefzBAVQuN4OaqLTT375JRAWpoWmQIDAQAB";
System.out.println("Token: "+token);
//System.out.println("Is valid?: "+isValidToken(token, (RSAPublicKey) kp.getPublic()));
System.out.println("Is valid?: "+isValidToken(token, publiKey));
//System.out.println(isValidToken(token, CertificateUtil.parseRSAPublicKey()));
}
}

Monday, December 18, 2017

How to remove untracked/ignored files and directories from git local repository


There is always be a need to remove the unwanted files and directories from the git to clean the git local repo, but sometimes it's a tedious job to do if we are not aware of some simple cool features that are offered by git, such as git clean, there is a wonderful and informative article available in git docs.

Here I wanted to give you some useful commands that do the required job of cleaning the untracked or ignored files and directories from the git repo.

This is written according to the git documentation provided here. This should not be considered as a complete guide to git clean.


  • Run this command to see what are the files or dirs going be removed: git clean -n  or   git clean --dry-run 

    So it doesn't actually remove anything, just show what would be done.
  • Run this command to delete the files or directories actually: git cleanBeware that it removes the files and directories permanently!!

    If you want to remove directories, run git clean -f -d or git clean -fd
    If you want to remove ignored files, run git clean -f -X or git clean -fX
    If you want to remove ignored and non-ignored files, run git clean -f -x or git clean -fx

  
It is always advisable to have a glance at the complete documentation at git! Have a look at git clean documentation for a clear understanding.