code-rag-bench/online-tutorials huggingface dataset:
PyQt5 – Find if Radio Button is checked

22 Apr, 2020
In this article we will see if how we can find if the radio button is checked. By default the radio button is unchecked but with the help of setChecked method we can set it to checked.
In order check if the radio button is checked or not we will do the following :
1. Create a push button2. Create a label to tell if radio button is checked or not.3. Connect a method to it such that if its state gets changed method should be called.4. In method check if radio button is checked or not with the help of isChecked method.5. Change the text of label according to the state.
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a radio button        self.radio_button = QRadioButton(self)          # setting geometry of radio button        self.radio_button.setGeometry(200, 150, 120, 40)          # setting text to radio button        self.radio_button.setText("GEEK ?")          # creating label to display if it is checked or not        self.label = QLabel("", self)          # setting geometry of label        self.label.setGeometry(200, 200, 150, 40)          # setting callable method to radio button        self.radio_button.clicked.connect(self.check)      # method called by radio button    def check(self):                  # checking if it is checked        if self.radio_button.isChecked():                          # changing text of label            self.label.setText("It is now checked")          # if it is not checked        else:                          # changing text of label            self.label.setText("")      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
numpy.cumprod() in Python

28 Nov, 2018
numpy.cumprod() function is used when we want to compute the cumulative product of array elements over a given axis.
Syntax : numpy.cumprod(arr, axis=None, dtype=None, out=None)
Parameters :arr : [array_like] Array containing numbers whose cumulative product is desired. If arr is not an array, a conversion is attempted.axis : Axis along which the cumulative product is computed. The default is to compute the product of the flattened array.dtype : Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of arr, unless arr has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.
Return : A new array holding the result is returned unless out is specified, in which case it is returned.
Code #1 : Working
# Python program explaining# numpy.cumprod() function  import numpy as geek  in_num = 10  print ("Input  number : ", in_num)    out_prod = geek.cumprod(in_num) print ("cumulative product of input number : ", out_prod) 
Output :
Input  number :  10
cumulative product of input number :  [10]

 Code #2 :
# Python program explaining# numpy.cumprod() function  import numpy as geek  in_arr = geek.array([[2, 4, 6], [1, 3, 5]])   print ("Input array : ", in_arr)     out_prod = geek.cumprod(in_arr) print ("cumulative product of array elements: ", out_prod) 
Output :
Input array :  [[2 4 6]
 [1 3 5]]
cumulative product of array elements:  [  2   8  48  48 144 720]

 Code #3 :
# Python program explaining# numpy.cumprod() function  import numpy as geek  in_arr = geek.array([[2, 4, 6], [1, 3, 5]])   print ("Input array : ", in_arr)     out_prod = geek.cumprod(in_arr, axis = 1) print ("cumulative product of array elements taking axis 1: ", out_prod) 
Output :
Input array :  [[2 4 6]
 [1 3 5]]
cumulative product of array elements taking axis 1:  [[ 2  8 48]
 [ 1  3 15]]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Python | Row lengths in Matrix

30 Dec, 2020
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using max() + map() + sum() + list comprehension
The combination of above functions can help to get the solution to this particular problem in just a one line and hence quite useful. The sum function computes the sum of sublists, max function can be used to order in descending and all this bound together using list comprehension.
# Python3 code to demonstrate# Row lengths in matrix# using max() + map() + sum() + list comprehension  # initializing listtest_list = [[4, 5, 6], [7, 8], [2]]  # printing original listprint("The original list : " + str(test_list))  # using max() + map() + sum() + list comprehension# Row lengths in matrixres = [sum(len(row) > idx for row in test_list)    for idx in range(max(map(len, test_list)))]  # print resultprint("The row lengths in matrix : " + str(res))
The original list : [[4, 5, 6], [7, 8], [2]]
The row lengths in matrix : [3, 2, 1]

 
Method #2 : Using sum() + filter() + zip_longest()
This problem can also be solved using the set of functions above. The filter function can be used to get the separate lists and the task of binding for summation done by sum function is performed by zip_longest function.
# Python3 code to demonstrate# Row lengths in matrix# using sum() + filter() + zip_longest()from itertools import zip_longest  # initializing listtest_list = [[4, 5, 6], [7, 8], [2]]  # printing original listprint("The original list : " + str(test_list))  # using sum() + filter() + zip_longest()# Row lengths in matrixres = [sum(1 for idx in filter(None.__ne__, i))              for i in zip_longest(*test_list)]  # print resultprint("The row lengths in matrix : " + str(res))
The original list : [[4, 5, 6], [7, 8], [2]]
The row lengths in matrix : [3, 2, 1]

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find Eigenvalues and Eigenvectors of a Matrix in R Programming – eigen() Function

