code-rag-bench/online-tutorials huggingface dataset:
Python | os.mkfifo() method

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.mkfifo() method in Python is used to create a FIFO (a named pipe) named path with the specified mode.
FIFOs are named pipe which can be accessed like other regular files. This method only create FIFO but don’t open it and the created FIFO does exist until they are deleted. FIFOs are generally us as rendezvous between client and “server type processes.
Syntax: os.mkfifo(path, mode = 0o666, *, dir_fd = None)
Parameters:path: A path-like object representing the file system path. It can be a string or bytes object representing a file path.mode (optional): A numeric value representing the mode of the FIFO (named pipe) to be created. The default value of mode parameter is 0o666 (octal).dir_fd (optional): This is a file descriptor referring to a directory.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as a positional parameter.
Return type: This method does not return any value.
Code: Use of os.mkfifo() method
# Python3 program to explain os.mkfifo() method  # importing os moduleimport os    # Pathpath = "./mypipe"  # Mode of the FIFO (a named pipe)# to be createdmode = 0o600  # Create a FIFO named path# with the specified mode# using os.mkfifo() methodos.mkfifo(path, mode)    print("FIFO named '% s' is created successfully." % path)
FIFO named './mypipe' is created successfully.

python-os-module
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
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
Introduction To PYTHON
Overlay Density Plots in Base R

17 Jun, 2021
In this article, we will discuss how to overlay density plot using some base functions of the R Programming Language. Overlaying density plots means creating some density plots of the different data over a single plot.
Plot() : This is a generic function for plotting R objects.
Syntax:
plot(x, y, ...)
Parameters:
x: the coordinates of points in the plot.
y: the y coordinates of points in the plot,
...: Arguments to be passed to methods, such as graphical parameters
Density(): This is a generic function density that computes kernel density estimates. Its default method does so with the given kernel and bandwidth for uni-variate observations.
Syntax:
density(x,...)
Parameters:
x:-the data from which the estimate is to be computed.
...:-further arguments for (non-default) methods.
Returns:
This function will be returning the density plot of the given data.
Lines(): This is a generic function taking coordinates given in various ways and joining the corresponding points with line segments.
Syntax:
lines(x, ...)
Parameters:
x:-coordinate vectors of points to join.
...:-Further graphical parameters
R creates histogram using hist() function.
Syntax:
hist(v, main, xlab, xlim, ylim, breaks, col, border)
Parameters:
v: This parameter contains numerical values used in histogram.
main: This parameter main is the title of the chart.
col: This parameter is used to set color of the bars.
xlab: This parameter is the label for horizontal axis.
border: This parameter is used to set border color of each bar.
xlim: This parameter is used for plotting values of x-axis.
ylim: This parameter is used for plotting values of y-axis.
breaks: This parameter is used as width of each bar.
Overlaying two density plots may seem complex, but it is as simple as plotting a same density graph. For every other plot you just have to keep calling the function with their respective density and add their required mechanism to functions except the first one to keep drawing them on the same plot.
Example 1:
R
gfg <-rnorm(500)  a <- rnorm(200)b <- rnorm(100)  plot(density(gfg))lines(density(a), col = "red")lines(density(b), col = "green")  legend("topright", c("gfg", "a", "b"),       col =c("black","red","green"), lty=1)
Output:
Example 2:
R
set.seed(99990)  data<-data.frame(a=round(rnorm(1000,50,50)))data2<-data.frame(b=round(rnorm(600,30,30)))data3<-data.frame(c=round(rnorm(300,10,10)))  hist(data$a, col="#abf5bf",main="overlaying histogram")hist(data2$b, col="#52d977", add=T)hist(data3$c, col="#669172", add=T)
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
list reverse function in C++ STL

