code-rag-bench/online-tutorials huggingface dataset:
How to use Badge Component in ReactJS?

05 Mar, 2021
Badge generates a small badge to the top-right of its children component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Badge Component in ReactJS using the following approach.
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 modules using the following command.
npm install @material-ui/core
npm install @material-ui/icons
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 MailIcon from '@material-ui/icons/Mail';import Badge from '@material-ui/core/Badge';  export default function App() {    return (     <div style={{display: 'block', padding: 30}}>      <h4>How to use Badge Component in ReactJS?</h4>      <Badge badgeContent={4}       color="primary">        <MailIcon />      </Badge>    </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/badges/
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 useNavigate() Hook
How to Use Bootstrap with React?
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
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
How to load a TSV file into a Pandas DataFrame? - GeeksforGeeks

18 Oct, 2021
In this article, we will discuss how to load a TSV file into a Pandas Dataframe.
The idea is extremely simple we only have to first import all the required libraries and then load the data set by the use of read_csv() method. To this method simply the path of the dataframe is passed. This is enough to get the job done.
Syntax :
pandas.read_csv(path, sep=’\t’)
Given below are some implementations for the same.
Example 1: Loading a TSV dataset into pandas dataframe
Dataset Used:  data.tsv
Python3
import pandas as pd  # Data.tsv is stored locally in the # same directory as of this python filedf = pd.read_csv('data.tsv',sep = '\t') df
Output:
Example 2: Loading a TSV dataset into pandas dataframe
Dataset used: babynames.tsv
Python3
import pandas as pd  df = pd.read_csv('babynames.tsv', sep = '\t')df
Output:
Picked
Python pandas-dataFrame
Python pandas-io
Python-pandas
TrueGeek-2021
Python
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Types of Internet Protocols
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
\texttt - Tex Command

\texttt - Used to produce text-mode material in typewriter  font within a mathematical expression.
{ \texttt #1}
\texttt command is used to produce text-mode material in typewriter font within a mathematical expression.

\texttt{\alpha in texttt mode }\alpha

\alpha in texttt mode α



\texttt{\alpha in texttt mode }\alpha

\alpha in texttt mode α


\texttt{\alpha in texttt mode }\alpha

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Arduino - Ultrasonic Sensor

The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module.
Power Supply − +5V DC
Quiescent Current − <2mA
Working Current − 15mA
Effectual Angle − <15°
Ranging Distance − 2cm – 400 cm/1′′ – 13ft
Resolution − 0.3 cm
Measuring Angle − 30 degree
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × ULTRASONIC Sensor (HC-SR04)
Follow the circuit diagram and make the connections as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor

void setup() {
   Serial.begin(9600); // Starting Serial Terminal
}

void loop() {
   long duration, inches, cm;
   pinMode(pingPin, OUTPUT);
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(pingPin, LOW);
   pinMode(echoPin, INPUT);
   duration = pulseIn(echoPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches);
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(100);
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}
The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as follows −
Connect the +5V pin to +5v on your Arduino board.
Connect Trigger to digital pin 7 on your Arduino board.
Connect Echo to digital pin 6 on your Arduino board.
Connect GND with GND on Arduino.
In our program, we have displayed the distance measured by the sensor in inches and cm via the serial port.
You will see the distance measured by sensor in inches and cm on Arduino serial monitor.
Select Columns with Specific Data Types in Pandas Dataframe

02 Dec, 2020
In this article, we will see how to select columns with specific data types from a dataframe. This operation can be performed using the DataFrame.select_dtypes() method in pandas module.
Syntax: DataFrame.select_dtypes(include=None, exclude=None)Parameters : include, exclude : A selection of dtypes or strings to be included/excluded. At least one of these parameters must be supplied.Return : The subset of the frame including the dtypes in include and excluding the dtypes in exclude.
Step-by-step Approach:
First, import modules then load the dataset.
Python3
# import required moduleimport pandas as pd  # assign datasetdf = pd.read_csv("train.csv")
Then we will find types of data present in our dataset using dataframe.info() method.
Python3
# display description# of the datasetdf.info()
Output:
Now, we will use DataFrame.select_dtypes() to select a specific datatype.
Python3
# store columns with specific data typeinteger_columns = df.select_dtypes(include=['int64']).columnsfloat_columns = df.select_dtypes(include=['float64']).columnsobject_columns = df.select_dtypes(include=['object']).columns
Finally, display the column having a particular data type.
Python3
# display columnsprint('\nint64 columns:\n', integer_columns)print('\nfloat64 columns:\n', float_columns)print('\nobject columns:\n', object_columns)
Output:
Below is the complete program based on the above approach:
Python3
# import required moduleimport pandas as pd  # assign datasetdf = pd.read_csv("train.csv")  # store columns with specific data typeinteger_columns = df.select_dtypes(include=['int64']).columnsfloat_columns = df.select_dtypes(include=['float64']).columnsobject_columns = df.select_dtypes(include=['object']).columns  # display columnsprint('\nint64 columns:\n',integer_columns)print('\nfloat64 columns:\n',float_columns)print('\nobject columns:\n',object_columns)
Output:
Example:
Here we are going to extract columns of the below dataset:
Python3
# import required moduleimport pandas as pdfrom vega_datasets import data  # assign datasetdf = data.seattle_weather()  # display datasetdf.sample(10)
Output:
Now, we are going to display all the columns having float64 as the data type.
Python3
# import required moduleimport pandas as pdfrom vega_datasets import data  # assign datasetdf = data.seattle_weather()  # display description# of datasetdf.info()  # store columns with specific data typecolumns = df.select_dtypes(include=['float64']).columns  # display columnsprint('\nColumns:\n', columns)
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python IMDbPY – Getting movie ID from searched movies

22 Apr, 2020
In this article we will see how we can get the movie id from searched movies, movie id is basically unique id given to each movie as movie name can be same but id will be distinct. We use search_movie method to search movies with the same name.
In order to get movie id we use movieID method.
Syntax : movies[0].movieID
Here movies is the list of movies returned by search_movie and movies[0] refer to first element in list
Argument : It takes no argument.
Return : It return string which is Movie ID
Below is the implementation.
# importing the moduleimport imdb   # creating instance of IMDbia = imdb.IMDb()   # name name = "Udta punjab"   # searching the name search = ia.search_movie(name)    # loop for printing the name and idfor i in range(len(search)):          # getting the id    id = search[i].movieID          # printing it    print(search[i]['title'] + " : " + id )
Output :
Udta Punjab : 4434004
Diljit Dosanjh (Udta Punjab) : 6574338

Another example :
# importing the moduleimport imdb   # creating instance of IMDbia = imdb.IMDb()   # name name = "3 idiots"   # searching the name search = ia.search_movie(name)    # loop for printing the name and idfor i in range(len(search)):          # getting the id    id = search[i].movieID          # printing it    print(search[i]['title'] + " : " + id )
Output :
3 Idiots : 1187043
3 idiotas : 3685624
3 Idiots : 12049418
3 Idiots w/ GUNS : 0222441
3 Idiots on Wheels : 6689378
3 Idiots Try Candy! : 8474256
3 Idiots; How Cho Copes with Slump : 9419952
The Idiots : 0154421
Idiots : 0341476
Vidiots : 5830890
Idiotest : 3607166
Idiotsitter : 3532050
The Idiot : 0043614
Idioten : 7147976
Idiots : 1687235
4 Idiots : 6470848
Idiots : 2622956
The Idiot : 0051762
Idiots : 6866900
Idiot : 0366028

Python IMDbPY-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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
The CSS3 rotate3d() Function

The rotate3d() function in CSS is used to rotate an element in 3D space. Set the amount and angle of rotation as parameter of rotate3d().
Let us see an example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
   transform: rotate3d(1, 1, 1, 45deg);
}
.skew_img {
   transform-origin: left;
   transform: skew(-0.10turn, 30deg);
}
</style>
</head>
<body>
<h1>Learn</h1>
<img class="demo" src=
"https://www.tutorialspoint.com/numpy/images/numpy-mini-logo.jpg"
alt="Numpy">
<img class="skew_img" src=
"https://www.tutorialspoint.com/apache_spark/images/apache-spark-mini-logo.jpg"
alt="Apache Spark">
</body>
</html>
Let us now see another example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
   transform: rotate3d(1, 2, 0, 30deg);
   color: red;
   font-family: sans-serif;
   font-size: 30px;
}
.skew_img {
   transform-origin: left;
   transform: skew(-0.10turn, 30deg);
}
</style>
</head>
<body>
<h1>Learn</h1>
<p class="demo">Learn Apache Spark</p>
<img class="skew_img" src=
"https://www.tutorialspoint.com/apache_spark/images/apache-spark-mini-logo.jpg"
alt="Apache Spark">
</body>
</html>
Python BeautifulSoup – find all class

26 Nov, 2020
Prerequisite:- Requests , BeautifulSoup
The task is to write a program to find all the classes for a given Website URL. In Beautiful Soup there is no in-built method to find all classes.
Module needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4


requests:  Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
pip install requests


Methods #1: Finding the class in a given HTML document.
Approach:
Create an HTML doc.
Import module.
Parse the content into BeautifulSoup.
Iterate the data by class name.
Code:
Python3
# html codehtml_doc = """<html><head><title>Welcome  to geeksforgeeks</title></head><body><p class="title"><b>Geeks</b></p>    <p class="body">geeksforgeeks a computer science portal for geeks</body>"""  # import modulefrom bs4 import BeautifulSoup  # parse html contentsoup = BeautifulSoup( html_doc , 'html.parser')  # Finding by class namesoup.find( class_ = "body" )
Output:
<p class="body">geeksforgeeks a computer science portal for geeks
</p>
 
Methods #2: Below is the program to find all class in a URL.
Approach:
Import module
Make requests instance and pass into URL
Pass the requests into a Beautifulsoup() function
Then we will iterate all tags and fetch class name
Code:
Python3
# Import Modulefrom bs4 import BeautifulSoupimport requests  # Website URLURL = 'https://www.geeksforgeeks.org/'  # class list setclass_list = set()  # Page content from Website URLpage = requests.get( URL )  # parse html contentsoup = BeautifulSoup( page.content , 'html.parser')  # get all tagstags = {tag.name for tag in soup.find_all()}  # iterate all tagsfor tag in tags:      # find all element of tag    for i in soup.find_all( tag ):          # if tag has attribute of class        if i.has_attr( "class" ):              if len( i['class'] ) != 0:                class_list.add(" ".join( i['class']))  print( class_list )
Output:
Technical Scripter 2020
Web-scraping
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Slicing range() function in Python

03 Nov, 2021
range() allows users to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes mainly three arguments.
start: integer starting from which the sequence of integers is to be returned
stop: integer before which the sequence of integers is to be returned.The range of integers end at stop – 1.
step: integer value which determines the increment between each integer in the sequence
Note: For more information, refer to Python range() function
Example:
# Python Program to  # show range() basics     # printing a number for i in range(10):     print(i, end =" ") print()
Output:
0 1 2 3 4 5 6 7 8 9 
In Python, range objects are not iterators but are iterables. So slicing a range() function does not return an iterator but returns an iterable instead.
Example:
# Python program to demonstrate# slicing of range function    a = range(100)  # Slicing range functionans = a[:50]print(ans)
Output:
range(0, 50)
Now our new range ‘ans’ has numbers from 0 to 50 (50 exclusive). So a generalization for understanding this is 
a[start : end : the difference between numbers]
So doing something like ans = a[10:89:3] will have a range of numbers starting from 10 till 89 with a difference of 3 in between them. 
Example:
# Python program to demonstrate# slicing of range function    a = range(100)  # Slicing range functionans = a[10:89:3]print(ans)  ans = a[::5]print(ans)
Output:
range(10, 89, 3)
range(0, 100, 5)
contactmm
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
XML - Tags

Let us learn about one of the most important part of XML, the XML tags. XML tags form the foundation of XML. They define the scope of an element in XML. They can also be used to insert comments, declare settings required for parsing the environment, and to insert special instructions.
We can broadly categorize XML tags as follows −
The beginning of every non-empty XML element is marked by a start-tag. Following is an
example of start-tag −
<address>

Every element that has a start tag should end with an end-tag. Following is an example of end-tag −
</address>

Note, that the end tags include a solidus ("/") before the name of an element.
The text that appears between start-tag and end-tag is called content. An element which has no content is termed as empty. An empty element can be represented in two ways as follows −
A start-tag immediately followed by an end-tag as shown below −
<hr></hr>
A complete empty-element tag is as shown below −
<hr />
Empty-element tags may be used for any element which has no content.
Following are the rules that need to be followed to use XML tags −
XML tags are case-sensitive. Following line of code is an example of wrong syntax </Address>, because of the case difference in two tags, which is treated as erroneous syntax in XML.
<address>This is wrong syntax</Address>
Following code shows a correct way, where we use the same case to name the start and the end tag.
<address>This is correct syntax</address>
XML tags must be closed in an appropriate order, i.e., an XML tag opened inside another element must be closed before the outer element is closed. For example −
<outer_element>
   <internal_element>
      This tag is closed before the outer_element
   </internal_element>
</outer_element>

    84 Lectures 
     6 hours 

 Frahaan Hussain

    29 Lectures 
     2 hours 

 YouAccel

    27 Lectures 
     1 hours 

 Jordan Stanchev

    16 Lectures 
     2 hours 

 Simon Sez IT
 Print
 Add Notes
 Bookmark this page
fseek() in C/C++ with example - GeeksforGeeks

02 Jun, 2017
fseek() is used to move file pointer associated with a given file to a specific position.Syntax:
int fseek(FILE *pointer, long int offset, int position)
pointer: pointer to a FILE object that identifies the stream.
offset: number of bytes to offset from position
position: position from where offset is added.

returns:
zero if successful, or else it returns a non-zero value 

position defines the point with respect to which the file pointer needs to be moved. It has three values:SEEK_END : It denotes end of the file.SEEK_SET : It denotes starting of the file.SEEK_CUR : It denotes file pointer’s current position.
// C Program to demonstrate the use of fseek()#include <stdio.h>  int main(){    FILE *fp;    fp = fopen("test.txt", "r");          // Moving pointer to end    fseek(fp, 0, SEEK_END);          // Printing position of pointer    printf("%ld", ftell(fp));      return 0;}
Output:
81

Explanation
The file test.txt contains the following text:
"Someone over there is calling you.
we are going for work.
take care of yourself."
When we implement fseek() we move the pointer by 0 distance with respect to end of file i.e pointer now points to end of the file. Therefore the output is 81.
Related article: fseek vs rewind in C
This article is contributed by Hardik Gaur. 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.
C-File Handling
C-Library
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Function Pointer in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Java throw Keyword

❮ Java Keywords

Throw an exception if age is below 18 (print "Access 
denied"). If age is 18 or older, print "Access granted":
public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}


Try it Yourself »

The throw keyword is used to create a custom error.
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
The exception type is often used together with a custom method, like in the example above.
Differences between throw and throws:
throw is followed by an object (new type)
used inside the method
throws is followed by a class
and used with the method signature
Read more about exceptions in our Java Try..Catch Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
C++ function call by pointer

The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by pointer, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function  swap(), which exchanges the values of the two integer variables pointed to by its arguments.
// function definition to swap the values.
void swap(int *x, int *y) {
   int temp;
   temp = *x; /* save the value at address x */
   *x = *y; /* put y into x */
   *y = temp; /* put x into y */
  
   return;
}
To check the more detail about C++ pointers, kindly check C++ Pointers chapter.
For now, let us call the function swap() by passing values by pointer as in the following example −
#include <iostream>
using namespace std;

// function declaration
void swap(int *x, int *y);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

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

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}
When the above code is put together in a file, compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Python | Equidistant element list - GeeksforGeeks