19 Jun, 2020
eigen() function in R Language is used to calculate eigenvalues and eigenvectors of a matrix. Eigenvalue is the factor by which a eigenvector is scaled.
Syntax: eigen(x)
Parameters:x: Matrix
Example 1:
# R program to illustrate # Eigenvalues and eigenvectors of matrix     # Create a 3x3 matrix A = matrix(c(1:9), 3, 3)   cat("The 3x3 matrix:\n") print(A)     # Calculating Eigenvalues and eigenvectors print(eigen(A)) 
Output:
The 3x3 matrix:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
eigen() decomposition
$values
[1]  1.611684e+01 -1.116844e+00 -5.700691e-16

$vectors
           [, 1]       [, 2]       [, 3]
[1, ] -0.4645473 -0.8829060  0.4082483
[2, ] -0.5707955 -0.2395204 -0.8164966
[3, ] -0.6770438  0.4038651  0.4082483

Example 2:
# R program to illustrate # Eigenvalues and eigenvectors of matrix     # Create a 3x3 matrix A = matrix(c(2, 3, 5, 1), 2, 2) A     # Calculating Eigenvalues and eigenvectors print(eigen(A)) 
Output:
     [, 1] [, 2]
[1, ]    2    5
[2, ]    3    1
eigen() decomposition
$values
[1]  5.405125 -2.405125

$vectors
          [, 1]       [, 2]
[1, ] 0.8265324 -0.7503320
[2, ] 0.5628892  0.6610612

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Global memory management in C++ : Stack or Heap?

Stack and heap are used to store variables during the execution of the program and it also get destroyed.
Global data structures or global variables are not consumed by stack or heap. They basically allocated in a fixed memory block, which remains unchanged.
int a[10]; // located in a fixed memory block
int main() {
   int main() {
      float *ptr = (int *)malloc(sizeof(float)10.0)); //use heap.
   }
}
Push query results into variable with MongoDB?

