code-rag-bench/online-tutorials huggingface dataset:
How to get column names in Pandas dataframe - GeeksforGeeks

12 May, 2022
While analyzing the real datasets which are often very huge in size, we might need to get the column names in order to perform some certain operations. Let’s discuss how to get column names in Pandas dataframe. First, let’s create a simple dataframe with nba.csv file. 
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     # calling head() method  # storing in new variable data_top = data.head()     # display data_top 
 Now let’s try to get the columns name from above dataset.
YouTubeGeeksforGeeks507K subscribersDifferent Ways to Get Python Pandas Column Names | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ty9TWZ7js6A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Method #1: Simply iterating over columns 
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")   # iterating the columnsfor col in data.columns:    print(col)
Output:    Method #2: Using columns with dataframe object 
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")     # list(data) orlist(data.columns)
Output:    Method #3: column.values method returns an array of index. 
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")     list(data.columns.values)
Output:    Method #4: Using tolist() method with values with given the list of columns. 
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")     list(data.columns.values.tolist())
Output:    Method #5: Using sorted() method Sorted() method will return the list of columns sorted in alphabetical order. 
Python3
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("nba.csv")     # using sorted() methodsorted(data)
Output: 
sagartomar9927
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
GET and POST requests using Python
Java Program to Calculate and Display Area of a Circle - GeeksforGeeks

28 Mar, 2021
Given a radius of the circle, write a java program to calculate and display the area of the circle. (Take ∏=3.142)
Example
Input : radius= 5
Output: Area of circle is : 78.55

Input : radius= 8
Output: Area of circle is : 201.08
As we know to calculate the area of a circle, the radius of the circle must be known, so if the radius of the circle is known, then the area of the circle can be calculated by using the formula:
Area = 3.142*(radius)*(radius)
Below is the Java Program to calculate the area of the circle:- 
Java
// Java program to calculate the area of thepublic class GFG {    public static void main(String[] args)    {        int radius;        double pi = 3.142, area;        radius = 5;        // calculating the area of the circle        area = pi * radius * radius;        // printing the area of the circle        System.out.println("Area of circle is :" + area);    }}
Area of circle is :78.55

circle
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
How to compare two ValueTuple in C#? - GeeksforGeeks

23 Jul, 2019
To compare two instances of ValueTuple you can use CompareTo method which is provided by ValueTuple structure. ValueTuple.CompareTo(ValueTuple) Method is used to compare the current instance of ValueTuple with another ValueTuple instance. It always returns zero if they are equal to each other.
Syntax:
public int CompareTo (ValueTuple other);
Here, other is the object to compare with the current instance.
Returns: The method always returns 0 of type System.Int32.
Exception: This method will throw an ArgumentException if the other is not ValueTuple instance.
Example 1:
// C# program to illustrate the // concept of CompareTo methodusing System;  class GFG {      // Main method    static public void Main()    {          // Creating value tuples with two elements        var MyTple1 = ValueTuple.Create(56, 45);        var MyTple2 = ValueTuple.Create(56, 3);        var MyTple3 = ValueTuple.Create(56, 45);        var MyTple4 = ValueTuple.Create(5345, 45);          // Using CompareTo method        int res1 = MyTple1.CompareTo(MyTple2);        int res2 = MyTple1.CompareTo(MyTple3);        int res3 = MyTple1.CompareTo(MyTple4);          // Display result        Console.WriteLine("Result 1: " + res1);        Console.WriteLine("Result 2: " + res2);        Console.WriteLine("Result 3: " + res3);    }}
Result 1: 1
Result 2: 0
Result 3: -1

Example 2:
// C# program to illustrate the// use of CompareTo methodusing System;  class GFG {      // Main Method    static public void Main()    {          // Creating value tuples with one element        var MyVTple1 = ValueTuple.Create(2018);        var MyVTple2 = ValueTuple.Create(2018);          // Compare both value tuples        // Using CompareTo method        if (MyVTple1.CompareTo(MyVTple2) == 0)         {            Console.WriteLine("Welcome to GeeksforGeeks");        }          else         {            Console.WriteLine("Page Not Found");        }    }}
Welcome to GeeksforGeeks

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple.compareto?view=netframework-4.8
CSharp-ValueTuple
CSharp-ValueTuple-Methods
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
C# | Data Types
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Linked List Implementation in C#
Node.js date-and-time Date.locale() Method - GeeksforGeeks