03 Oct, 2019
Sometimes, while working with Python list we can have a problem in which we need to construct the list in which the range is auto computed using the start, end and length parameters. The solution of this problem can have many applications. Let’s discuss a way in which this task can be performed.
Method : Using list comprehensionThis task can be performed using list comprehension, shorthand for the loop version of logic. In this, we just compute the range using division manipulation and extend it to increasing list forming equidistant list.
# Python3 code to demonstrate working of# Equidistant element list# using list comprehension  # initializing start value strt = 5  # initializing end value end = 10  # initializing lengthlength = 8  # Equidistant element list# using list comprehensiontest_list = [strt + x * (end - strt)/length for x in range(length)]  # Printing resultprint("The Equidistant list is : " + str(test_list))
 
The Equidistant list is : [5.0, 5.625, 6.25, 6.875, 7.5, 8.125, 8.75, 9.375]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
How to dynamically update a plot in a loop in Ipython notebook?

We can iterate a plot using display.clear_output(wait=True), display.display(pl.gcf()) and time.sleep() methods in a loop to get the exact output.
Plot a sample (or samples) from the "standard normal" distribution using pylab.randn().
Plot a sample (or samples) from the "standard normal" distribution using pylab.randn().
Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it.
Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it.
Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure.
Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure.
To sleep for a while, use time.sleep() method.
To sleep for a while, use time.sleep() method.
import time
import pylab as pl
from IPython import display
for i in range(2):
   pl.plot(pl.randn(100))
   display.clear_output(wait=True)
   display.display(pl.gcf())
   time.sleep(1.0)