For this, you can use aggregate(). Let us create a collection with documents −
> db.demo142.insertOne({"Value":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9c6fdf09dd6d08539b2")
}
> db.demo142.insertOne({"Value":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9cafdf09dd6d08539b3")
}
> db.demo142.insertOne({"Value":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9cdfdf09dd6d08539b4")
}
> db.demo142.insertOne({"Value":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9d0fdf09dd6d08539b5")
}
> db.demo142.insertOne({"Value":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9d9fdf09dd6d08539b6")
}
Display all documents from a collection with the help of find() method −
> db.demo142.find();
This will produce the following output −
{ "_id" : ObjectId("5e32e9c6fdf09dd6d08539b2"), "Value" : 50 }
{ "_id" : ObjectId("5e32e9cafdf09dd6d08539b3"), "Value" : 45 }
{ "_id" : ObjectId("5e32e9cdfdf09dd6d08539b4"), "Value" : 60 }
{ "_id" : ObjectId("5e32e9d0fdf09dd6d08539b5"), "Value" : 55 }
{ "_id" : ObjectId("5e32e9d9fdf09dd6d08539b6"), "Value" : 50 }
Following is the query to push query results into variable −
> var query = db.demo142.aggregate( 
...    { "$group": { "_id": null, "MaxValue": { "$max": "$Value" } } }
... ]);
> var largestValue= query.toArray()[0]["MaxValue"];
> printjson(largestValue);
This will produce the following output −
60
C# Program to Check status of Current Thread

To check the status of the current thread in C#, use the IsAlive property.
Firstly, use the currentThread property to display information about a thread −
Thread thread = Thread.CurrentThread;
Now use the thread.IsAlive property to check the status of the thread −
thread.IsAlive
Let us see the complete code to check the status of current thread in C#.
Live Demo
using System;
using System.Threading;
namespace Demo {
   class MyClass {
      static void Main(string[] args) {
         Thread thread = Thread.CurrentThread;
         thread.Name = "My New Thread";
         Console.WriteLine("Thread Status = {0}", thread.IsAlive);
         Console.ReadKey();
      }
   }
}
Thread Status = True
Python Pandas – Check if two Dataframes are exactly same

The equals() function is used to check if two dataframes are exactly same. At first, let us create DataFrame1 with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)
Create DataFrame2 with two columns −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)
To check for equality, use the equals() method −
dataFrame1.equals(dataFrame2)

Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print"\nDataFrame2 ...\n",dataFrame2

# check for equality
print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2)


This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

DataFrame2 ...
        Car   Reg_Price
0       BMW        7000
1     Lexus        1500
2      Audi        5000
3   Mustang        8000
4  Mercedes        9000 
5    Jaguar        6000

Are both the DataFrames equal? False
What do you mean by Scenario Outline in Cucumber?

We use the Scenario Outline keyword in the feature file in Cucumber. If a
particular scenario needs to be executed with more than a set of data in multiple
combinations, then we use the Scenario Outline.
The multiple data sets are represented in form of a table separated by (||) symbol
under Examples keyword. Each row represents a group of data.
Feature file.
Feature: Login Verification Feature
Scenario Outline: Login Verification
Given User lands on the home page
When Page title is Tutorialspoint
Then User keys in "<username>" and "<password>"
Examples:
| username | password |
| Selenium | t123     |
| Python   |pt123     |
Step Definition file with Then statement having parametrization.
@Then (“^User keys in \"(.*)\” and \"(.*)\”$”)
public void user_keys(String username, String password){
   System.out.println("The username and password is : " + username
   +””+ password);
}
Arithmetic Mean in C programming

Arithmetic mean is the sum of a collection of numbers divided by the number of numbers in the collection.
The mean of n numbers x1, x2, . . ., xn is x. If each observation is increased by p, the mean of the new observations is (x + p).
The mean of n numbers x1, x2, . . ., xn is x. If each observation is increased by p, the mean of the new observations is (x + p).
The mean of n numbers x1, x2, . . ., xn is x. If each observation is decreased by p, the mean of the new observations is (x - p).
The mean of n numbers x1, x2, . . ., xn is x. If each observation is decreased by p, the mean of the new observations is (x - p).
The mean of n numbers x1, x2, . . ., xn is x. If each observation is multiplied by a nonzero number p, the mean of the new observations is px.
The mean of n numbers x1, x2, . . ., xn is x. If each observation is multiplied by a nonzero number p, the mean of the new observations is px.
The mean of n numbers x1, x2, . . ., xn is x. If each observation is divided by a nonzero number p, the mean of the new observations is (x/p).
The mean of n numbers x1, x2, . . ., xn is x. If each observation is divided by a nonzero number p, the mean of the new observations is (x/p).
Type 1: Direct mean
Given the array and number of elements
Input - 1,2,3,4,5,6,7,8,9
Output - 5
Explanation - To calculate the arithmetic mean of all numbers, first perform addition of all the numbers, then make a variable responsible for the arithmetic mean and place addition/size in a variable say armean.
#include<iostream>
using namespace std;
int main(){
   int n, i, sum=0;
   int arr[]={1,2,3,4,5,6,7,8,9};
   n=9;
   for(i=0; i<n; i++) {
      sum=sum+arr[i];
   }
   int armean=sum/n;
   cout<<"Arithmetic Mean = "<<armean;
}
Type 2: Range and no of elements present I range is given.
Given three integers X, Y and N. Logic to find N Arithmetic means between X and Y.
N terms in an Arithmetic progression (no. of terms between X and Y)
X= first and
Y= last terms.
Input  - X = 22 Y = 34 N = 5
Output - 24 26 28 30 32
The Arithmetic progression series is
22 24 26 28 30 32 34
Explanation
Let X1, X2, X3, X4......Xn be N Arithmetic Means between two given numbers X and Y.
Then X, X1, X2, X3, X4......Xn, Y will be in Arithmetic Progression. Now Y = (N+2)th term of the Arithmetic progression.
Finding the (N+2)th term of the Arithmetic progression Series, where d is the Common Difference
Y = X + (N + 2 - 1)d
Y - X = (N + 1)d
So the Common Difference d is given by.
d = (Y - X) / (N + 1)
We have the value of A and the value of the common difference(d), now we can find all the N Arithmetic Means between X and Y.
#include<stdio.h>
int main() {
   int X = 22, Y = 34, N = 5;
   float d = (float)(Y - X) / (N + 1);
   for (int i = 1; i <= N; i++) {
      printf("%3f ", (X + i * d));
   }
   return 0;
}
24.000000 26.000000 28.000000 30.000000 32.000000
How to plot with xgboost.XGBCClassifier.feature_importances_ model? (Matplotlib)

To change the size of a plot in xgboost.plot_importance, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Load the data from a csv file.
Get x and y data from the loaded dataset.
Get the xgboost.XGBCClassifier.feature_importances_ model instance.
Fit x and y data into the model.
Print the model.
Make a bar plot.
To display the figure, use show() method.
from numpy import loadtxt
from xgboost import XGBClassifier
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# data.csv contains data like -> 13, 145, 82, 19, 110, 22.2, 0.245, 57, 0
dataset = loadtxt('data.csv', delimiter=",")
X = dataset[:, 0:8]
y = dataset[:, 8]

model = XGBClassifier()
model.fit(X, y)

print(model.feature_importances_)

plt.bar(range(len(model.feature_importances_)), model.feature_importances_)

plt.show()
[13:46:53] WARNING: ../src/learner.cc:1095: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
[0.10621197 0.2424023 0.08803366 0.07818192 0.10381887 0.1486732
0.10059207 0.13208601]
How to delete an installed module in Python?

You can uninstall most installed Python packages using pip. For more info on pip uninstall, head over to: https://pip.pypa.io/en/stable/reference/pip_uninstall/. For example, if you have numpy package installed and want to uninstall it, then enter the following:
$ pip uninstall numpy
However there are some exceptions. These packages cant be removed easily using pip:
1. Pure distutils packages installed with python setup.py install, which leave behind no metadata to determine what files were installed.
2. Script wrappers installed by python setup.py develop.
You need to remove all files manually, and also undo any other stuff that installation did manually.
If you don't know the list of all files, you can reinstall it with the --record option, and take a look at the list this produces. To record list of installed files, you can use:
$ python setup.py install --record files.txt
Now you'll have a list of all files in the files.txt, which you can then manually remove.
How to remove text from a string in JavaScript?

You can remove text from a string in Javascript using 2 methods,
substring and replace.
JS string class provides a substring method that can be used to extract a substring from a given string. This can be used to remove text from either or both ends of the string.
str.substr(start[, length])
let a = 'Hello world'
console.log(a.substr(0, 5))
console.log(a.substr(6))
console.log(a.substr(4, 3))
This will give the output −
Hello
world
o w
JS string class provides a replace method that can be used to replace a substring from a given string with an empty string. This can be used to remove text from either or both ends of the string.
str.replace(old, new)
let a = 'Hello world'
console.log(a.replace(" world", ""))
console.log(a.replace("Hello ", ""))
console.log(a.replace("o w", ""))
This will give the output −
Hello
world
hellorld
How to execute a Javascript function in Python with Selenium?

We can execute a JavaScript function in Python with Selenium webdriver. DOM interacts with the elements via JavaScript. Selenium is capable of executing JavaScript commands with the execute_script method.
Few actions like web scrolling cannot be done by Selenium directly. For this, we shall use the JavaScript Executor. We shall take the help of the JavaScript command window.scrollTo and pass it to the execute_script method. To scroll to the bottom of the page, we have to pass 0 and document.body.scrollHeight as parameters to the window.scrollTo.
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
#scroll till page bottom
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);)
We can also do web action like click on a link with JavaScript. Here, also we shall utilize the execute_script method and pass arguments with index and element as parameters to that method.
e = driver.find_element_by_css_selector(".cls")
driver.execute_script("arguments[0].click();",e)
Let us click the link Library on the page.
from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver.implicitly_wait(0.8)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element
l = driver.find_element_by_xpath("//*[text()='Library']")
#click with execute_script
driver.execute_script("arguments[0].click();",l)
print("Page title after click: " + driver.title)
How to do multiple imports in Python?