26 Mar, 2021
The date-and-time.Date.locale() method is used to get or switch the locale from one into another language.
Required Module: Install the module by npm or used it locally.
By using npm:
npm install date-and-time --save
By using CDN link:
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
locale(])
Parameters: This method takes the locale and code as a parameter.
Return Value: This method returns the current locale of the date and time object.
Example 1:
index.js
// Node.js program to demonstrate the  // Date.locale() APi  // Importing date-and-time moduleconst date = require('date-and-time')  // Getting the locale valueconst value = date.locale();  // display the resultconsole.log("current locale :- " + value)
Run index.js file using below command:
node index.js
Output:
current locale :- en
Example 2: Changing locale 
Filename: index.js 
index.js
// Node.js program to demonstrate the  // Date.locale() APi  // Importing date-and-time moduleconst date = require('date-and-time')  // Changing the local to es spanishconsole.log("Change local "+date.locale('es'))
Run index.js file using below command:
node index.js
Output:
Change local es
Reference: https://github.com/knowledgecode/date-and-time#localecode-locale
Node.js-Methods
NodeJS date-time
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
SYSDATE() function in MySQL - GeeksforGeeks

27 Nov, 2020
SYSDATE() function in MySQL is used to return the current date and time in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format depending on the context of the function.
Syntax :
SYSDATE()

Parameter :This method does not accept any parameter.
Returns :It returns the current date and time value.
Example-1 :Getting the current date and time using SYSDATE Function.
SELECT SYSDATE() as CurrentDateAndTime ;

Output :
Example-2 :Getting the current date and time using SYSDATE Function in numeric format.
SELECT SYSDATE() + 0 as CurrDateAndTime ;

Output :
Example-3 :The SYSDATE function can be used to set value of columns. To demonstrate create a table named DeliveryDetails.
CREATE TABLE DeliveryDetails (
DeliveryId INT AUTO_INCREMENT,
ProductId INT NOT NULL,
ProductName VARCHAR(20) NOT NULL,
Delivered_At TIMESTAMP NOT NULL,
PRIMARY KEY(DeliveryId)
);

Here, we will use SYSDATE function when a delivery will be completed. The value in Delivered_At column will be the value given by SYSDATE Function.
INSERT INTO  
DeliveryDetails(ProductId, ProductName, Delivered_At)
VALUES
(94567, 'Acer Helios', SYSDATE());
Now, checking the DeliveryDetails table :
SELECT * FROM DeliveryDetails;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
PHP | Imploding and Exploding

08 Mar, 2018
Imploding and Exploding are couple of important functions of PHP that can be applied on strings or arrays. PHP provides us with two important builtin functions implode() and explode() to perform these operations. As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter.
implode() method
Syntax:
string implode (glue ,pieces)

or,
string implode (pieces)

Parameters:The function accepts two parameters as described below.
glue (optional): This parameter expects a string segment that is used as the glue to join the pieces of the array. This is an optional parameter with default value being an empty string.
pieces: This parameter expects an array whose elements are to be joined together to construct the final imploded string.
Return Type: This function traverses the input array and concatenates each element with one glue segment separating them to construct and return the final imploded string.
Below program illustrates the working of implode() in PHP:
<?php// PHP code to illustrate the working of implode()  $array1 = array('www', 'geeksforgeeks', 'org');echo(implode('.',$array1)."<br>");   $array2 = array('H', 'E', 'L', 'L', 'O');echo(implode($array2));?>
Output:
www.geeksforgeeks.org
HELLO

You may refer to the article on PHP | implode() function to learn about implode() in details.
explode() method
Syntax:
array explode (delimiter, string, limit)

Parameters:The function accepts three parameters as described below.
delimiter: This parameter expects a string segment that can be used as the separator. If the delimiter itself is not present in the string then the resultant will be an array containing the string as its sole element.
string: This parameter expects a string which is to be exploded.
limit: This parameter expects an integer (both positive and negative). This is an optional parameter with default value of PHP_INT_MAX. The limit refers to the maximum number of divisions that are to be made on the input string.
Return Type: This function returns an array of strings containing the separated segments.
Below program illustrates the working of explode() in PHP:
<?php// PHP code to illustrate the working of explode()  $str1 = '1,2,3,4,5';$arr = explode(',',$str1);foreach($arr as $i)echo($i.'<br>');?>
Output:
1
2
3
4
5