Figure(640x480)
Figure(640x480)
How to Get the Current Working Directory in Golang? - GeeksforGeeks

10 May, 2020
Getwd functionis used to get the current working directory in Golang, the function returns the rooted path name and if the current directory can be reached via multiple paths, the function can return any one of them.
Syntax:
func Getwd()(dir string, err error)
The func returns two things the directory and also error, if there is no error it returns nil.
// Golang code for printing// current working directory  package main  import (    "fmt"    "os")  func main() {      // using the function    mydir, err := os.Getwd()    if err != nil {        fmt.Println(err)    }    fmt.Println(mydir)}
Output:
users/home/desktop
You may get different outputs on online compilers. For better understanding, use the offline compiler.
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Loops in Go Language
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
C | Structure & Union | Question 5 - GeeksforGeeks

28 Jun, 2021
#include<stdio.h> struct st {     int x;     struct st next; };     int main() {     struct st temp;     temp.x = 10;     temp.next = temp;     printf("%d", temp.next.x);     return 0; }
(A) Compiler Error(B) 10(C) Runtime Error(D) Garbage ValueAnswer: (A)Explanation: A structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of structQuiz of this Question
C-Structure & Union
Structure & Union
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Function Pointer in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 5
C | File Handling | Question 1
C | Dynamic Memory Allocation | Question 5
Removing duplicate elements from an array in PHP