To import multiple modules, just use the import statement multiple times. For example,
>>> import os
>>> import math
>>> import sys
Sometimes grouping imports make more sense. To import multiple modules with a single import statement, just separate the module names by commas. For example,
>>> import math, sys, os
If you want to change the name under which the modules are imported, just add as after each module name followed by module alias. For example,
>>> import math as Mathematics, sys as system
If you have a list of modules you want to import as strings, then you can use the inbuilt __import__(module_name). For example,
>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
...     globals()[lib] = __import__(lib)
Passing Pointers to Functions in C++

C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function −
#include <iostream>
#include <ctime>
 
using namespace std;
void getSeconds(unsigned long *par);

int main () {
   unsigned long sec;
   getSeconds( &sec );

   // print the actual value
   cout << "Number of seconds :" << sec << endl;

   return 0;
}

void getSeconds(unsigned long *par) {
   // get the current number of seconds
   *par = time( NULL );
   
   return;
}
When the above code is compiled and executed, it produces the following result −
Number of seconds :1294450468

The function which can accept a pointer, can also accept an array as shown in the following example −
#include <iostream>
using namespace std;
 
// function declaration:
double getAverage(int *arr, int size);
 
int main () {
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;
 
   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;
 
   // output the returned value 
   cout << "Average value is: " << avg << endl; 
    
   return 0;
}