You may refer to the article on PHP | explode() function to learn about explode() in details.
Important Points to Note:
The implode() function implodes the elements of an array and returns the resultant string.
Although not advised, the implode() function can take the parameters irrespective of their order
The PHP | Join() function is an alias of implode() function.
PHP-array
PHP-function
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Creating Roles

27 Sep, 2018
A role is created to ease setup and maintenance of the security model. It is a named group of related privileges that can be granted to the user. When there are many users in a database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles:
You can grant or revoke privileges to users, thereby automatically granting or revoking privileges.
You can either create Roles or use the system roles pre-defined.
Some of the privileges granted to the system roles are as given below:
Creating and Assigning a Role –
First, the (Database Administrator)DBA must create the role. Then the DBA can assign privileges to the role and users to the role.
Syntax –
CREATE ROLE manager;
Role created.

In the syntax:‘manager’ is the name of the role to be created.
Now that the role is created, the DBA can use the GRANT statement to assign users to the role as well as assign privileges to the role.
It’s easier to GRANT or REVOKE privileges to the users through a role rather than assigning a privilege directly to every user.
If a role is identified by a password, then GRANT or REVOKE privileges have to be identified by the password.
Grant privileges to a role –
GRANT create table, create view
TO manager;
Grant succeeded.

Grant a role to users
GRANT manager TO SAM, STARK;
Grant succeeded.

Revoke privilege from a Role :
REVOKE create table FROM manager;

Drop a Role :
DROP ROLE manager;