The ‘array_flip’ function can be used, that will reverse the values as indices and keys as values.
 Live Demo
<?php
   $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68);
   echo "The original array contains \n";
   print_r($my_arr);
   $my_arr = array_flip($my_arr);
   $my_arr = array_flip($my_arr);
   $my_arr= array_values($my_arr);
   echo "\n The array after removing duplicate elements is \n ";
   print_r($my_arr);
?>
The original array contains
Array
(
   [0] => 45
   [1] => 65
   [2] => 67
   [3] => 99
   [4] => 81
   [5] => 90
   [6] => 99
   [7] => 45
   [8] => 68
)

The array after removing duplicate elements is
Array
(
   [0] => 45
   [1] => 65
   [2] => 67
   [3] => 99
   [4] => 81
   [5] => 90
   [6] => 68
)
An array is defined and duplicate elements from the array can be found and removed using the ‘array_flip’ function, that basically reverses the keys/index as values and values as keys. This way, the value that is repeated comes twice in the index and one of them is removed since indices have to be unique. Again, the ‘array_flip’ function is used to get the array back to the original form.
JavaScript String - link() Method

This method creates an HTML hypertext link that requests another URL.
The syntax for link() method is as follows −
string.link( hrefname )

hrefname − Any string that specifies the HREF of the A tag; it should be a valid URL.
Returns the string with <a> tag.
Try the following example.
<html>
   <head>
      <title>JavaScript String link() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String("Hello world");
         var URL = "http://www.tutorialspoint.com";         
         alert(str.link( URL ));
      </script>      
   </body>