double getAverage(int *arr, int size) {
   int i, sum = 0;       
   double avg;          
 
   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }
   avg = double(sum) / size;
 
   return avg;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.4


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Basics of Tokenizer using Tensorflow | by Sarthak Vinayaka | Towards Data Science

This article is for those who are newbies in the world of Natural Language Processing and want to make a project of Sentiment classification / Text Classification.
What is Tokenization?
As the word suggests tokenizing means dividing the sentence into a series of tokens or in layman words we can say that whenever there is a space in a sentence we add a comma between them so our sentence will get break down into tokens and each word gets a unique value of an integer.
Here is the python code using TensorFlow.
tokenizer = Tokenizer ( num_words=20, oov_token='<OOV>')tokenizer.fit_on_texts(sentence)word_index=tokenizer.word_indexsequences=tokenizer.texts_to_sequences(sentence)
After executing the above piece of code our normal text gets converted to a set of integer, below shown how our sentence looks like.
[[3, 4, 5, 2], [3], [4, 5, 2], [6, 7, 8], [9, 2]]['Hello How are you ?', 'Hello', 'How are you', 'I am fine', 'Thank You']
Now our task is to convert the array of variable length into a fixed-length array and this can be done using padding.
What is Padding ?
Padding is the method to convert the integer array of variable length into fixed-length either by truncating ( if the length is greater than the max_length defined than truncate the array ) or padding ( if he length is shorter than the max_length than pad the array with 0 ).
Below is the python code for doing so.
padded=pad_sequences(sequences, maxlen=7, truncating='post')
After executing the above code our new array will be of fixed length as shown below.
[[0 0 0 3 4 5 2][0 0 0 0 0 0 3][0 0 0 0 4 5 2][0 0 0 0 6 7 8][0 0 0 0 0 9 2]]
Integer value corresponding to words
Here is the python code to see what are the values corresponding to each word.
tokenizer.word_index
After executing the above code output will be as shown below.
{'<OOV>': 1, 'am': 7, 'are': 5, 'fine': 8, 'hello': 3, 'how': 4, 'i': 6, 'thank': 9, 'you': 2}
Conclusion
Here we have implemented basic tokenizer that will help in sentiment classification using deep learning and will be used in the real world dataset.
Powershell - Arithmetic Operators Examples

The following scripts demonstrates the arithmetic operators.
> $a = 10
 
> $b = 20
 
> $c = 25
 
> $d = 25
 
> $a + $b
 30
 
> $a - $b
 -10
 
> $a * $b
 200
 
> $b / $a
 2
 
> $b % $a
 0 

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
How to read CSV File into Python using Pandas | by Barney H. | Towards Data Science