Explanation –Firstly it creates a manager role and then allows managers to create tables and views. It then grants Sam and Stark the role of managers. Now Sam and Stark can create tables and views. If users have multiple roles granted to them, they receive all of the privileges associated with all of the roles. Then create table privilege is removed from role ‘manager’ using Revoke.The role is dropped from the database using drop.
sunny94
SQL-basics
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Interview Questions
SQL | Views
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Matplotlib.axes.Axes.set_yticks() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_yticks() function in axes module of matplotlib library is used to Set the y ticks with list of ticks.
Syntax:Axes.set_yticks(self, ticks, minor=False)
Parameters: This method accepts the following parameters.
ticks : This parameter is the list of y-axis tick locations.
minor : This parameter is used whether set major ticks or to set minor ticks
Return value: This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.set_yticks() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms    fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10))  fig.suptitle('matplotlib.axes.Axes.set_yticks()\ function Example\n\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  # Fixing random state for reproducibilitynp.random.seed(19680801)  x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape)  fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2)  ax.set_yticks([-1, 0, 1])  ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)  fig.suptitle('matplotlib.axes.Axes.set_yticks()\ function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Python-matplotlib
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
What is a functional interface in Java?

An interface with only one abstract method is known as Functional Interface. @FunctionalInterface annotation can be added so that we can mark an interface as a functional interface. The Java compiler automatically identifies the functional interface.
The lambda expressions are used primarily to define the inline implementation of a functional interface. It eliminates the need for an anonymous class and gives a simple and powerful functional programming capability to Java.
Few java default interfaces are functional interfaces listed below
java.lang.Runnable
java.util.concurrent.Callable
java.io.FileFilter
java.util.Comparator
java.beans.PropertyChangeListener
@FunctionalInterface
interface interface-name {
 // only one abstract method
}
@FunctionalInterface
interface MathOperation {
   int operation(int a, int b);
}
public class LambdaExpressionTest {
   public static void main(String args[]) {
      MathOperation addition = (a, b) -> a + b;  // lambda expression
      MathOperation multiplication = (int a, int b) -> { return a * b; };  // lambda expression
      System.out.println("The addition of two numbers are: " + addition.operation(5, 5));
      System.out.println("The multiplication of two numbers are: " + multiplication.operation(5, 5));
   }
}
The addition of two numbers are: 10
The multiplication of two numbers are:: 25
strings.Index() Function in Golang With Examples

19 Apr, 2020
strings.Index() Function in Golang is used to get the first instance of a specified substring. If the substring is not found, then this method will return -1.
Syntax:
func Index(str, sbstr string) int
Here, str is the original string and sbstr is a string whose we want to find index value.
Example 1:
// Go program to illustrate the // String Index() Function  package main      import (     "fmt"    "strings")      // Main function func main() {          // Creating and initializing the strings     str1 := "Welcome to GeeksforGeeks"    str2 := "My name is XYZ"         // Displaying strings     fmt.Println("String 1: ", str1)     fmt.Println("String 2: ", str2)          // Using Index() function     res1 := strings.Index(str1, "Geeks")     res2 := strings.Index(str2, "is")        // Displaying the result     fmt.Println("\nIndex values:")     fmt.Println("Result 1: ", res1)     fmt.Println("Result 2: ", res2)      } 
Output:
String 1:  Welcome to GeeksforGeeks
String 2:  My name is XYZ

Index values:
Result 1:  11
Result 2:  8

Example 2:
// Go program to illustrate the// String Index() Function  package main  import (    "fmt"    "strings")  // Main functionfunc main() {      // Using Index() function    res1 := strings.Index("GFG", "H")    res2 := strings.Index("GeeksforGeeks", "for")      // Displaying the result    fmt.Println("Result 1: ", res1)    fmt.Println("Result 2: ", res2)  }
Output:
Result 1:  -1
Result 2:  5

Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Golang Maps
Arrays in Go
How to copy one slice into another slice in Golang?
Time Durations in Golang
Interfaces in Golang
Inheritance in GoLang
Check if the String starts with specified prefix in Golang
How to iterate over an Array using for loop in Golang?
How to compare two slices of bytes in Golang?
Type Casting or Type Conversion in Golang
Java Program to Add two Matrices

23 Feb, 2021
Given two matrices A and B of same size, the task to add them in Java. Examples: 
Input: A[][] = {{1, 2}, 
                {3, 4}}
       B[][] = {{1, 1}, 
                {1, 1}}
Output: {{2, 3}, 
         {4, 5}}

Input: A[][] = {{2, 4}, 
                {3, 4}}
       B[][] = {{1, 2}, 
                {1, 3}}       
Output: {{3, 6}, 
         {4, 7}}
Approach:  
Take the two matrices to be added
Create a new Matrix to store the sum of the two matrices
Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index.
Print the final new matrix
Below is the implementation of the above approach: 
Java
// Java program for addition of two matrices import java.io.*; class GFG {     // Function to print Matrix    static void printMatrix(int M[][],                            int rowSize,                            int colSize)    {        for (int i = 0; i < rowSize; i++) {            for (int j = 0; j < colSize; j++)                System.out.print(M[i][j] + " ");             System.out.println();        }    }     // Function to add the two matrices    // and store in matrix C    static int[][] add(int A[][], int B[][],                       int size)    {        int i, j;        int C[][] = new int[size][size];         for (i = 0; i < size; i++)            for (j = 0; j < size; j++)                C[i][j] = A[i][j] + B[i][j];         return C;    }     // Driver code    public static void main(String[] args)    {        int size = 4;         int A[][] = { { 1, 1, 1, 1 },                      { 2, 2, 2, 2 },                      { 3, 3, 3, 3 },                      { 4, 4, 4, 4 } };        // Print the matrices A        System.out.println("\nMatrix A:");        printMatrix(A, size, size);         int B[][] = { { 1, 1, 1, 1 },                      { 2, 2, 2, 2 },                      { 3, 3, 3, 3 },                      { 4, 4, 4, 4 } };        // Print the matrices B        System.out.println("\nMatrix B:");        printMatrix(B, size, size);         // Add the two matrices        int C[][] = add(A, B, size);         // Print the result        System.out.println("\nResultant Matrix:");        printMatrix(C, size, size);    }}
Matrix A:
1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 

Matrix B:
1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 4 

Resultant Matrix:
2 2 2 2 
4 4 4 4 
6 6 6 6 
8 8 8 8
 
Time Complexity: O(N2), where N is the row or column number of the matrix
Auxiliary Space: O(N2)
subhammahato348
Java
Java Programs
Matrix
School Programming
Matrix
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
PortSpider – Advance Network Port scanner on Kali Linux

17 Jun, 2021
PortSpider is a free and open-source tool available on GitHub. PortSpider is an Open Source Intelligence and network scanning Tool based on (OSINT). This tool can scan huge network ranges to find open and closed ports and all the vulnerable services running on the server or on the system, not only scans a single target system but can target a big number range of IP addresses. It is very helpful for auditing the network of companies and organizations they used to scan the whole range of their private IP addresses.
Ssh module Scan for open SSH ports of systems.
Printer module Scan for open printer ports and websites.
Game server module Scan for open game server ports.
manual module Scan custom ports.
HTTP module Scan for open HTTP ports and get the titles.
MySQL module Scan for open MySQL servers, and try to log in with the default credentials.
MongoDB module Scan for open MongoDB instances and check if they are password protected.
Step 1: Open your Kali Linux operating system and using the following command download the tool from GitHub. After downloading the tool move to the directory and install all the requirements using the following command
git clone https://github.com/xdavidhu/portSpider.git
cd portSpider/
python3 -m install -r requirements.txt
Step 2: The tool has been downloaded to your Kali Linux operating system now run the tool using the following command.
python3 portSpider.py
The tool has been downloaded and running successfully. Now we will see some examples.
Example: Use the PortSpider tool to use MySQL module and scan the IP range.
use mysql
options
The tool has started scanning using mysql module. This is how you can also perform scanning in your IP range using port spider.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
f-strings in Python

21 Jan, 2021
PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler. To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.   Code #1 :  
Python3
# Python3 program introducing f-stringval = 'Geeks'print(f"{val}for{val} is a portal for {val}.")  name = 'Tushar'age = 23print(f"Hello, My name is {name} and I'm {age} years old.")
Output :  
GeeksforGeeks is a portal for Geeks.
Hello, My name is Tushar and I'm 23 years old.
  Code #2 :  
Python3
# Prints today's date with help# of datetime libraryimport datetime today = datetime.datetime.today()print(f"{today:%B %d, %Y}")
Output :  
April 04, 2018
  Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format().   Let’s see few error examples, which might occur while using f-string :Code #3 : Demonstrating Syntax error.  
Python3
answer = 456f"Your answer is "{answer}""
Code #4 : Backslash Cannot be used in format string directly. 
Python3
f"newline: {ord('\n')}"
Output :  
Traceback (most recent call last):
  Python Shell, prompt 29, line 1
Syntax Error: f-string expression part cannot include a backslash: , line 1, pos 0
  But the documentation points out that we can put the backslash into a variable as a workaround though : 
Python3
newline = ord('\n') f"newline: {newline}"
Output :  
newline: 10
Reference : PEP 498, Literal String Interpolation 
mustafaaçık
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Python OpenCV | cv2.erode() method

29 Nov, 2019
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.erode() method is used to perform erosion on the image. The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground object (Always try to keep foreground in white). It is normally performed on binary images. It needs two inputs, one is our original image, second one is called structuring element or kernel which decides the nature of operation. A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1, otherwise it is eroded (made to zero).
Syntax: cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]])Parameters:src: It is the image which is to be eroded .kernel: A structuring element used for erosion. If element = Mat(), a 3 x 3 rectangular structuring element is used. Kernel can be created using getStructuringElement.dst: It is the output image of the same size and type as src.anchor: It is a variable of type integer representing anchor point and it’s default value Point is (-1, -1) which means that the anchor is at the kernel center.borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc.iterations: It is number of times erosion is applied.borderValue: It is border value in case of a constant border.Return Value: It returns an image.
Image used for all the below examples:Example #1:
# Python program to explain cv2.erode() method   # importing cv2 import cv2  # importing numpy import numpy as np  # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'  # Reading an image in default mode image = cv2.imread(path)   # Window name in which image is displayed window_name = 'Image'  # Creating kernelkernel = np.ones((5, 5), np.uint8)  # Using cv2.erode() method image = cv2.erode(image, kernel)   # Displaying the image cv2.imshow(window_name, image) 
Output:
Example #2:
# Python program to explain cv2.erode() method   # importing cv2 import cv2  # importing numpy import numpy as np  # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'  # Reading an image in default mode image = cv2.imread(path)   # Window name in which image is displayed window_name = 'Image'  # Creating kernelkernel = np.ones((6, 6), np.uint8)  # Using cv2.erode() method image = cv2.erode(image, kernel, cv2.BORDER_REFLECT)   # Displaying the image cv2.imshow(window_name, image) 
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2009 | Question 24