14 Jun, 2022
The list::reverse() is a built-in function in C++ STL which is used to reverse a list container. It reverses the order of elements in the list container. Syntax:
list_name.reverse()
Parameters: This function does not accept any parameters. Return Value: This function does not return any value. It just reverses the order of elements in the list container with which it is used. Below program illustrate the list::reverse() function in C++ STL: 
CPP
// CPP program to illustrate the// list::reverse() function#include <bits/stdc++.h>using namespace std; int main(){    // Creating a list    list<int> demoList;     // Adding elements to the list    demoList.push_back(10);    demoList.push_back(20);    demoList.push_back(30);    demoList.push_back(40);     // Initial list:    cout << "Initial List: ";    for (auto itr = demoList.begin(); itr != demoList.end(); itr++)        cout << *itr << " ";     // reversing the list    demoList.reverse();     // List after reversing the order of elements    cout << "\n\nList after reversing: ";    for (auto itr = demoList.begin(); itr != demoList.end(); itr++)        cout << *itr << " ";     return 0;}
Initial List: 10 20 30 40 

List after reversing: 40 30 20 10
Time Complexity – Linear O(N)
utkarshgupta110092
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to delete particular data in a document in MongoDB?

You can use $unset. Let us first create a collection with documents −
> db.demo20.insertOne(
...    {
...
...       "ListOfEmployee" : [
...          {
...             "EmployeeName1" : "John"
...          },
...          {
...             "EmployeeName2" : "Carol"
...          }
...       ],
...       "EmployeeName2" : []
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e138c3555d0fc6657d21f12")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.demo20.find();
This will produce the following output −
{ "_id" : ObjectId("5e138c3555d0fc6657d21f12"), "ListOfEmployee" : [ { "EmployeeName1" : "John" }, { "EmployeeName2" : "Carol" } ], "EmployeeName2" : [ ] }
Following is the query to delete particular data in a document −
> db.demo20.update({ "EmployeeName2": { "$exists": 1 }},{ "$unset": { "EmployeeName2": "" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.demo20.find();
This will produce the following output −
{ "_id" : ObjectId("5e138c3555d0fc6657d21f12"), "ListOfEmployee" : [ { "EmployeeName1" : "John" }, { "EmployeeName2" : "Carol" } ] }
until command in Linux with Examples

27 May, 2019
until command in Linux used to execute a set of commands as long as the final command in the ‘until’ Commands has an exit status which is not zero. It is mostly used where the user needs to execute a set of commands until a condition is true.
Syntax:
until COMMANDS; do COMMANDS; done
Here, if the COMMANDS get evaluated to false then the statements will be executed. If the COMMANDS get evaluated to true then the no statements will be executed and control will go after the done statement.
Example:
Options:
help until : It displays help information.
linux-command
Linux-Shell-Commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java.util.function.IntBinaryOperator interface with Examples

18 Jul, 2019
The IntBinaryOperator interface was introduced in Java 8. It represents an operation on two int values and returns the result as an int value. It is a functional interface and thus can be used as a lambda expression or in a method reference. It is mostly used when the operation needs to be encapsulated from the user.
Methods
applyAsInt(): This function takes two int values, performs the required operation and returns the result as an int.public int applyAsInt(int val1, int val2)

applyAsInt(): This function takes two int values, performs the required operation and returns the result as an int.public int applyAsInt(int val1, int val2)

public int applyAsInt(int val1, int val2)

Example to demonstrate IntBinaryOperator interface as a lambda expression .
// Java program to demonstrate IntBinaryOperator  import java.util.function.IntBinaryOperator;  public class IntBinaryOperatorDemo {    public static void main(String[] args)    {        // Binary operator defined to divide        // factorial of two numbers        IntBinaryOperator binaryOperator = (x, y) ->        {            int fact1 = 1;            for (int i = 2; i <= x; i++) {                fact1 *= i;            }            int fact2 = 1;            for (int i = 2; i <= y; i++) {                fact2 *= i;            }            return fact1 / fact2;        };          System.out.println("5! divided by 7! = "                           + binaryOperator.applyAsInt(5, 7));        System.out.println("7! divided by 5! = "                           + binaryOperator.applyAsInt(7, 5));    }}
5! divided by 7! = 0
7! divided by 5! = 42

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/function/IntBinaryOperator.html
Java - util package
Java-Functional-Interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.moveaxis() function | Python

22 Apr, 2020
numpy.moveaxis() function move axes of an array to new positions. Other axes remain in their original order.
Syntax : numpy.moveaxis(arr, source, destination)Parameters :arr : [ndarray] input array.source : [ int or sequence of int] Original positions of the axes to move. These must be unique.destination : [ int or sequence of int] Destination positions for each of the original axes. These must also be unique.Return : [ndarray] Array with moved axes. This array is a view of the input array.
Code #1 :
# Python program explaining# numpy.moveaxis() function  # importing numpy as geek import numpy as geek  arr = geek.zeros((1, 2, 3, 4))  gfg = geek.moveaxis(arr, 0, -1).shape  print (gfg)
Output :
(2, 3, 4, 1)

 Code #2 :
# Python program explaining# numpy.moveaxis() function  # importing numpy as geek import numpy as geek  arr = geek.zeros((1, 2, 3, 4))  gfg = geek.moveaxis(arr, -1, 0).shape  print (gfg)
Output :
(4, 1, 2, 3)

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to import variables from another file in Python?

03 Mar, 2021
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simple import <library_name>. For example, math library. If we want to use the pi variable we use import math and then math.pi.
To import variables from another file, we have to import that file from the current program. This will provide access to all the methods and variables available in that file.
We can use any Python source file as a module by executing an import statement in some other Python source file. When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module.
Python’s from statement lets you import specific attributes from a module. 
Note: For more information, refer Python Modules
Different approaches to import variables from other file
import <file_name> and then use <file_name>.<variable_name> to access variable
from <file_name> import <variable_names> and use variables
from <file_name> import * and then use variables directly.
Example:
Suppose we have a file named “swaps.py”. We have to import the x and y variable from this file in another file named “calval.py”. 
Python3
# swaps.py file from which variables to be importedx = 23y = 30  def swapVal(x, y):  x,y = y,x  return x, y
Now create a second python file to call the variable from the above code:
Python3
# calval.py file where to import variables# import swaps.py file from which variables # to be imported# swaps.py and calval.py files should be in # same directory.import swaps  # Import x and y variables using # file_name.variable_name notationnew_x = swaps.xnew_y = swaps.y  print("x value: ", new_x, "y value:", new_y)  # Similarly, import swapVal method from swaps filex , y = swaps.swapVal(new_x,new_y)  print("x value: ", x, "y value:", y)
Output:
x value:  23 y value: 30
x value:  30 y value: 23
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Wand polygon() function in Python

10 May, 2020
polygon() function is another drawing function introduced in wand.drawing module. We can draw complex shapes using polygon() function. It takes a list of points in polygons as argument. Stroke line will automatically close between first & last point.
Syntax :
wand.drawing.polygon(points)

Parameters :
Example #1
from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color  with Drawing() as draw:    draw.stroke_width = 2    draw.stroke_color = Color('black')    draw.fill_color = Color('white')      # points list for polygon    points = [(25, 25), (175, 100), (25, 175)]      # draw polygon using polygon() function    draw.polygon(points)    with Image(width = 200, height = 200, background = Color('lightgreen')) as image:        draw(image)        image.save(filename = "polygon.png")
Output :
Example #2:
from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color  with Drawing() as draw:    draw.stroke_width = 2    draw.stroke_color = Color('black')    draw.fill_color = Color('white')      # points list for polygon    points = [(50, 50), (150, 50), (175, 150), (25, 150)]      # draw polygon using polygon() function    draw.polygon(points)    with Image(width = 200, height = 200, background = Color('lightgreen')) as image:        draw(image)        image.save(filename = "polygon2.png")
Output :
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NLP | Flattening Deep Tree

26 Feb, 2019
Some of the corpora that we use are often deep trees of nested phrases. But working on such deep trees is a tedious job for training the chunker. As IOB tag parsing is not designed for nested chunks. So, in order to use these trees for chunker training, we must flatten them.Well, POS (part of Speech) are actually part of the tree structure instead of being in the word. These are used with Tree.pos() method, designed specifically for combining words with preterminal Tree labels such as part-of-speech tags.
Code #1 : Class for flattening the deep tree
from nltk.tree import Tree  def flatten_childtrees(trees):    children = []          for t in trees:        if t.height() < 3:            children.extend(t.pos())                      elif t.height() == 3:            children.append(Tree(t.label(), t.pos()))                      else:            children.extend(                    flatten_childtrees())                  return children    def flatten_deeptree(tree):    return Tree(tree.label(),                 flatten_childtrees())     
 Code #2 : Evaluating flatten_deeptree()
from nltk.corpus import treebankfrom transforms import flatten_deeptree  print ("Deep Tree : \n", treebank.parsed_sents()[0])  print ("\nFlattened Tree : \n",        flatten_deeptree(treebank.parsed_sents()[0]))    
Output :
Deep Tree : 
 (S
  (NP-SBJ
    (NP (NNP Pierre) (NNP Vinken))
    (,, )
    (ADJP (NP (CD 61) (NNS years)) (JJ old))
    (,, ))
  (VP
    (MD will)
    (VP
      (VB join)
      (NP (DT the) (NN board))
      (PP-CLR (IN as) (NP (DT a) (JJ nonexecutive) (NN director)))
      (NP-TMP (NNP Nov.) (CD 29))))
  (. .))

Flattened Tree : 
Tree('S', [Tree('NP', [('Pierre', 'NNP'), ('Vinken', 'NNP')]), (', ',
', '), Tree('NP', [('61', 'CD'), ('years', 'NNS')]), ('old', 'JJ'),
(', ', ', '), ('will', 'MD'), ('join', 'VB'), Tree('NP', [('the',
'DT'), ('board', 'NN')]), ('as', 'IN'), Tree('NP', [('a', 'DT'),
('nonexecutive', 'JJ'), ('director', 'NN')]), Tree('NP-TMP', [('Nov.',
'NNP'), ('29', 'CD')]), ('.', '.')])

The result is a much flatter Tree that only includes NP phrases. Words that are not part of an NP phrase are separated
How it works ?
flatten_deeptree() : returns a new Tree from the given tree by calling flatten_childtrees() on each of the given tree’s children.
flatten_childtrees() : Recursively drills down into the Tree until it finds child trees whose height() is equal to or less than 3.
Code #3 : height()
from nltk.corpus import treebankfrom transforms import flatten_deeptree  from nltk.tree import Tree  print ("Height : ",        Tree('NNP', ['Pierre']).height())  print ("\nHeight : ", Tree(        'NP', [Tree('NNP', ['Pierre']),                     Tree('NNP', ['Vinken'])]). height())
Output :
Height : 2

Height : 3

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.
Optional or() method in Java with examples

30 Jul, 2019
The or() method of java.util.Optional class in Java is used to get this Optional instance if any value is present. If there is no value present in this Optional instance, then this method returns an Optional instance with the value generated from the specified supplier.
Syntax:
public Optional<T> or(Supplier<T> supplier)

Parameters: This method accepts supplier as a parameter of type T to generate an Optional instance with the value generated from the specified supplier.
Return supplier: This method returns this Optional instance, if any value is present. If there is no value present in this Optional instance, then this method returns an Optional instance with the value generated from the specified supplier.
Exception: This method throws NullPointerException if the supplying function is null or produces a null result.
Below programs illustrate or() method:
Note: As this method was added in Java 9, the programs need JDK 9 to execute.
Program 1:
// Java program to demonstrate// Optional.or() method  import java.util.*;import java.util.function.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print supplier        System.out.println("Optional: "                           + op);          // or supplier        System.out.println("Optional by or(() ->"                           + " Optional.of(100)) method: "                           + op.or(() -> Optional.of(100)));    }}
Output:
Optional: Optional[9455]
Optional by or(() -> Optional.of(100)) method: Optional[9455]

Program 2:
// Java program to demonstrate// Optional.or() method  import java.util.*;import java.util.function.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print supplier        System.out.println("Optional: "                           + op);          try {              // or supplier            System.out.println("Optional by or(() ->"                               + " Optional.of(100)) method: "                               + op.or(() -> Optional.of(100)));        }        catch (Exception e) {            System.out.println(e);        }    }}
Output:
Optional: Optional.empty
Optional by or(() -> Optional.of(100)) method: Optional[100]

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#or-java.util.function.Supplier-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove or hide X-axis labels from a Seaborn / Matplotlib plot?

To remove or hide X-axis labels from a Seaborn/Matplotlib plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Use sns.set_style() to set an aesthetic style for the Seaborn plot.
Use sns.set_style() to set an aesthetic style for the Seaborn plot.
Load an example dataset from the online repository (requires Internet).
Load an example dataset from the online repository (requires Internet).
To hide or remove X-axis labels, use set(xlabel=None).
To hide or remove X-axis labels, use set(xlabel=None).
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import seaborn as sns

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

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")

ax = sns.boxplot(x="day", y="total_bill", data=tips)
ax.set(xlabel=None)

plt.show()
Python VLC Instance – Setting Loop on the media

29 Aug, 2020
In this article we will see how we can set loop on the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. Setting loop means that media will get replayed everytime.
In order to do this we will use vlm_set_loop method with the Instance object
Syntax : instance.vlm_set_loop(name, True)
Argument : It takes media name and bool as argument
Return : It returns 0 on success, -1 on error
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating Instance class objectplayer = vlc.Instance()  # creating a new media listmedia_list = player.media_list_new()  # creating a media player objectmedia_player = player.media_list_player_new()  # creating a new mediamedia = player.media_new("death_note.mkv")  # adding media to media listmedia_list.add_media(media)  # setting media list to the mediaplayermedia_player.set_media_list(media_list)  # setting loopplayer.vlm_set_loop("death_note", True)    # start playing videomedia_player.play()    # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output :
Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating Instance class objectplayer = vlc.Instance()  # creating a new media listmedia_list = player.media_list_new()  # creating a media player objectmedia_player = player.media_list_player_new()  # creating a new mediamedia = player.media_new("1.mp4")  # adding media to media listmedia_list.add_media(media)  # setting media list to the mediaplayermedia_player.set_media_list(media_list)  # setting loopplayer.vlm_set_loop("1", True)    # start playing videomedia_player.play()    # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output :
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program that Extract words starting with Vowel From A list

11 Oct, 2020
Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u).
Input : test_list = [“all”, “love”, “get”, “educated”, “by”, “gfg”] Output : [‘all’, ‘educated’] Explanation : a, e are vowels, hence words extracted.Input : test_list = [“all”, “love”, “get”, “educated”, “by”, “agfg”] Output : [‘all’, ‘educated’, ‘agfg’] Explanation : a, e, a are vowels, hence words extracted. 
Method 1 : Using startswith() and loop
In this, we check for each word, and check if it starts with a vowel using startswith() on the first alphabet of every word. The iteration part is done using loop.
Python3
# initializing listtest_list = ["all", "love", "and", "get", "educated", "by", "gfg"]  # printing original listprint("The original list is : " + str(test_list))  res = []vow = "aeiou"for sub in test_list:    flag = False          # checking for begin char    for ele in vow:        if sub.startswith(ele):            flag = True             break    if flag:        res.append(sub)  # printing result print("The extracted words : " + str(res))
Output:
The original list is : [‘all’, ‘love’, ‘and’, ‘get’, ‘educated’, ‘by’, ‘gfg’]The extracted words : [‘all’, ‘and’, ‘educated’]
Method 2 : Using any(), startswith() and loop
In this, we check for vowels using any(), and rest all the functionality is similar to the above method.
Python3
# initializing listtest_list = ["all", "love", "and", "get", "educated", "by", "gfg"]  # printing original listprint("The original list is : " + str(test_list))  res = []vow = "aeiou"for sub in test_list:          # check for vowel beginning    flag = any(sub.startswith(ele) for ele in vow)          if flag:        res.append(sub)  # printing result print("The extracted words : " + str(res))
Output:
The original list is : [‘all’, ‘love’, ‘and’, ‘get’, ‘educated’, ‘by’, ‘gfg’]The extracted words : [‘all’, ‘and’, ‘educated’]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
How to use Skeleton Component in ReactJS ?

08 Apr, 2021
A Skeleton Component is used whenever the data is not loaded, the placeholder preview is to be shown to the user. This component displays a placeholder preview of our content. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use Skeleton Component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Skeleton from "@material-ui/lab/Skeleton";  export default function App() {  return (    <div style={{ display: "block", padding: 30 }}>      <h4>How to use Skeleton Component in ReactJS?</h4>      TEXT VARIANT: <Skeleton variant="text" width={200} />       <br />      RECTANGULAR VARIANT: <Skeleton        variant="rect"        width={110}        height={220}      />{" "}       <br />      CIRCLE VARIANT:         <Skeleton variant="circle"                  width={50} height={50} />{" "}      <br />    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://material-ui.com/components/skeleton/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
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?
Differences between Functional Components and Class Components in React
Why copy constructor argument should be const in C++?

05 Jan, 2022
When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, predict the output of following C++ program. Assume that copy elision is not done by compiler. 
C
#include<iostream>using namespace std; class Test{   /* Class data members */public:   Test(Test &t) { /* Copy data members from t*/}   Test()        { /* Initialize data members */ }}; Test fun(){    cout << "fun() Called\n";    Test t;    return t;} int main(){    Test t1;    Test t2 = fun();    return 0;}
Output: 
 Compiler Error in line "Test t2 = fun();" 
The program looks fine at first look, but it has compiler error. If we add const in copy constructor, the program works fine, i.e., we change copy constructor to following.  
C
Test(const Test &t) { cout << "Copy Constructor Called\n"; }
Or if we change the line “Test t2 = fun();” to following two lines, then also the program works fine. 
C
Test t2;t2 = fun();
In above codes, what’s actually happening?
It gets executed but copy constructor is not called, instead it calls the default constructor where assignment operator is overloaded. Even if we have an explicit overloaded assignment operator, it is not going to call it. 
The function fun() returns by value. So the compiler creates a temporary object which is copied to t2 using copy constructor in the original program (The temporary object is passed as an argument to copy constructor). The reason for compiler error is, compiler created temporary objects cannot be bound to non-const references and the original program tries to do that. It doesn’t make sense to modify compiler created temporary objects as they can die any moment. This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
priyanka panda
cpp-constructor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Gas Station in C++

Suppose there is a circle, and there are n gas stations on the circle. We have two sets of data like −
The amount of gas that every gas stations has
Distance from one gas stations to another.
Calculate the first point, from where a car will be able to complete the circle. Assume for 1 unit of gas, the car can go 1 unit of distance. Suppose there are four gas stations, and the amount of gas, and distance from the next gas stations is as like [(4, 6), (6, 5), (7, 3), (4, 5)], the first point from where car can make a circular tour is 2nd gas stations. Output should be start = 1 (index of second gas stations)
This problem can be solved efficiently using queue. Queue will be used to store the current tour. We will insert the first gas stations into the queue, we will insert gas stations till, we either complete the tour, or current amount of gas becomes negative. If the amount becomes negative, then we keep deleting gas stations until it becomes empty.
Let us see the following implementation to get a better understanding −
 Live Demo
#include <iostream>
using namespace std;
class gas {
   public:
      int gas;
      int distance;
};
int findStartIndex(gas stationQueue[], int n) {
   int start_point = 0;
   int end_point = 1;
   int curr_gas = stationQueue [start_point].gas - stationQueue [start_point].distance;
   while (end_point != start_point || curr_gas < 0) {
      while (curr_gas < 0 && start_point != end_point) {
         curr_gas -= stationQueue[start_point].gas - stationQueue [start_point].distance;
         start_point = (start_point + 1) % n;
         if (start_point == 0)
         return -1;
      }
      curr_gas += stationQueue[end_point].gas - stationQueue [end_point].distance;
      end_point = (end_point + 1) % n;
   }
   return start_point;
}
int main() {
   gas gasArray[] = {{4, 6}, {6, 5}, {7, 3}, {4, 5}};
   int n = sizeof(gasArray)/sizeof(gasArray [0]);
   int start = findStartIndex(gasArray, n);
   if(start == -1)
      cout<<"No solution";
   else
      cout<<"Index of first gas station : "<<start;
}
[[4, 6], [6, 5], [7, 3], [4, 5]]
Index of first gas station : 1
How to Install and Run UserRecon Tool? - GeeksforGeeks

05 Oct, 2021
UserRecon tool is used to find usernames across over 75 social networks. It is very useful when you are running an investigation to determine the usage of the same username across different social media platforms such as Twitter, Instagram, MySpace, Youtube, Reddit, WordPress, GitHub, and many more. With the push of a button, an OSINT investigator will be able to find whether the same username exists on different social media networks. It is a very convenient and easy-to-use tool.
Step 1: Open your terminal and type the following command.
git clone https://github.com/issamelferkh/userrecon.git
Step 2: After cloning the tool, change the directory to UserRecon.
cd userrecon
Fig 1: UserRecon cloned and directory changed to UserRecon.
Step 3: Now list all hidden files using ls -la command in your terminal.
ls -la
Step 4: Change the permission of userrecon.sh.
chmod +x userrecon.sh
Step 5: After changing the permission of userrecon.sh, run the tool by the following command.
./userrecon.sh
Fig 2: UserRecon up and running.
After running the tool by the command, ./userrecon.sh, you will see a screen similar to the one shown above. Now just type in the username you want to search and see the magic happens.
Fig 3: Searching username ‘Talha’.
As we can see, UserRecon is searching the username ‘Talha’ on all 75 sites and returning the link if it exists. All this data gets stored in Talha.txt file.
It can be accessed in any text editor. Suppose, we want to open it in vi editors, the command will be:
vi Talha.txt
Fig 4: Talha.txt file opened in vi editor.
We can open any of the links to see the profile on that social media network. To exit from vi editors, press shift + ZQ. As we can see from the above operations UserRecon can be a very useful and time-saving tool if someone wants to search for a username on social medial networks.
how-to-install
Linux-Tools
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Create and Setup Spring Boot Project in Eclipse IDE?
How to Check the OS Version in Linux?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Install Zip and Unzip in Linux? - GeeksforGeeks

06 Oct, 2021
Zip is a command-line compression utility for files and directories. File and folder compression allows for quicker and more reliable file and folder transfer, storage, and email. Unzip, on the other hand, is a program that allows you to decompress files and directories.
zip is used to compress the files to reduce file size and also used as a file package utility. zip is available in many operating systems like Unix, Linux, windows, etc.
If you have limited bandwidth between two servers and want to transfer the files faster, then zip the files and transfer.
The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command.
The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command.
Compression ratios of 2:1 to 3:1 are common for text files. zip has one compression method (deflation) and can also store files without compression. zip automatically chooses the better of the two for each file to be compressed.
The program is useful for packaging a set of files for distribution; for archiving files; and for saving disk space by temporarily compressing unused files or directories.
You can install Zip by running the below command:
$ sudo apt-get install zip
Installing Zip
After installation, use the command to verify that the zip was installed correctly or not.
$ zip
Verify Zip installed properly
Similarly, you can install Unzip by running the below command:
$ sudo apt install unzip
Installing Unzip
After installation, use the command to verify the unzip was installed correctly or not.
$ unzip
Verify Unzip installed properly
The zip and unzip utilities are already pre-installed in newer Linux distros like Ubuntu 20.04 and CentOS 8, so you’re good to go.
how-to-install
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Create and Setup Spring Boot Project in Eclipse IDE?
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Can we override a private or static method in Java

No, we cannot override private or static methods in Java.
Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.
Let us see what happens when we try to override a private method −
 Live Demo
class Parent {
   private void display() {
      System.out.println("Super class");    
   }
}
public class Example extends Parent {
   void display() // trying to override display() {
      System.out.println("Sub class");
   }
   public static void main(String[] args) {
      Parent obj = new Example();
      obj.display();
   }
}
The output is as follows −
Example.java:17: error: display() has private access in Parent
obj.method();
      ^
1 error
The program gives a compile time error showing that display() has private access in Parent class and hence cannot be overridden in the subclass Example.
If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.
Let us see what happens when we try to override a static method in a subclass
 Live Demo
class Parent {
   static void display() {
      System.out.println("Super class");    
   }
}
public class Example extends Parent {
   void display() // trying to override display() {
      System.out.println("Sub class");
   }
   public static void main(String[] args) {
      Parent obj = new Example();
      obj.display();
   }
}
This generates a compile-time error. The output is as follows −
Example.java:10: error: display() in Example cannot override display() in Parent
void display() // trying to override display()
    ^
overridden method is static
1 error
Convert tuple to float value in Python

When it is required to convert a tuple to a float value, the 'join' method, 'float' method, 'str' method and generator expression can be used.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
The 'float' method converts a given element to float data type.
The 'str' method converts the given element into string data type.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = ( 7, 8)

print ("The first tuple is : " )
print(my_tuple_1)

my_result = float('.'.join(str(elem) for elem in my_tuple_1))

print("After converting the tuple to float, the tuple is : ")
print(my_result)
The first tuple is :
(7, 8)
After converting the tuple to float, the tuple is :
7.8
A tuple is defined and is displayed on the console.
The '.' operator and 'join' method is used to join the two elements in the tuple as a decimal number.
This result is assigned to a variable.
It is displayed as output on the console.
What is method overloading in C#?

Two or more than two methods having the same name but different parameters is what we call method overloading in C#.
Method overloading in C# can be performed by changing the number of arguments and the data type of the arguments.
Let’s say you have a function that prints multiplication of numbers, then our overloaded methods will have the same name but different number of arguments −
public static int mulDisplay(int one, int two) { }
public static int mulDisplay(int one, int two, int three) { }
public static int mulDisplay(int one, int two, int three, int four) { }
The following is an example showing how to implement method overloading −
 Live Demo
using System;
public class Demo {
   public static int mulDisplay(int one, int two) {
      return one * two;
   }

   public static int mulDisplay(int one, int two, int three) {
      return one * two * three;
   }

   public static int mulDisplay(int one, int two, int three, int four) {
      return one * two * three * four;
   }
}

public class Program {
   public static void Main() {
      Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15));
      Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20));
      Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7));
   }
}
Multiplication of two numbers: 150
Multiplication of three numbers: 2080
Multiplication of four numbers: 1470
abs() function for complex number in c++ - GeeksforGeeks