The easiest way to do this :
import pandas as pddf = pd.read_csv ('file_name.csv')print(df)
If you want to import a subset of columns, simply addusecols=['column_name'];
pd.read_csv('file_name.csv', usecols= ['column_name1','column_name2'])
If you want to use another separator, simply add sep='\t' ; Default separator is ',' .
pd.read_csv('file_name.csv', sep='\t')
Pandas DataFrames is an excel like data structure with labeled axes (rows and columns). Here is an example of pandas DataFrame that we will use as an example below:
Code to generate DataFrame:
Pandas read_csv() function imports a CSV file to DataFrame format.
Here are some options:
filepath_or_buffer: this is the file name or file path
df.read_csv('file_name.csv’) # relative positiondf.read_csv('C:/Users/abc/Desktop/file_name.csv')
header: this allows you to specify which row will be used as column names for your dataframe. Expected an int value or a list of int values.
Default value is header=0, which means the first row of the CSV file will be treated as column names.
If your file doesn’t have a header, simply set header=None .
df.read_csv('file_name.csv’, header=None) # no header
The output of no header:
sep: Specify a custom delimiter for the CSV input, the default is a comma.
pd.read_csv('file_name.csv',sep='\t') # Use Tab to separate
index_col: This is to allow you to set which columns to be used as the index of the dataframe. The default value is None, and pandas will add a new column start from 0 to specify the index column.
It can be set as a column name or column index, which will be used as the index column.
pd.read_csv('file_name.csv',index_col='Name') # Use 'Name' column as index
nrows: Only read the number of first rows from the file. Needs an int value.
usecols: Specify which columns to import to the dataframe. It can a list of int values or column names.
pd.read_csv('file_name.csv',usecols=[1,2,3]) # Only reads col1, col2, col3. col0 will be ignored.pd.read_csv('file_name.csv',usecols=['Name']) # Only reads 'Name' column. Other columns will be ignored.
converters: Helps to convert values in the columns by defined functions.
na_values: The default missing values will be NaN. Use this if you want other strings to be considered as NaN. The expected input is a list of strings.
pd.read_csv('file_name.csv',na_values=['a','b']) # a and b values will be treated as NaN after importing into dataframe.
What are the different types of conditional statements supported by C#?

The conditional statement requires the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
The following are the types of conditional statements −
Let us see an example of nested switch statement in C# −
switch (a) {
   case 100:
   Console.WriteLine("This is part of outer switch ");

   switch (b) {
      case 200:
      Console.WriteLine("This is part of inner switch ");
      break;
   }
   break;
}
Go - Call by reference

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other value. Accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
/* function definition to swap the values */
func swap(x *int, y *int) {
   var temp int
   temp = *x    /* save the value at address x */
   *x = *y      /* put y into x */
   *y = temp    /* put temp into y */
}
To learn more about pointers in Go programming, please go through Go - Pointers.
For now, let us call the function swap() by passing values by reference as in the following example −
package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 100
   var b int = 200

   fmt.Printf("Before swap, value of a : %d\n", a )
   fmt.Printf("Before swap, value of b : %d\n", b )

   /* calling a function to swap the values.
   * &a indicates pointer to a ie. address of variable a and 
   * &b indicates pointer to b ie. address of variable b.
   */
   swap(&a, &b)

   fmt.Printf("After swap, value of a : %d\n", a )
   fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
   var temp int
   temp = *x    /* save the value at address x */
   *x = *y    /* put y into x */
   *y = temp    /* put temp into y */
}
Put the above code in a single Go file, and then compile and execute it. It produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function.

    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
What is the relation between auto and decltype in C++?

Auto and decltype serve different purposes so they don't map one-to-one. auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it. The value returned by decltype can directly be used to define another variable.
auto follows the rules of template parameter deduction. You can read more about these rule at http://en.cppreference.com/w/cpp/language/template_argument_deduction
While decltype has rules it should follow defined in the standard. Here is an excerpt from the standard with these rules:
Similarly to the sizeof operator, the operand of decltype is unevaluated. Informally, the type returned by decltype(e) is deduced as follows −
If the expression e refers to a variable in local or namespace scope, a static member variable or a function parameter, then the result is that variable's or parameter's declared type
If e is a function call or an overloaded operator invocation, decltype(e) denotes the declared return type of that function
Otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e; if e is an rvalue, the result is T
These semantics were designed to fulfill the needs of generic library writers, while at the same time being intuitive for novice programmers because the return type of decltype always matches the type of the object or function exactly as declared in the source code. More formally, Rule 1 applies to unparenthesized id-expressions and class member access expressions. For function calls, the deduced type is the return type of the statically chosen function, as determined by the rules for overload resolution. 
Example using auto and decltype,
#include<iostream>
#include<vector>

using namespace std;

int main() {
    // Using auto for type deduction
    vector<int> arr(10);
    for(auto it = arr.begin(); it != arr.end(); it ++) {
        cin >> *it;
    }

    // Using decltype for type deduction
    vector<int> arr(10);
    for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) {
        cin >> *it;
    }
    return 0;
}
Note that The type denoted by decltype can be different from the type deduced by auto. You can read more about these subtle differences in this 12-page explanation of type deduction in C++ − http://thbecker.net/articles/auto_and_decltype/section_01.html
Make a <form> left-aligned with Bootstrap

Use the .form-inline class in Bootstrap to make a <form> left aligned.
You can try to run the following code to implement .form-inline class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form class = "form-inline" role = "form">
         <div class = "form-group">
            <label class = "sr-only" for = "name">Name</label>
            <input type = "text" class = "form-control" id = "name" placeholder = "Enter Player Name">
         </div>
         <div class = "form-group">
            <label class = "sr-only" for = "name">Name</label>
            <input type = "text" class = "form-control" id = "name" placeholder = "Enter Player Country">
         </div>
         <button type = "submit" class = "btn btn-primary">Submit</button>
      </form>
   </body>
</html>
What is the Python Global Interpreter Lock (GIL)