28 Jun, 2021
The binary operation c is defined as follows
Which one of the following is equivalent to P∨Q?
A) 

B) 

C) 

D) 
(A) A(B) B(C) C(D) DAnswer: (B)Explanation:  
 
This solution is contributed by Anil Saikrishna Devarasetty.Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Database & Collection in MongoDB?

05 Feb, 2021
MongoDB stores data records as documents that are stored together in collections and the database stores one or more collections of documents.
Document: A document is a basic unit of storing data into the database. A single record of a collection is also known as a document. Basically, It is a structure that compromises key & value pairs which is similar to the JSON objects. Documents have a great ability to store complex data. For example:
Here, the name, country, age and status are fields, and gfg, India, 21, A are their values.
Collection: It is used to store a varied number of documents inside the database. As MongoDB is a Schema-free database, it can store the documents that are not the same in structure. Also, there is no need to define the columns and their datatype. 
Database: The MongoDB database is a container for collections and it can store one or more collections. It is not necessary to create a database before you work on it. The show dbs command gives the list of all the databases. 
In MongoDB, we can create a database using the use command. As shown in the below image
use gfgDB
Here, we have created a database named as “gfgDB”. If the database doesn’t exist, MongoDB will create the database when you store any data to it. Using this command we can also switch from on database to another.
In MongoDB, we can view all the existing database using the following command:
show dbs
This command returns a list of all the existing databases.
In MongoDB, a new collection is created when we add one or more documents to it. We can insert documents in the collection using the following methods:
Inserting only one document in the collection
db.myNewCollection1.insertOne( { name:"geeksforgeeks" } )
Here, we create a collection named as myNewCollection1 by inserting a document that contains a name field with its value in it using insertOne() method.
Inserting many documents in the collection
db.myNewCollection2.insertMany([{name:"gfg", country:"India"},
                                {name:"rahul", age:20}])
