Sunday, 29 December 2024

LangChain interview Questions

 What is the difference between a Charactertextsplitter and a Recursivetextsplitter?


What are the default characters used by the RecursiveCharacterTextSplitter?


What is the purpose of the CharacterTextSplitter?


What is the purpose of the VectorstoreIndexCreator in Langchain?


What is the purpose of the RetrievalQAWithSourcesChain in Langchain?


What are the main benefits of using LangChain Document Loaders?


In the context of LangChain Document Loaders, what is the role of a loader?



Monday, 27 May 2024

Key Points about Correlation

 Correlation is a statistical measure that describes the extent to which two variables change together. It quantifies the degree to which the variables are related. When the values of one variable change systematically with the values of another variable, they are said to be correlated.

Key Points about Correlation

  1. Direction of Correlation:

    • Positive Correlation: Both variables move in the same direction. As one variable increases, the other also increases. Conversely, as one decreases, the other also decreases.
    • Negative Correlation: The variables move in opposite directions. As one variable increases, the other decreases, and vice versa.
    • No Correlation: There is no systematic relationship between the variables. Changes in one variable do not predict changes in the other.
  2. Strength of Correlation:

    • Perfect Correlation: When two variables move exactly together, they have a correlation of +1 (perfect positive correlation) or -1 (perfect negative correlation).
    • Strong Correlation: The variables have a correlation close to +1 or -1.
    • Weak Correlation: The correlation is close to 0.
    • Zero Correlation: There is no relationship between the variables (correlation is 0).
  3. Correlation Coefficient: The correlation coefficient (often denoted as rr) is a numerical value that ranges from -1 to +1 and quantifies the degree of correlation between two variables.

    • +1 indicates a perfect positive correlation.
    • -1 indicates a perfect negative correlation.
    • 0 indicates no correlation.

Types of Correlation Coefficients

  1. Pearson Correlation Coefficient: Measures the linear relationship between two continuous variables. It assumes that the data is normally distributed.

    r=(xixˉ)(yiyˉ)(xixˉ)2(yiyˉ)2r = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2 \sum (y_i - \bar{y})^2}}

    where xix_i and yiy_i are the individual sample points, and xˉ\bar{x} and yˉ\bar{y} are the means of the x and y variables, respectively.

  2. Spearman's Rank Correlation Coefficient: Measures the strength and direction of the association between two ranked variables. It does not assume a linear relationship or normally distributed data.

    rs=16di2n(n21)r_s = 1 - \frac{6 \sum d_i^2}{n(n^2 - 1)}

    where did_i is the difference between the ranks of corresponding values, and nn is the number of observations.

  3. Kendall's Tau: Measures the strength of association between two variables by considering the number of concordant and discordant pairs.

Example in Python Using Pearson Correlation

Here’s how you can calculate and visualize the Pearson correlation coefficient using Python's pandas and seaborn libraries:

import pandas as pd

import numpy as np

import seaborn as sns

import matplotlib.pyplot as plt


# Sample data

data = {

    'X': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],

    'Y': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

}

df = pd.DataFrame(data)


# Calculate Pearson correlation coefficient

correlation_matrix = df.corr()

pearson_corr = correlation_matrix.loc['X', 'Y']

print(f"Pearson Correlation Coefficient: {pearson_corr}")


# Visualize the correlation

sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')

plt.show()



Interpreting the Correlation

  • Value of rr:
    • r=1r = 1: Perfect positive correlation
    • 0<r<10 < r < 1: Positive correlation
    • r=0r = 0: No correlation
    • 1<r<0-1 < r < 0: Negative correlation
    • r=1r = -1: Perfect negative correlation

Understanding correlation is crucial for determining relationships between variables, which can help in predictive modeling, risk management, and decision-making processes. However, it's important to remember that correlation does not imply causation. Just because two variables are correlated does not mean that one causes the other to change.

Sunday, 10 March 2024

Error: No module named matplotlib.pyplot

While practising the first time we will get this error, without installing the matplotlib

Install using the following command:


pip install matplotlib


Example:

import numpy as np
import matplotlib.pyplot as plt

product_category = np.array(['Furniture', 'Technology', 'Office Supplies'])
sales = np.array ([4110451.90, 4744557.50, 3787492.52] )

plt.bar(product_category, sales)
plt.show()

Wednesday, 28 February 2024

Swapping 2 numbers doesn't involve making a new variable in python

Swapping

Description
You are given two integer variables,  x and y. You have to swap the values stored in x and y.

----------------------------------------------------------------------
Input:
Two numbers x and separated by a comma.

Output:
Print 5 lines. The first two lines will have values of variables shown before swapping, and the last two lines will have values of variables shown after swapping. The third line will be blank.


Ans:

#takes input in form of the string

in_string=12,15


#here extract the two numbers from the string