In this article, we will learn about What is the Python Global Interpreter Lock (GIL).
This is a lock or hindrance that resistant the availability of the Python interpreter to multiple threads simultaneously. GIL is identified as a fault/issue in Python 3.x. Or earlier as it doesn’t allow multithreading in a multi-threaded architecture.
Python supports the concept of automatic garbage collection. As soon as the reference count of an object reaches zero the memory is cleaned and free for usage.
>>> import sys
>>> var = {}
>>> print(sys.getrefcount(ar))
>>> 2
>>> v=var
>>> print(sys.getrefcount(v))
>>> 3
Of in this case if the reference count starts decreasing and increasing simuktaneiously the automatic collector won’t be able to work properly and hence chances of memory leakage are increased.
To reduce this risk the GIL was introduced in python. By adding global lock is considered to be better than adding the lock to each variable that would result in a series of locks leading to deadlocking.
GIL needs to be improved so that we can handle it in a better manner. So instead of removing GIL, we are working on improving the concept of GIL. as python is purely linked with the base of c and cpython we can’t directly remove the Gil. Although there are various methods to handle the issues that GIL which solves are difficult to implement and decreasing the processing and run time of the system.
For e.g.,
Let us suppose process P1 is going on having threads t1 and t2. Python threads being native by nature, are scheduled by the underlying operating system.
t1 running(run stage) (acquire GIL) → t1 waiting for I/O(in/out) (releases GIL) → t2 running(run stage) (acquires GIL, by this time t1 is also ready to run but GIL is acquired by t2)
Hence, here the GIL becomes the major restriction. SO, if we want to write a multi-threaded python application/module that does heavy CPU bound operations, it becomes impossible to get the desired results.
Because, in Python real multi-threading is not possible, as effectively the process will be utilizing only one CPU at a single time even when multicore CPU is available.
However, in most Python applications (web application, Django based servers, etc.), this doesn't remain an issue as these applications are I/O bounded by nature.
As a Python programmer, we never have to deal with acquiring and releasing GIL until we are writing C/C++ modules/scripts that are executable in python
In this article, we learnt about the Python Global interpreter lock, its importance & why can’t be removed directly from python.
How to declare a variable in Python?

In Python, we need not declare a variable with some specific data type.
Python has no command for declaring a variable. A variable is created when some value is assigned to it. The value assigned to a variable determines the data type of that variable.
Thus, declaring a variable in Python is very simple.
Just name the variable
Just name the variable
Assign the required value to it
Assign the required value to it
The data type of the variable will be automatically determined from the value assigned, we need not define it explicitly.
The data type of the variable will be automatically determined from the value assigned, we need not define it explicitly.
To declare an integer variable −
Name the variable
Name the variable
Assign an integer value to it
Assign an integer value to it
 Live Demo
x=2
print(x)
print(type(x))
This is how you declare a integer variable in Python. Just name the variable and assign the required value to it. The datatype is automatically determined.
2
<class 'int'>
Assign a string value to the variable and it will become a string variable. In Python, the string value cane be assigned in single quotes or double quotes.
 Live Demo
x='2'
print(x)
print(type(x))
2
<class 'str'>
A float variable can be declared by assigning float value. Another way is by typecasting.
We will use both.
 Live Demo
x=2.0
print(x)
print(type(x))
y=float(2)
print(y)
print(type(y))
2.0
<class 'float'>
2.0
<class 'float'>
Note: The string variable can also be declared using type casting, when using integer values as string.
Unlike some another languages, where we can assign only the value of the defined data type to a variable. This means an integer varibale can only be assigned an integer value throughout the program. But,in Python , the variable are not of a particular datatype. Their datatype can be changed even after it is set.
The following example will clarify the above concept.
 Live Demo
x=10
print(x)
print(type(x))
x="abc"
print(x)
print(type(x))
10
<class 'int'>
abc
<class 'str'>
The variable x was of type int. Later when string value is assigned to it, it changes into a string variable.
Find n-th term of series 1, 3, 6, 10, 15, 21 | Practice | GeeksforGeeks

Given a number N, find the Nth term in the series 1, 3, 6, 10, 15, 21...
 
Example 1:
Input :
N = 4 
Output:
10
Explanation:
The 4th term of the Series is 10.
Example 2:
Input :
N = 3 
Output:
6
Explanation:
The 3rd term of the Series is 6.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function findNthTerm() which takes an Integer N as input and returns the answer.
 
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
 
Constraints:
1 <= N <= 104
0
mayank180919995 days ago
   int findNthTerm(int N) {
        // code here
        return (N*N+N)/2;
    }
-1
rsbly7300952 weeks ago
class Solution {
   findNthTerm(N){
      return (N*((N+1)/2))
   }
}
0
ishangarg23 weeks ago
recursive solution:
   int sum = 0;       if(N == 0) return 0;       sum = findNthTerm(N-1);       return sum + N; 