Here, we create a collection named as myNewCollection2 by inserting two documents using insertMany() method.
In MongoDB, we can view all the existing collection in the database using the following command:
show collections
This command returns a list of all the existing collections in the gfgDB database.
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB Cursor
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
Mongoose | update() Function
How to perform grep operation on all files in a directory?

The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.
Normally, the pattern that we are trying to search in the file is referred to as the regular expression.
grep [options] pattern [files]
While there are plenty of different options available to us, some of the most used are −
-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern
Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1.
grep -rni "word" *
In the above command replace the “word” placeholder with
For that we make use of the command shown below −
grep -rni "func main()" *
The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.
main.go:120:func main() {}

In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −
grep -s "func main()" *
In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command.
main.go:120:func main() {}
Another command that we can make use of is the find command.
find . -name "*.go" -exec grep -H "func main" {} \;
./main.go:func main() {
NLP | WuPalmer – WordNet Similarity

20 Jun, 2021
How Wu & Palmer Similarity works ? It calculates relatedness by considering the depths of the two synsets in the WordNet taxonomies, along with the depth of the LCS (Least Common Subsumer).  
The score can be 0 < score <= 1. The score can never be zero because the depth of the LCS is never zero (the depth of the root of taxonomy is one). It calculates the similarity based on how similar the word senses are and where the Synsets occur relative to each other in the hypernym tree. Code #1 : Introducing Synsets  
Python3
from nltk.corpus import wordnet syn1 = wordnet.synsets('hello')[0]syn2 = wordnet.synsets('selling')[0] print ("hello name :  ", syn1.name())print ("selling name :  ", syn2.name())
Output :  
hello name :   hello.n.01
selling name :   selling.n.01
  Code #2 : Wu Similarity  
Python3
syn1.wup_similarity(syn2)
Output :  
0.26666666666666666
hello and selling are apparently 27% similar! This is because they share common hypernyms further up the two.   Code #3 : Let’s check the hypernyms in between.  
Python3
sorted(syn1.common_hypernyms(syn2))
Output :  
[Synset('abstraction.n.06'), Synset('entity.n.01')]
One of the core metrics used to calculate similarity is the shortest path the distance between the two Synsets and their common hypernym.   Code #4 : Let’s understand the use of hypernerm.  
Python3
ref = syn1.hypernyms()[0]print ("Self comparison : ",       syn1.shortest_path_distance(ref)) print ("Distance of hello from greeting : ",       syn1.shortest_path_distance(syn2)) print ("Distance of greeting from hello : ",       syn2.shortest_path_distance(syn1))
Output :  
Self comparison :  1
Distance of hello from greeting :  11
Distance of greeting from hello :  11
Note : The similarity score is very high i.e. they are many steps away from each other because they are not so similar. The codes mentioned here uses ‘noun’ but one can use any Part of Speech (POS). 
surindertarika1234
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Show and hide password using JavaScript

19 Feb, 2019
While filling up a form, there comes a situation where we type a password and want to see what we have typed till now. To see that, there is a checkbox clicking on which makes the characters visible.In this post, this feature i.e. toggling password is implemented using JavaScript.
Algorithm1)Create a HTML form which contain an input field of type password.
2)Create a checkbox which will be responsible for toggling.
3)Create a function which will response for toggling when a user clicks on the checkbox.
Examples:
Password is geeksforgeeks.So, on typing it will show like this *************And on clicking the checkbox it will show the characters: geeksforgeeks.
<!DOCTYPE html><html><body>   <b><p>Click on the checkbox to show           or hide password: </p></b>   <b>Password</b>: <input type="password"      value="geeksforgeeks" id="typepass">    <input type="checkbox" onclick="Toggle()">    <b>Show Password</b>      <script>    // Change the type of input to password or text        function Toggle() {            var temp = document.getElementById("typepass");            if (temp.type === "password") {                temp.type = "text";            }            else {                temp.type = "password";            }        }</script></body></html>
Output:
Hide password:
Show password:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
PHP | ob_start() Function