</html>
<a href = "http://www.tutorialspoint.com">Hello world</a>


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to increase the font size of the legend in my Seaborn plot using Matplotlib?

To increase the font size of the legend in a Seaborn plot, we can use the fontsize variable and can use it in legend() method argument.
Create a data frame using Pandas. The keys are number, count, and select.
Create a data frame using Pandas. The keys are number, count, and select.
Plot a bar in Seaborn using barplot() method.
Plot a bar in Seaborn using barplot() method.
Initialize a variable fontsize to increase the fontsize of the legend.
Initialize a variable fontsize to increase the fontsize of the legend.
Use legend() method to place legend on the figure with fontsize in the argument.
Use legend() method to place legend on the figure with fontsize in the argument.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas
import matplotlib.pylab as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pandas.DataFrame(dict(
   number=[2, 5, 1, 6, 3],
   count=[56, 21, 34, 36, 12],
   select=[29, 13, 17, 21, 8]
))
bar_plot1 = sns.barplot(x='number', y='count', data=df, label="count", color="red")
bar_plot2 = sns.barplot(x='number', y='select', data=df, label="select", color="green")
fontsize = 20
plt.legend(loc="upper right", frameon=True, fontsize=fontsize)
plt.show()
ftp_connect() function in PHP

The ftp_connect() function opens an FTB connection.
ftp_connect(host,port,timeout);
host − The FTP server to connect to
host − The FTP server to connect to
port − The port of the FTP server. The default is 21. The host can be a domain or IP address.
port − The port of the FTP server. The default is 21. The host can be a domain or IP address.
timeout − The timeout for network operation
timeout − The timeout for network operation
The ftp_connect() function returns an FTP stream on success or FALSE on error
The following is an example: to open an FTP connection, to work in it and closing it.
<?php
   $ftp_server="192.168.0.4";
   $ftp_user="amit";
   $ftp_pass="tywg61gh";
   $con = ftp_connect($ftp_server);  
   $res = ftp_login($con, $ftp_user, $ftp_pass);
   ftp_chdir($con, 'demo');
   echo ftp_pwd($con);
   if (ftp_cdup($con)) {
      echo "Directory changed!\n";
   } else {
      echo "Directory change not successful!\n";
   }
   echo ftp_pwd($con);
   ftp_close($con);