mylist = in_string.split(',')

x=int(mylist[0])

y=int(mylist[1])


#print x and y before swapping


print('x before swapping: {0}'.format(x))

print('y before swapping: {0}'.format(y))


#Writing your swapping code here

x = x + y 

y = x - y 

x = x - y 


print()

#print x and y after swapping

print('x after swapping: {0}'.format(x))

print('y after swapping: {0}'.format(y))



Output:

x before swapping: 12

y before swapping: 15


x after swapping: 15

y after swapping: 12


Thursday, 29 August 2019

Ext JS 7.0 Has Arrived

 Ext JS version 7.0 is finally over! The latest milestone update for our highly regarded JavaScript framework is now generally available, bringing major enhancements to the Modern Toolkit.

Modern Toolkit Enhancements in the Ext JS 7.0 release include:

  • Froala WYSIWYG HTML Edito​r- Froala, a light-weight WYSIWYG HTML Editor written in JavaScript, is now a part of Ext JS framework. Edit your application code using the smartest, feature-rich editing capabilities
  • Tree Drag and Drop- Easily move and reorder tree menus 
  • CheckBoxGroup Form Component- Group collection of checkbox buttons in a flexible format
  • RadioGroup Form Component- Customize option selection with radio buttons
  • Breadcrumb Toolbar- Present information in an easily navigable hierarchical format 
  • Accordion Panel- Support multiple expandable/collapsible panels
  • Accessibility improvements: Keyboard/Focus Management, Tab Indexing
  • Quality improvements throughout the Modern and Classic toolkits addressing over 70 customer reported issues.
  • And more!

Thursday, 15 August 2019

React v16.9.0 and the Roadmap Update

Renaming Unsafe Lifecycle Methods 

Over a year ago, we announced that unsafe lifecycle methods are getting renamed:
  • componentWillMount → UNSAFE_componentWillMount
  • componentWillReceiveProps → UNSAFE_componentWillReceiveProps
  • componentWillUpdate → UNSAFE_componentWillUpdate

Deprecating javascript: URLs


URLs starting with javascript: are a dangerous attack surface because it’s easy to accidentally include unsanitized output in a tag like <a href> and create a security hole

Deprecating “Factory” Components 

Before compiling JavaScript classes with Babel became popular, React had support for a “factory” component that returns an object with a render method:

New Features 


Async act() for Testing



Performance Measurements with <React.Profiler>




Reference: Reactjs Blog

Understanding the Spread Operator in JavaScript



Today we are going to discuss about the ES6 feature of Spread operator, Based on MDN docs.

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Syntax for how to use:

For function calls:

myFunction(...iterableObj);

For array literals or strings:

[...iterableObj, '4', 'five', 6];

For object literals (new in ECMAScript 2018):

let objClone = { ...obj };


Example of Replace of apply:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

concatenate arrays

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5]


Spread in object literals

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }

Tuesday, 2 July 2019

Ext JS TAGFIELD for modern Toolkit

Upto now Extjs 6 sencha is not providing Tagfield for modern toolkit.
This kind of component we can use many places in current mobile apps based on client requirements. So i implemented the tagfield using picker and working as expected.

Preview:



Code snippet:

Ext.define('Ext.field.TagField', {
    extend: 'Ext.field.Picker',
    xtype: 'tagfield',
    requires: [
        'Ext.picker.Picker'
    ],
    config: {
        store: null,
        displayField: 'text',
        valueField: 'id',
        picker: 'floated',
        floatedPicker: {
            xtype: 'list',
            selectable: 'multi'
        },
        selected: {}
    },

    onSelect(t, recs) {
        let i = 0,
            len = recs.length;
        if (!this._selected) {
            this._selected = {};
        }
        while (i < len) {

            this._selected[recs[i].get(this.getValueField())] = recs[i];
            this.addTag(recs[i]);
            i++;
        }
    },

    onDeselect(t, recs) {
        let i = 0,
            len = recs.length;
        while (i < len) {
            delete this._selected[recs[i].get(this.getValueField())];
            this.removeTag(recs[i]);
            i++;
        }

    },

    addTag(tag) {
        
        var dispFld = this.getDisplayField();
        var elId = this.id + '-tagId-' + tag.internalId;
        let el = document.createElement('span');
        el.id = elId;
        el.innerHTML = `${tag.get( dispFld )} <span style="margin-left: 2px; color: red;" class="x-fa fa-times-circle" aria-hidden="true">&nbsp;</span>`;
        el.style.padding = '4px';
        el.style.margin = '4px';
        el.style.cursor = 'default';
        el.style.backgroundColor = '#1E90FF';
        el.style.borderRadius = '3px';
        if (tag.tagCls) {
            el.classList.add(tag.tagCls);
        }

        el.setAttribute('tagFieldSpan', true);

        el.querySelector('span').addEventListener('click', function () {
            this.getPicker().onItemDeselect([tag]);
            this.getPicker().setItemSelection([tag], false);
        }.bind(this));

        this.beforeInputElement.append(el);
        this.beforeInputElement.setStyle({
            marginRight: '10px',
            flexWrap: 'wrap'
        });

        let storedValues = this.getValue();
        this.fireEvent('change', this, storedValues, this._selected);
        storedValues = null;
    },

    removeTag(tag) {
        
        let removed = tag.get(this.getValueField());

        let el = this.beforeInputElement.down(`#${this.id}-tagId-${tag.internalId}`);
        if (el) {
            el.destroy();
        }

        if (!this.expanded) {
            this.syncLabelPlaceholder(true);
        }

        let storedValues = this.getValue();
        this.fireEvent('change', this, storedValues, this._selected, removed);
        storedValues = null;
        removed = null;
    },
    createFloatedPicker() {
        
        const me = this;
        let result = Ext.merge({
            ownerCmp: me,
            store: me.getStore(),
            itemTpl: '{name}',
            listeners: {
                select: {
                    fn: me.onSelect,
                    scope: me
                },
                deselect: {
                    fn: me.onDeselect,
                    scope: me
                }
            }
        }, me.getFloatedPicker());
        return result;
    },

    getValue() {
        
        var keys = Object.keys(this._selected),
            i = 0,
            len = keys.length,
            values = [];

        while (i < len) {
            values.push(this._selected[keys[i]].get(this.getValueField()));
            i++;
        }

        return values;
    },

    setValue(v) {
        
        let selection = [];

        if (!(v instanceof Array)) {
            v = [v];
        }

        let i = 0,
            len = v.length,
            store = this.getPicker().getStore(),
            f, me = this;

        if (!store) {
            return false;
        }

        if (!store.isLoaded()) {
            store.addListener('load', () => {
                me.setValue(v);
            });
            return false;
        }

        while (i < len) {
            f = store.getAt(store.findExact(this.getValueField(), v[i]));
            if (f) {
                selection.push(f);
            }
            i++;
        }

        if (selection.length) {
            this.getPicker().select(selection);
        }

        if (!this.expanded) {
            this.syncLabelPlaceholder(true);
        }
    },

    privates: {
        syncLabelPlaceholder: function (val) {
            let inside;
            this._animPlaceholderLabel = val;
            if (this.rendered) {
                if (Object.keys(this._selected).length > 0) {
                    inside = false;
                } else {
                    inside = !this.hasFocus || this.getDisabled() || this.getReadOnly();
                }
                this.setLabelInPlaceholder(inside);
            }

            this._animPlaceholderLabel = false;
        },
    },

    isInputField: false,
    isSelectField: true
});

Ext.application({
    name: 'Fiddle',
    launch: function () {

        Ext.define('Fiddle.view.MyPanel', {
            extend: 'Ext.panel.Panel',
            alias: 'TestPanelDataBinding',
            viewModel: {
                data: {
                    fName: 'HariKrishna Bura'
                }
            },
            width: 400,
            height: 300,
            title: 'Form data',
            items: [{
                xtype: 'textfield',
                bind: '{fName}',
                width: 300,
                label: 'Name'
            }, {
                xtype: 'tagfield',
                multiSelect: true,
                displayField: 'name',
                valueField: 'id',
                label: 'tag Field',
                store: Ext.create('Ext.data.Store', {
                    data: [{
                        id: 1,
                        name: 'Hyderabad'
                    }, {
                        id: 2,
                        name: 'Bengaluru'
                    }, {
                        id: 3,
                        name: 'Chennai'
                    }]
                })
            }]

        });
        /*
        tag or checkbox
        */
        var pnl = Ext.create('Fiddle.view.MyPanel', {
            fullscreen: true
        });
    }

});
 

You can access my fiddler for reference:

https://fiddle.sencha.com/#view/editor&fiddle/2sdu




Tuesday, 30 April 2019

State of Sencha Address - Webinar

You’re invited to join Sencha leadership for a webinar on Thursday, May 2nd at 8:30am PDT/11:30am EDT/4:30pm BST where we will discuss the state-of-the-state of all things Sencha planned for 2019, including but not limited to: 

  • Sencha Roadmap overview, including new and upcoming product releases
  • Growth initiatives to reignite the momentum of Ext JS
  • Preview of Ext JS 7.0
  • And more!
You will also have the opportunity to meet our new General Manager of Sencha, Kegan Blumenthal and we'll host a Q&A session at the end. 

We hope you’ll join us and look forward to your participation. 

Event Details: 
Date: Thursday, May 2, 2019
Time: 8:30am PDT/11:30am EDT/4:30pm BST
Duration: 60 Minutes