08 Mar, 2018
Let’s take a quick recap. PHP is an interpreted language thus each statement is executed one after another, therefore PHP tends to send HTML to browsers in chunks thus reducing performance. Using output buffering the generated HTML gets stored in a buffer or a string variable and is sent to the buffer to render after the execution of the last statement in the PHP script.
But Output Buffering is not enabled by default. In order to enable the Output Buffering one must use the ob_start() function before any echoing any HTML content in a script.
Syntax:
bool ob_start ()

Parameters: The function can accept a bunch of optional parameters as follows:
Callback function: This is an optional parameter that expects a function that takes the contents of the output buffer and returns a string that is to be sent to the browser for rendering. The callback function is generally used for compressing the HTML content.
Chunk size: This is another optional parameter that sets the output buffer size of provided size and outputs as soon as the buffer is either full or exceeded.
Flags: This is another optional parameter that accepts a bitmask to control the operations that can be implemented on the output buffer. This parameter is passed to restrict access. The Default permissions gives access to clean, flush and removal of the buffer.
Return Type: This function returns TRUE on success otherwise FALSE.
Below program illustrates the working of ob_start() in PHP:
<?php  // PHP code to illustrate the working//  of ob_start() Function   function callback($buffer){    // Return Everything in CAPS.    return (strtoupper($buffer));}  ob_start("callback");echo "Hello Geek!";ob_end_flush();  ?>
Output:
HELLO GEEK!

Important points to note:
Enables Output Buffering.
Output Buffering flags can be of four types PHP_OUTPUT_HANDLER_CLEANABLE(only clean), PHP_OUTPUT_HANDLER_FLUSHABLE(only flush), PHP_OUTPUT_HANDLER_REMOVABLE(only remove), PHP_OUTPUT_HANDLER_STDFLAGS(allowed every operation).
Output buffers are stackable, thus nested ob_start() methods are allowed and works as desired if they are closed/flushed sequentially.
Reference:http://php.net/manual/en/function.ob-start.php
PHP-function
PHP-input-output
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript - For Loop

The 'for' loop is the most compact form of looping. It includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
The flow chart of a for loop in JavaScript would be as follows −
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
   Statement(s) to be executed if test condition is true
}

Try the following example to learn how a for loop works in JavaScript.
<html>
   <body>      
      <script type = "text/javascript">
         <!--
            var count;
            document.write("Starting Loop" + "<br />");
         
            for(count = 0; count < 10; count++) {
               document.write("Current Count : " + count );
               document.write("<br />");
            }         
            document.write("Loop stopped!");
         //-->
      </script>      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 
Set the variable to different value and then try...


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page