?>
Addition of two number using ‘-‘ operator?

Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform the operation on the user-defined data type. For example, '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation), etc.
Input
10 20
20 30
Output
30
50
To perform addition of two numbers using ‘-‘ operator by Operator overloading. Binary operators will require one object as an argument so they can perform the operation. If we are using Friend functions here then it will need two arguments.
The operator is being invoked: ob1-ob2. The object before the operator will invoke the function and the object after the operator will be passed as an argument to the function. So, in this case, ob1 is invoking object and ob2 is passed as an argument to the function.
We are passing 10, 20 as the values of ob1’s x and y and 20, 30 as the values of ob2’s x and y.
#include <iostream>
using namespace std;
class sum {
   public:
      int x, y, z;
   void getdata(int a, int b) {
      x=a;
      y=b;
   }
   void display() {
      cout<<"\nSum of X:"<<x;
      cout<<"\nSum of Y:"<<y;
   }
   void operator-(sum &);
};
void sum::operator-(sum &ob) {
   x=x+ob.x;
   y=y+ob.y;
   display();
}
int main() {
   sum ob1, ob2;
   ob1.getdata(10,20);
   ob2.getdata(20,30);
   ob1-ob2;
}
How to add a character to the beginning of every word in a string in JavaScript?

We are required to write a function that takes in two strings, we have to return a new string
which is just the same as the first of the two arguments but have second argument prepended
to its every word.
For example −
Input → ‘hello stranger, how are you’, ‘@@’
Output → ‘@@hello @@stranger, @@how @@are @@you’
If second argument is not provided, take ‘#’ as default.
const str = 'hello stranger, how are you';
const prependString = (str, text = '#') => {
   return str
   .split(" ")
   .map(word => `${text}${word}`)
      .join(" ");
};
console.log(prependString(str));
console.log(prependString(str, '43'));
The output in the console will be −
#hello #stranger, #how #are #you
43hello 43stranger, 43how 43are 43you
Group by function in R using Dplyr - GeeksforGeeks