0
sayanmazumder9991 month ago
JAVA
      int sum = 1;        for(int i = 2; i<N+1; i++) sum += i;            return sum;
+1
kirankolte21561 month ago
 
class Solution {   static int findNthTerm(int N) {       // code here       return N*(N+1)/2;                     }}
0
shivanshixa312 months ago
int findNthTerm(int N) {
        // code here
        int d=2,A1=1;
        for(int i=0;i<N-1;i++){
            A1+=d;
            d++;
        }
        return A1;
    }
0
manohar4r2 months ago
static int findNthTerm(int n){       int f = 1, s = 2;       for(int i=2; i<=n;i++){           f=f+s;           s++;       }       return f;   }
0
younisteli932 months ago
int first =1;       int sec= 2;       int[] arr = new int[n];       for (int i=0; i<n; i++)       {           arr[i]=first;           first=first+sec;           sec++;       }
0
nehalshetty73 months ago
import java .io.*;import java .util.*;
public class Main{public static void main(String[] args) {   Scanner sc= new Scanner(System.in);   int n= sc.nextInt();   int []arr={1,3,6,10,15,21};        {   System.out.println(arr[n-1]);       }         }}
0
1ashishchauhan20023 months ago
    int findNthTerm(int N) {       return (N*(N+1))/2;   }
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Program to find minimum difference between two elements from two lists in Python

Suppose we have two lists L1 and L2, we have to find the smallest difference between a number from L1 and a number from L2.
So, if the input is like L1 = [2, 7, 4], L2 = [16, 10, 11], then the output will be 3, as the smallest difference is 10 - 7 = 3.
To solve this, we will follow these steps −
sort the list L1 and sort the list L2
ans := infinity
i := 0, j := 0
while i < size of L1 and j < size of L2, doans := minimum of ans and |L1[i] - L2[j]|if L1[i] < L2[j], theni := i + 1otherwise,j := j + 1
ans := minimum of ans and |L1[i] - L2[j]|
if L1[i] < L2[j], theni := i + 1
i := i + 1
otherwise,j := j + 1
j := j + 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, L1, L2):
      L1.sort()
      L2.sort()
      ans = float("inf")
      i = j = 0
      while i < len(L1) and j < len(L2):
         ans = min(ans, abs(L1[i] - L2[j]))
         if L1[i] < L2[j]:
            i += 1
         else:
            j += 1
      return ans
ob = Solution()
L1 = [2, 7, 4] L2 = [16, 10, 11]
print(ob.solve(L1, L2))
[2, 7, 4], [16, 10, 11]
3
How to load and save 3D Numpy array to file using savetxt() and loadtxt() functions? - GeeksforGeeks

05 Sep, 2020
Prerequisites: numpy.savetxt(), numpy.loadtxt()
Numpy.savetxt() is a method in python in numpy library to save an 1D and 2D array to a file.
Syntax: numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘, encoding=None)
numpy.loadtxt() is a method in python in numpy library to load data from a text file for faster reading.
Syntax: numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
As discussed earlier we can only use 1D or 2D array in numpy.savetxt(), and if we use an array of more dimensions it will throw a ValueError – Expected 1D or 2D array, got 3D array instead. Therefore, we need to find a way to save and retrieve, at least for 3D arrays, here’s how you can do this by using some Python tricks.
Step 1: reshape the 3D array to 2D array.
Step 2: Insert this array to the file
Step 3: Load data from the file to display
Step 4: convert back to the original shaped array
Example:
Python3
import numpy as gfg    arr = gfg.random.rand(5, 4, 3)  # reshaping the array from 3D# matrice to 2D matrice.arr_reshaped = arr.reshape(arr.shape[0], -1)  # saving reshaped array to file.gfg.savetxt("geekfile.txt", arr_reshaped)  # retrieving data from file.loaded_arr = gfg.loadtxt("geekfile.txt")  # This loadedArr is a 2D array, therefore# we need to convert it to the original# array shape.reshaping to get original# matrice with original shape.load_original_arr = loaded_arr.reshape(    loaded_arr.shape[0], loaded_arr.shape[1] // arr.shape[2], arr.shape[2])  # check the shapes:print("shape of arr: ", arr.shape)print("shape of load_original_arr: ", load_original_arr.shape)  # check if both arrays are same or not:if (load_original_arr == arr).all():    print("Yes, both the arrays are same")else:    print("No, both the arrays are not same")
Output:
shape of arr:  (5, 4, 3)
shape of load_original_arr:  (5, 4, 3)
Yes, both the arrays are same
Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
Convert integer to string in Python