10 Oct, 2018
The abs() function for complex number is defined in the complex header file. This function is used to return the absolute value of the complex number z.
Syntax:
template<class T> T abs (const complex<T>& z);

Parameter:
z: It represents the given complex number.
Return: It returns the absolute value of the complex number.
Below programs illustrate the above function:-
Example 1:-
// C++ program to demonstrate// example of abs() function.   #include <bits/stdc++.h>using namespace std;   // driver functionint main (){  // defines the complex number: (5.0+12.0i)  complex<double> complexnumber (5.0, 12.0);     // prints the absolute value of the complex number  cout << "The absolute value of " << complexnumber << " is: ";  cout << abs(complexnumber) << endl;    return 0;}
The absolute value of (5,12) is: 13

Example 2:-
// C++ program to demonstrate// example of abs() function.  #include <bits/stdc++.h>using namespace std;  // driver functionint main (){  // defines the complex number: (4.0+3.0i)  complex<double> complexnumber (4.0, 3.0);    // prints the absolute value of the complex number  cout << "The absolute value of " << complexnumber << " is: ";  cout << abs(complexnumber) << endl;      return 0;}
The absolute value of (4,3) is: 5

C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to implement Singly Linked List in C++ using class
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Difference between user defined function and library function in C/C++
Handling the Divide by Zero Exception in C++
Different ways to print elements of vector
Dynamic _Cast in C++
Count substrings that contain all vowels | SET 2
Base class pointer pointing to derived class object
What is APP_BASE_HREF in Angular 10 ?

13 Apr, 2021
In this article, we are going to see what is APP_BASE_HREF in Angular 10 and how to use it.
APP_BASE_HREF returns a predefined DI token for the base href of the current page. The APP_BASE_HREF is the URL prefix that should be preserved.
Syntax:
 provide: APP_BASE_HREF, useValue: '/gfgapp'
Approach: 
In app.module.ts and APP_BASE_HREF in providers with useValue.
In app.component.ts store APP_BASE_HREF into any variable and use it.
 
Example 1:
app.module.ts
Javascript
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';  import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import {APP_BASE_HREF} from '@angular/common';  @NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    AppRoutingModule  ],  providers: [ {provide: APP_BASE_HREF, useValue: '/gfgapp'} ],  bootstrap: [AppComponent]})export class AppModule { }
app.component.ts
Javascript
import { Component, Inject } from '@angular/core';import {APP_BASE_HREF} from '@angular/common';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  title = 'demo1';  constructor(@Inject(APP_BASE_HREF) private baseHref:string) {    var a = this.baseHref;    console.log(a, " is base HREF")  }    }
Output:
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to setup 404 page in angular routing ?
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 ?