31 Aug, 2021
Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames. Group_by() function alone will not give any output. It should be followed by summarise() function with an appropriate action to perform. It works similar to GROUP BY in SQL and pivot table in excel.
Syntax:
group_by(col,...)
Syntax:
group_by(col,..) %>% summarise(action)
The dataset in use:
Sample_Superstore
This is the simplest way by which a column can be grouped, just pass the name of the column to be grouped in the group_by() function and the action to be performed on this grouped column in summarise() function.
Example: Grouping single column by group_by()
R
library(dplyr) df = read.csv("Sample_Superstore.csv") df_grp_region = df %>% group_by(Region)  %>%                    summarise(total_sales = sum(Sales),                              total_profits = sum(Profit),                              .groups = 'drop') View(df_grp_region)
Output:
 
Group_by() function can also be performed on two or more columns, the column names need to be in the correct order. The grouping will occur according to the first column name in the group_by function and then the grouping will be done according to the second column.
Example: Grouping multiple columns
R
library(dplyr) df = read.csv("Sample_Superstore.csv") df_grp_reg_cat = df %>% group_by(Region, Category) %>%                   summarise(total_Sales = sum(Sales),                             total_Profit = sum(Profit),                             .groups = 'drop') View(df_grp_reg_cat)
Output:
We can also calculate mean, count, minimum or maximum by replacing the sum in the summarise or aggregate function. For example, we will find mean sales and profits for the same group_by example above.
Example: 
R
library(dplyr) df = read.csv("Sample_Superstore.csv") df_grp_reg_cat = df %>% group_by(Region, Category) %>%                   summarise(mean_Sales = mean(Sales),                             mean_Profit = mean(Profit),                             .groups = 'drop') View(df_grp_reg_cat)
Output:
pasulakiransai
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Printing Output of an R Program
Logistic Regression in R Programming
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
C++ Program for Common Divisors of Two Numbers?

Here we will see how we can get the number of common divisors of two numbers. We are not going to find all common divisors, but we will count how many common divisors are there. If two numbers are like 12 and 24, then common divisors are 1, 2, 3, 4, 6, 12. So there are 6 common divisors, so the answer will be 6.
begin
   count := 0
   gcd := gcd of a and b
   for i := 1 to square root of gcd, do
      if gcd is divisible by 0, then
         if gcd / i = i, then
            count := count + 1
         else
            count := count + 2
         enf if
      end if
   done
   return count
end
 Live Demo
#include<iostream>
#include<cmath>
using namespace std;
int gcd(int a, int b) {
   if (a == 0)
      return b;
   return gcd(b%a, a);
}
int countCommonDivisors(int a,int b) {
   int gcd_val = gcd(a, b); //get gcd of a and b
   int count = 0;
   for (int i=1; i<=sqrt(gcd_val); i++) {
      if (gcd_val%i==0) { // when'i' is factor of n
         if (gcd_val/i == i) //if two numbers are same
            count += 1;
         else
            count += 2;
      }
   }
   return count;
}
main() {
   int a = 12, b = 24;
   cout << "Total common divisors: " << countCommonDivisors(a, b);
}
The differences array: 6 5 10 1
Create date from day, month, year fields in MySQL?

You can use in-built function STR_TO_DATE() from MySQL. The syntax is as follows −
SELECT
STR_TO_DATE(CONCAT(yourYearColumName,'-',LPAD(yourMonthColumName,2,'00'),'-',LPAD(yourDayColumName,2,'00')), '%Y-%m-%d') as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table DateCreateDemo
   −> (
   −> `Day` varchar(2),
   −> `Month` varchar(2),
   −> `Year` varchar(4)
   −> );
Query OK, 0 rows affected (1.68 sec)
Insert values for all fields using insert command. The query is as follows −
mysql> insert into DateCreateDemo values('15','12','2018');
Query OK, 1 row affected (0.09 sec)

mysql> insert into DateCreateDemo values('10','11','2016');
Query OK, 1 row affected (0.37 sec)

mysql> insert into DateCreateDemo values('12','6','2017');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DateCreateDemo values('9','8','2019');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DateCreateDemo values('10','5','2020');
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from DateCreateDemo;
The following is the output −
+------+-------+------+
| Day  | Month | Year |
+------+-------+------+
| 15   | 12    | 2018 |
| 10   | 11    | 2016 |
| 12   | 6     | 2017 |
| 9    | 8     | 2019 |
| 10   | 5     | 2020 |
+------+-------+------+
5 rows in set (0.00 sec)
Create a date using the above three fields which is ‘Day’,’Month’ and ‘Year’. The query is as follows −
mysql> select
   −> STR_TO_DATE(CONCAT(Year,'-',LPAD(Month,2,'00'),'-',LPAD(day,2,'00')), '%Y-%m-%d') as DateDemo from DateCreateDemo;
The following is the output −
+------------+
| DateDemo   |
+------------+
| 2018-12-15 |
| 2016-11-10 |
| 2017-06-12 |
| 2019-08-09 |
| 2020-05-10 |
+------------+
5 rows in set (0.06 sec)
How to sort a column of a Pandas DataFrame?

To sort a column in a Pandas DataFrame, we can use the sort_values() method.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print input DataFrame, df.
Print input DataFrame, df.
Initialize a variable col to sort the column.
Initialize a variable col to sort the column.
Print the sorted DataFrame.
Print the sorted DataFrame.
 Live Demo
import pandas as pd

df = pd.DataFrame(
   {
     "x": [5, 2, 7, 0],
     "y": [4, 10, 5, 1],
    `"z": [9, 3, 5, 1]
  }
)

print "Input DataFrame is:\n", df
col = "x"
df = df[col].sort_values(ascending=False)
print "After sorting column ", col, "DataFrame is:\n", df
Input DataFrame is:
   x  y  z
0  5  4  9
1  2 10  3
2  7  5  5
3  0  1  1
After sorting column x DataFrame is:
2  7
0  5
1  2
3  0
Name: x, dtype: int64
Write a power (pow) function using C++

The power function is used to find the power given two numbers that are the base and exponent. The result is the base raised to the power of the exponent.
An example that demonstrates this is as follows −
Base = 2
Exponent = 5

2^5 = 32

Hence, 2 raised to the power 5 is 32.
A program that demonstrates the power function in C++ is given as follows −
 Live Demo
#include
using namespace std;

int main(){
   int x, y, ans = 1;

   cout << "Enter the base value: \n";
   cin >> x;

   cout << "Enter the exponent value: \n";
   cin >> y;

   for(int i=0; i<y; i++)
   ans *= x;

   cout << x <<" raised to the power "<< y <<" is "<&;lt;ans;

   return 0;
}
The output of the above program is as follows −
Enter the base value: 3
Enter the exponent value: 4
3 raised to the power 4 is 81
Now let us understand the above program.
The values of base and exponent are obtained from the user. The code snippet that shows this is as follows −
cout << "Enter the base value: \n";
cin >> x;

cout << "Enter the exponent value: \n";
cin >> y;
The power is calculated using the for loop that runs till the value of the exponent. In each pass, the base value is multiplied with ans. After the completion of the for loop, the final value of power is stored in the variable ans. The code snippet that shows this is as follows −
for(int i=0; i<y; i++)
ans *= x;
Finally, the value of the power is displayed. The code snippet that shows this is as follows −
cout << x <<" raised to the power "<< y <<" is "<<ans;