code-rag-bench/online-tutorials huggingface dataset:
What is the difference between ++i and i++ in c?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. 
That means both i++ and ++i will be equivalent.
i=5;
i++;
printf("%d",i);
and 
i=5
++i;
printf("%d",i);
both will make i=6.
However, when increment expression is used along with assignment operator, then operator precedence will come into picture. 
i=5;
j=i++;
In this case, precedence of = is higher than postfix ++. So, value of i is assigned to i before incrementing i. Here j becomes 5 and i becomes 6.
i=5;
j=++i;
In this case, precedence of prefix ++ is more than = operator. So i will increment first and the incremented value is assigned to j Here i and j both become 6.
#include <stdio.h>
int main() {
   int i=5,j;
   j=i++;
   printf ("\nafter postfix increment i=%d j=%d", i,j);
   i=5;
   j=++i;
   printf ("\n after prefix increment i=%d j=%d",i,j);
   return 0;
}
The output is
after postfix increment i=6 j=5
 after prefix increment i=6 j=6
How can I use Python regex to split a string by multiple delimiters?

The following code uses Python regex to split the given string by multiple deliimiters
import re
s = 'Beautiful; Soup\n is, good: Python* application'
result = re.split('; |, |\*|\n|:',s)
print result
This gives the output
['Beautiful', 'Soup', ' is', 'good', ' Python', ' application']
MySQL: What is 'AUTO_INCREMENT=5' in a create table query?

The AUTO_INCREMENT=5 in a create table query tells that the first record will start from 5 i.e. not default 1. As we know if you do not set the value to AUTO_INCREMENT then MySQL starts from 1 by default.
The syntax is as follows:
CREATE TABLE yourTableName
(
yourColumnName1 dataType NOT NULL AUTO_INCRMENT,
.
.
.
N,
PRIMARY KEY(yourColumnName1 )
)AUTO_INCREMENT=5;
To understand the above syntax, let us create a table.
Case1 − The table starts auto increment from 1 because it is the default standard.
The query to create a table is as follows:
mysql> create table defaultAutoIncrementDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (2.19 sec)
Now you can insert some records in the table using insert command. The query is as follows:
mysql> insert into defaultAutoIncrementDemo(Name) values('John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into defaultAutoIncrementDemo(Name) values('James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into defaultAutoIncrementDemo(Name) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into defaultAutoIncrementDemo(Name) values('Mike');
Query OK, 1 row affected (0.13 sec)
Now you can display all records and check the row will start from 1. The query is as follows:
mysql> select *from defaultAutoIncrementDemo;
The following is the output:
+----+--------+
| Id | Name   |
+----+--------+
|  1 | John   |
|  2 | James  |
|  3 | Robert |
|  4 | Mike   |
+----+--------+
4 rows in set (0.00 sec)
Case2 − Here is the query to start the auto_increment from 5. The query to create a table is as follows:
mysql> create table AutoIncrementStartsFrom5
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(10),
-> PRIMARY KEY(Id)
-> )AUTO_INCREMENT=5;
Query OK, 0 rows affected (1.00 sec)
Now insert some records in the table using insert command. The query is as follows:
mysql> insert into AutoIncrementStartsFrom5(Name) values('Larry');
Query OK, 1 row affected (0.15 sec)
mysql> insert into AutoIncrementStartsFrom5(Name) values('David');
Query OK, 1 row affected (0.20 sec)
mysql> insert into AutoIncrementStartsFrom5(Name) values('Bob');
Query OK, 1 row affected (0.13 sec)
mysql> insert into AutoIncrementStartsFrom5(Name) values('Ricky');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from AutoIncrementStartsFrom5;
The following is the output:
+----+-------+
| Id | Name |
+----+-------+
| 5 | Larry |
| 6 | David |
| 7 | Bob   |
| 8 | Ricky |
+----+-------+
4 rows in set (0.00 sec)
Look at the sample output, the auto_increment starts from 5.
Convert an Object to a Table in R Programming - as.table() Function - GeeksforGeeks

19 Jun, 2020
as.table() function in R Language is used to convert an object into a table.
Syntax: as.table(x)
Parameters:x: Object to be converted
Example 1:
# R Program to convert # an object to a table  # Creating a vectorvec = c(2, 4, 3, 1, 2, 3, 2, 1, 4, 2)   # Calling as.table() Functionas.table(vec)
Output:
A B C D E F G H I J 
2 4 3 1 2 3 2 1 4 2 

Example 2:
# R Program to convert # an object to a table  # Creating a matrixmat = matrix(c(1:9), 3, 3)mat   # Calling as.table() Functionas.table(mat)
Output:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
  A B C
A 1 4 7
B 2 5 8
C 3 6 9

R DataFrame-Function
R List-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
How to avoid the points getting overlapped while using stripplot in categorical scatter plot Seaborn Library in Python?

Visualizing data is an important step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. Seaborn is a library that helps in visualizing data. It comes with customized themes and a high level interface.
General scatter plots, histograms, etc can’t be used when the variables that need to be worked with are categorical in nature. This is when categorical scatterplots need to be used.
Plots such as ‘stripplot’, ‘swarmplot’ are used to work with categorical variables. The ‘stripplot’ function is used when atleast one of the variables is categorical. The data is represented in a sorted manner along one of the axes. But the disadvantage is that certain points get overlapped. This where the ‘jitter’ parameter has to be used to avoid the overlapping between variables.
It adds some random noise to the dataset, and adjusts the positions of the values along the categorical axis.
Syntax of stripplot function
seaborn.stripplot(x, y,data, jitter = ...)
Let us see how ‘jitter’ parameter can be used to plot categorical variables in a dataset −
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
my_df = sb.load_dataset('iris')
sb.stripplot(x = "species", y = "petal_length", data = my_df, jitter = True)
plt.show()
The required packages are imported.
The input data is ‘iris_data’ which is loaded from the scikit learn library.
This data is stored in a dataframe.
The ‘load_dataset’ function is used to load the iris data.
This data is visualized using the ‘stripplot’ function.
An additional parameter named ‘jitter’ is passed to avoid the overlapping of values of the datafame.
Here, the dataframe is supplied as parameter.
Also, the x and y values are specified.
This data is displayed on the console.
How to add background music in HTML?

The HTML <bgsound> tag is used to play music in the background. This tag is for Internet Explorer only.
You can try to run the following code to add background music in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML bgsound Tag</title>
   </head>
   <body>
      <bgsound src = "/html/yourfile.mdi"/>
      <p>Plays sound file in the background.</p>
   </body>
</html>
The HTML <bgsound> tag also supports the following attributes −
AWS Quicksight - AWS SDKs

You can use AWS Quicksight SDK’s to manage the following −
User and group management
Embedding dashboards
Following shows a sample HTML code to be used to display an embedded dashboard −
<!DOCTYPE html>
<html>
   <head>
      <title>Sample Embed</title>
      <script type="text/javascript" src="https://unpkg.com/amazon-quicksight-embedding-sdk@1.0.1/dist/quicksight-embedding-js-sdk.min.js"></script>
      <script type="text/javascript">
         function embedDashboard() {
            var containerDiv = document.getElementById("dashboardContainer");
            var params = {
               url: "https://us-east-1.quicksight.aws.amazon.com/sn/dashboards/xxx-x-x-xx-x-x-x-x-x-x-x-xx-xx-x-xx",
               container: containerDiv,
               parameters: {
                  country: 'United States'
               },
               height: "600px",
               width: "800px"
            };
            var dashboard = QuickSightEmbedding.embedDashboard(params);
            dashboard.on('error', function() {});
            dashboard.on('load', function() {});
            dashboard.setParameters({country: 'Canada'});
         }
      </script>
   </head>
<html>
To use AWS SDK’s, you should be familiar with the following −
JSON
JSON
Web services
Web services
HTTP requests
HTTP requests
One or more programming languages, such as JavaScript, Java, Python, or C#.
One or more programming languages, such as JavaScript, Java, Python, or C#.

    35 Lectures 
     7.5 hours 

 Mr. Pradeep Kshetrapal

    30 Lectures 
     3.5 hours 

 Priyanka Choudhary

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    51 Lectures 
     6 hours 

 Manuj Aggarwal

    41 Lectures 
     5 hours 

 AR Shankar

    14 Lectures 
     1 hours 

 Zach Miller
 Print
 Add Notes
 Bookmark this page
SQL Query to Get the Latest Record from the Table

23 Sep, 2021
Getting the latest record from the table is a simple task, you do not have a need to get advanced knowledge of SQL. In this article, we will discuss the simplest and easier methods to get the latest record from the Table.
You might want to get the latest record from the table with all the columns or you might want only a specific number of columns. You will get the solutions to both the problems in this article. 
Step 1: To solve the queries, firstly create a Table from which you want to extract the record. Here, created a table named Student having Student Data such as Student ID, First Name, Last Name, Age, and the Course of the Student. 
Query:
Create Table Student
(StudentID Int, StudentFirstName Varchar(40),
studentLastName Varchar(40),
Age Int, Course Varchar(60))
Step 2: Insert data into a table
Query:
Insert Into Student Values
(1001,'Sahil','Kumar',19,'B.Com'),
1002,'Himanshu','Saini',20,'B.Tech'),
1003,'Nikhil','Gandhi',20,'B.Tech'),
1004,'Pransh','Mehra',18,'B.Com'),
1005,'Sudhir','Sharma',19,'M.Tech')
Step 3: To see data entries we use the below query:
Query:
Select * From student;
Output:
Now to get the latest record from the table, we will use the following syntax:
Syntax:
Select Column_Name From Table_Name
Order By Column_Name Desc
The data that we get on the top of the table is our latest data,  we will use OrderBy Descending to get our record.
You have seen that the First Name of the Student is on the top of the list, while if we see in the creation of the table. Entered the name Sudhir as the last entry. This gave us the data of all the columns in the Table. 
Now let’s see how to get the record of a specific number of Columns.
To get the latest record of a specific number of columns, we will use the following syntax:
Query:
Select Top 3 Column_Name From Table_Name
Order By Column_Name Desc
Have a look at the example underneath, it shows the record of the Students in the Table.
 
You have observed only 3 entries from the table, but the thing to notice here is that these are the latest 3 entries of the Table, Student. In this way, you can get the latest record of more than one column.
 
Blogathon-2021
Picked
SQL-Query
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Script to Automate Refreshing an Excel Spreadsheet

14 Sep, 2021
In this article, we will learn how we can automate refreshing an Excel Spreadsheet using Python.
So to open the Excel application and workbooks we are going to use the pywin32 module. You can install the module using the below code:
pip install pywin32
Then we are going to open the Excel application using the win32com.client.Dispatch() method and workbooks using the Workbooks.open() method.
Syntax: File.Workbooks.open(PATH_OF_FILE)
Parameters: It will take the path of the excel file as its parameter.
And then use refresh the file using RefershAll():
Workbook.RefreshAll()
For this example, we created an excel file named “Book1” with the below content:
Below is the implementation:
Python3
# Importing the pywin32 moduleimport win32com.client  # Opening Excel software using the win32comFile = win32com.client.Dispatch("Excel.Application")  # Optional line to show the Excel softwareFile.Visible = 1  # Opening your workbookWorkbook = File.Workbooks.open("Book1.xlsx")  # Refeshing all the shestsWorkbook.RefreshAll()  # Saving the WorkbookWorkbook.Save()  # Closing the Excel FileFile.Quit()
Output:
Picked
Python-excel
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What happens when a virtual function is called inside a non-virtual function in C++

20 Dec, 2018
Predict the output of the following simple C++ program without any virtual function.
#include <iostream>using namespace std;  class Base{public:    void print()    {        cout << "Base class print function \n";    }    void invoke()    {        cout << "Base class invoke function \n";        this -> print();    }};  class Derived: public Base{public:    void print()    {        cout << "Derived class print function \n" ;    }    void invoke()    {        cout << "Derived class invoke function \n";        this -> print();    }};  int main(){    Base *b = new Derived;    b -> invoke();    return 0;}
Output:
Base class invoke function
Base class print function
Since there is no virtual function, run time polymorphic behavior doesn’t not work in the above code. Now predict the output of the following C++ program.
#include <iostream>using namespace std;  class Base{public:    virtual void print()    {        cout << "Base class print function \n";    }    void invoke()    {        cout << "Base class invoke function \n";        this -> print();    }};  class Derived: public Base{public:    void print()    {        cout << "Derived class print function \n" ;    }    void invoke()    {        cout << "Derived class invoke function \n";        this -> print(); // called under non - virtual function    }};  int main(){    Base *b = new Derived;    b -> invoke();    return 0;}
Output:
Base class invoke function
Derived class print function
So polymorphic behaviour works even when a virtual function is called inside a non-virtual function. The output can be guessed from the fact that the function to be called is decided at run-time using the vptr and vtable.
This article is contributed by Sumit Jaiswal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
xdsarkar
cpp-inheritance
cpp-virtual
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
React Material-UI Introduction and Installation

23 May, 2022
Material UI is the most powerful and efficient tool to build an Application by adding Designs and Animations and using it with technical and scientific innovation. It is basically a design language that was developed by Google in 2014. It uses more Design and Animations, grid-system and provides shadows and lightning effects.
It can be used with all the JavaScript frameworks like AngularJS, VueJS, and libraries like ReactJS, to make the Application more amazing and responsive. With over 35,000 stars on the GitHub, Material UI is one of the top User Interface libraries for React.
Features of Material UI: Material UI provides low-level utility functions called “style functions”  for building powerful design systems. 
Access the theme values directly from the component props.
Encourage UI consistency.
Write responsive style effortlessly.
Work with any theme object.
Less than KB g zipped.
Fast enough to execute.
Prerequisite:
A code editor like (VS Code, Atom, Sublime etc).
NodeJS should be installed.Installation of Node.js on WindowsInstallation of Node.js on linux
Knowledge of creating a react app.
Installation: To install Material UI run the below command in your working directory.
Install Material UI by using npm.npm install @material-ui/core
npm install @material-ui/core
Install Material UI by using yarn.yarn add @material-ui/core
yarn add @material-ui/core
Example: In this example we will make changes in App.js, we will import Material UI and place a button with the primary color.
App.js
import React, {Component} from 'react';import './App.css';import Button from '@material-ui/core/Button';   class App extends Component {  render(){    return (      <div className="App">         <br />        <Button variant="contained" color="primary"                 size="large">            GeeksforGeeks        </Button>         </div>          );   }   }  export default App;
Output:
bunnyram19
Material-UI
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Multiply two Floating-Point Numbers

07 Jan, 2021
The float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of the Float class can hold a single float value.
The task is to multiply two Floating point numbers in Java and print their multiplication.
Approach:
Initialize two float type numbers.
Store their multiplication result in a float variable.
Print that results
Java
// Java Program to print Multiplication of two floating// point Number.  import java.io.*;  class GFG {    public static void main(String[] args)    {          // f is to ensures that numbers are float DATA TYPE        float f1 = 1.5f;        float f2 = 2.0f;          // to store the multiplied value        float p = f1 * f2;          // to print the product        System.out.println("The product is: " + p);    }}
The product is: 3.0
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Regular Expressions in Scala

08 Apr, 2019
Regular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex.Regex is a class which is imported from the package scala.util.matching.Regex and it is extensively applied in searching and text parsing. In order to recast a string into a Regular Expressions, we need to make use of r() method with the stated string.
Example :
// Scala program for Regular // Expressions  // Creating objectobject GfG {      // Main method    def main(args: Array[String])     {              // Applying r() method        val portal = "GeeksforGeeks".r        val CS = "GeeksforGeeks is a CS portal."          // Displays the first match        println(portal findFirstIn CS)    }}
Some(GeeksforGeeks)

Here, we have called the method r() on the stated string to obtain an instance of Regex class, in order to create a pattern. The method findFirstIn() is utilized in the above code to find the first match of the Regular Expression. In order to find all the matching word in the expression, use findAllIn() method.
Example :
// Scala program for Regular // Expressionsimport scala.util.matching.Regex  // Creating objectobject GfG {      // Main method    def main(args: Array[String])     {              // Applying Regex class        val x = new Regex("Nidhi")        val myself = "My name is Nidhi Singh."          // replaces first match with the        // String given below        println(x replaceFirstIn(myself, "Rahul"))    }}
My name is Rahul Singh.

We can even use constructor of Regex in place of r() method. Here, replaceFirstIn() method is utilized to replace the first match of the stated string and we can even replace all the matches using replaceAllIn() method.
Example :
// Scala program for Regular // Expressionsimport scala.util.matching.Regex  // Creating objectobject GfG {      // Main method    def main(args: Array[String])     {              // Applying Regex class        val Geeks = new Regex("(G|g)fG")        val y = "GfG is a CS portal. I like gfG"          // Displays all the matches separated        // by a separator        println((Geeks findAllIn y).mkString(", "))    }}
GfG, gfG

Here, we have used mkString method to concatenate all the matches, separated by a separator and a pipe ( | ) is used in the above code to search both upper and lower case in the string given. Thus, both upper and lower case of the stated string is returned here.
 
Java inherits some features from Perl, Scala inherits the syntax of Scala regex from Java. Here below is the list of metacharacter syntax:
Picked
Scala
Scala-Basics
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | map() method
Scala | flatMap Method
String concatenation in Scala
Scala | reduce() Function
Type Casting in Scala
Scala List filter() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
Scala String substring() method with example
How to Install Scala with VSCode?
TypeScript | String valueOf() Method

17 Feb, 2021
The valueOf() is an inbuilt function in TypeScript that is used to return the primitive value of a String object.
Syntax: 
string.valueOf( ) 
Parameter: This method does not accept any parameter. Return Value: This method returns the primitive value of a String object. Below examples illustrate the String valueOf() method in TypeScript
Example 1: 
JavaScript
//language is TypeScript     // Original strings    var str = "Geeksforgeeks - Best Platform";     // use of String valueOf() Method    var newstr = str.valueOf()    console.log(newstr);
Output:  
Geeksforgeeks - Best Platform
Example 2:  
JavaScript
// Language is TypeScript     // Original strings    var str = new String("TypeScript - String valueOf()");     // use of String valueOf() Method    var newstr = str.valueOf()    console.log(newstr);
Output: 
TypeScript - String valueOf()
pratikraut0000
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw Spiraling Triangle using Turtle in Python - GeeksforGeeks

20 Aug, 2020
Prerequisite: Python Turtle Basic
Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle, methods defined in the turtle module, and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen). To move turtle(pen) there are some functions i.e forward(), backward(), etc.
Approach to draw a Spiraling Triangle of size n:  
Import turtle and create a turtle instance.
Using for loop(i = 0 to i< n * 3) and repeat below stepturtle.forward(i * 10).turtle.right(120).
turtle.forward(i * 10).
turtle.right(120).
Close the turtle instance.
Below is the implementation:
Python3
# importing turtle module import turtle   # sizen = 10  # creating instance of turtle pen = turtle.Turtle()   # loop to draw a side for i in range(n * 3):         # drawing side of     # length i*10     pen.forward(i * 10)           # changing direction of pen     # by 120 degree in clockwise     pen.right(120)      # closing the instance turtle.done() 
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to generate a sorted list in Python?

The sort method on lists in python uses the given class's gt and lt operators to compare. Most built in classes already has these operators implemented so it automatically gives you sorted list. You can use it as follows:
words = ["Hello", "World", "Foo", "Bar", "Nope"]
numbers = [100, 12, 52, 354, 25]
words.sort()
numbers.sort()

print(words)
print(numbers)
This will give the output:
['Bar', 'Foo', 'Hello', 'Nope', 'World']
[12, 25, 52, 100, 354]
If you don't want the input list to be sorted in place, you can use the sorted function to do so. For example,
words = ["Hello", "World", "Foo", "Bar", "Nope"]
sorted_words = sorted(words)

print(words)
print(sorted_words)
This will give the output:
["Hello", "World", "Foo", "Bar", "Nope"]
['Bar', 'Foo', 'Hello', 'Nope', 'World']
Integer to English Words in Python Programming

Suppose we have a number. The number can be anything in between 0 to 231 – 1. We have to convert the number into words. So if the number is like 512, then the result will be Five hundred twelve.
To solve this, we will follow these steps −
Define some lists like less_than_20, this will hold all words from one to nineteen
Define some lists like less_than_20, this will hold all words from one to nineteen
Another array like tens to hold tens, twenty, thirty and so on up to ninety
Another array like tens to hold tens, twenty, thirty and so on up to ninety
Another array for thousands, to hold thousand, million and billion
Another array for thousands, to hold thousand, million and billion
Define one function called helper(), this will take n
Define one function called helper(), this will take n
if n is 0, then return blank string
if n is 0, then return blank string
otherwise when n < 20, then return less_than_20[n] + blank space
otherwise when n < 20, then return less_than_20[n] + blank space
otherwise when n < 100, then return tens[n/10] + blank space + helper(n mod 10)
otherwise when n < 100, then return tens[n/10] + blank space + helper(n mod 10)
otherwise return less_than_20[n/100] + “Hundred” + helper(n mod 100)
otherwise return less_than_20[n/100] + “Hundred” + helper(n mod 100)
From the main method, do the following
From the main method, do the following
if num is 0, then return “Zero”
if num is 0, then return “Zero”
ans := empty string, i := 0
ans := empty string, i := 0
while num > 0if num mod 1000 is not 0, thenans := helper(num mod 1000) + thousands[i] + blank space + ans
while num > 0
if num mod 1000 is not 0, thenans := helper(num mod 1000) + thousands[i] + blank space + ans
if num mod 1000 is not 0, then
ans := helper(num mod 1000) + thousands[i] + blank space + ans
ans := helper(num mod 1000) + thousands[i] + blank space + ans
return ans
return ans
Let us see the following implementation to get better understanding −
class Solution(object):
less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"]
   tens = ["","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
   def numberToWords(self, num):
      if num == 0:
         return "Zero"
      ans = ""
      i = 0
      while num > 0:
         if num % 1000 != 0:
            ans = self.helper(num % 1000) + Solution.thousands[i] + " " + ans
            i += 1
            num //= 1000
         return ans.strip()
   def helper(self, n):
      if n == 0:
         return ""
      elif n < 20:
         return Solution.less_than_20[n] + " "
      elif n < 100:
         return Solution.tens[n//10] + " " + self.helper(n % 10)
      else:
         return Solution.less_than_20[n // 100] + " Hundred " +
self.helper(n % 100)
ob = Solution()
print(ob.numberToWords(512))
print(ob.numberToWords(7835271))
512
7835271
Five Hundred Twelve
Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One
numpy.zeros() in Python - GeeksforGeeks

28 Mar, 2022
The numpy.zeros() function returns a new array of given shape and type, with zeros. Syntax:
numpy.zeros(shape, dtype = None, order = 'C')
Parameters :
shape : integer or sequence of integers
order  : C_contiguous or F_contiguous
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
dtype : [optional, float(byDeafult)] Data type of returned array.  
Returns : 
ndarray of zeros having given shape, order and datatype.
Code 1 : 
Python
# Python Program illustrating# numpy.zeros method import numpy as geek b = geek.zeros(2, dtype = int)print("Matrix b : \n", b) a = geek.zeros([2, 2], dtype = int)print("\nMatrix a : \n", a) c = geek.zeros([3, 3])print("\nMatrix c : \n", c)
Output : 
Matrix b : 
 [0 0]

Matrix a : 
 [[0 0]
 [0 0]]

Matrix c : 
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
Code 2 : Manipulating data types 
Python
# Python Program illustrating# numpy.zeros method import numpy as geek # manipulation with data-typesb = geek.zeros((2,), dtype=[('x', 'float'), ('y', 'int')])print(b)
Output : 
[(0.0, 0) (0.0, 0)]
Reference : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.zeros.html#numpy.zeros Note : zeros, unlike zeros and empty, does not set the array values to zero or random values respectively.Also, these codes won’t run on online IDE’s. Please run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
kothavvsaakash
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Linux Admin - wc Command

wc is useful for counting occurrences in a file. It helps print newline, word, ad byte count from each file. Most useful is when combined with grep to show matches for a certain pattern.
We can see our system has 5 users with a group id of 0. Then upon further inspection only the root user has shell access.
[root@centosLocal centos]# cat /etc/passwd | cut -d":" -f4 | grep "^0" |  wc -l 
5 
[root@centosLocal centos]# cat /etc/passwd | cut -d":" -f4,5,6,7 | grep "^0" 
0:root:/root:/bin/bash 
0:sync:/sbin:/bin/sync 
0:shutdown:/sbin:/sbin/shutdown 
0:halt:/sbin:/sbin/halt 
0:operator:/root:/sbin/nologin 
[root@centosLocal centos]#


    57 Lectures 
     7.5 hours 

 Mamta Tripathi

    25 Lectures 
     3 hours 

 Lets Kode It

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    58 Lectures 
     2.5 hours 

 Frahaan Hussain

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    23 Lectures 
     5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Runtime Polymorphism in Java

Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.
See the example below to understand the concept −
 Live Demo
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object
      a.move(); // runs the method in Animal class
      b.move(); // runs the method in Dog class
   }
}
This will produce the following result −
Animals can move
Dogs can walk and run
string.punctuation in Python

In this tutorial, we are going to learn about the string.punctuation string.
The string punctuation is pre-defined in the string  module of Python3. It contains all the
characters as a string. We can use it anywhere in the program.
 Live Demo
# importing the string module
import string
# printing the punctuation
print(string.punctuation)
If you run the above code, then you will get the following result.
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
We can use it to generate strong passwords. Try it out. If you have any doubts in the tutorial,
mention them in the comment section.
Abstract class in Java

A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide implementations of the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Example
This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration.
/* File name : Employee.java */
public abstract class Employee {
   private String name; private String address; private int number;
   public Employee(String name, String address, int number) {
      System.out.println("Constructing an Employee");
      this.name = name; this.address = address;
      this.number = number;
   }
   public double computePay() {
      System.out.println("Inside Employee computePay"); return 0.0;
   }
   public void mailCheck() {
      System.out.println("Mailing a check to " + this.name + " " + this.address);
   }
   public String toString() {
      return name + " " + address + " " + number;
   }
   public String getName() {
      return name;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String newAddress) {
      address = newAddress;
   }
   public int getNumber() {
      return number;
   }
}
You can observe that except abstract methods the Employee class is same as the normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor.
Now you can try to instantiate the Employee class in the following way − 
/* File name : AbstractDemo.java */
public class AbstractDemo {
   public static void main(String [] args) {
      /* Following is not allowed and would raise error */
      Employee e = new Employee("George W.", "Houston, TX", 43);
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
 }
When you compile the above class, it gives you the following error − 
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error
Python - Merge Pandas DataFrame with Left Outer Join

To merge Pandas DataFrame, use the merge() function. The left outer join is implemented on both the DataFrames by setting under the “how” parameter of the merge() function i.e. −
how = “left”
At first, let us import the pandas library with an alias −
import pandas as pd

Let’s create two DataFrames to be merged −
# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)

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

   }
)
Merge DataFrames with common column Car and "left" in "how" parameter implements Left Outer Join −
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="left")

Following is the code −
import pandas as pd

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

print"DataFrame1 ...\n",dataFrame1

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

   }
)

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

# merge DataFrames with common column Car and "left" in "how" parameter implements Left Outer Join
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="left")
print"\nMerged dataframe with left outer join...\n", mergedRes
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

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

Merged dataframe with left outer join...
       Car   Units   Reg_Price
0      BMW     100      7000.0
1    Lexus     150      1500.0
2     Audi     110         NaN
3  Mustang      80      8000.0
4  Bentley     110         NaN
5   Jaguar      90      6000.0
Design Patterns - Strategy Pattern

In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.
We are going to create a Strategy interface defining an action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy.
StrategyPatternDemo, our demo class, will use Context and strategy objects to demonstrate change in Context behaviour based on strategy it deploys or uses.
Create an interface.
Strategy.java
public interface Strategy {
   public int doOperation(int num1, int num2);
}
Create concrete classes implementing the same interface.
OperationAdd.java
public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 + num2;
   }
}
OperationSubstract.java
public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}
OperationMultiply.java
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}
Create Context Class.
Context.java
public class Context {
   private Strategy strategy;

   public Context(Strategy strategy){
      this.strategy = strategy;
   }

   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}
Use the Context to see change in behaviour when it changes its Strategy.
StrategyPatternDemo.java
public class StrategyPatternDemo {
   public static void main(String[] args) {
      Context context = new Context(new OperationAdd());		
      System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

      context = new Context(new OperationSubstract());		
      System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

      context = new Context(new OperationMultiply());		
      System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}
Verify the output.
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
What does the volatile keyword mean in C++?

volatile means two things −
- The value of the variable may change without any code of yours changing it. Therefore whenever the compiler reads the value of the variable, it may not assume that it is the same as the last time it was read, or that it is the same as the last value stored, but it must be read again.- The act of storing a value to a volatile variable is a "side effect" which can be observed from the outside, so the compiler is not allowed to remove the act of storing a value; for example, if two values are stored in a row, then the compiler must actually store the value twice.As an example −
i = 2;
i = i;
The compiler must store the number two, read the variable i, store the variable that it read into i.You can find more details on the volatile keyword here − https://www.geeksforgeeks.org/understanding-volatile-qualifier-in-c/
C++ iomanip Library - setiosflags Function

The C++ function std::setiosflags behaves as if member setf were called with mask as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).
It is used to sets the format flags specified by parameter mask.
Following is the declaration for std::setiosflags function.
 setiosflags (ios_base::fmtflags mask);
mask − Mask representing the flags to be set. fmtflags is a bitmask type.
It returns unspecified. This function should only be used as a stream manipulator.
Basic guarantee − if an exception is thrown, the stream is in a valid state.
The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce data races.
In below example explains about setiosflag function.
#include <iostream>
#include <iomanip>

int main () {
   std::cout << std::hex;
   std::cout << std::setiosflags (std::ios::showbase | std::ios::uppercase);
   std::cout << 100 << std::endl;
   return 0;
}
Let us compile and run the above program, this will produce the following result −
0X64

 Print
 Add Notes
 Bookmark this page
C++ iomanip Library - setprecision Function

The C++ function  std::setprecision behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).
It is used to sets the decimal precision to be used to format floating-point values on output operations.
Following is the declaration for std::setprecision function.
setprecision (int n);
n − New value for the decimal precision.
It returns unspecified. This function should only be used as a stream manipulator.
Basic guarantee − if an exception is thrown, the stream is in a valid state.
The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce data races.
In below example explains about setprecision function.
#include <iostream>
#include <iomanip>

int main () {
   double f =3.14159;
   std::cout << std::setprecision(5) << f << '\n';
   std::cout << std::setprecision(9) << f << '\n';
   std::cout << std::fixed;
   std::cout << std::setprecision(5) << f << '\n';
   std::cout << std::setprecision(9) << f << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
3.1416
3.14159
3.14159
3.141590000

 Print
 Add Notes
 Bookmark this page
Queue.Dequeue Method in C#

The Queue.Dequeue() method in C# is used to remove and return the object at the beginning of the Queue.
The syntax is as follows −
public virtual object Dequeue ();
Let us now see an example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("A");
      queue.Enqueue("B");
      queue.Enqueue("C");
      queue.Enqueue("D");
      queue.Enqueue("E");
      queue.Enqueue("F");
      queue.Enqueue("G");
      Console.WriteLine("Count of elements = "+queue.Count);
      Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
      queue.Dequeue();
      queue.Dequeue();
      queue.Dequeue();
      Console.WriteLine("Count of elements = "+queue.Count);
   }
}
This will produce the following output −
Count of elements = 7
Element at the beginning of queue = A
Count of elements = 4
Let us now see another example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Gary");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      queue.Enqueue("Mark");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Queue...");
      foreach(string i in queue) {
         Console.WriteLine(i);
      }
      queue.Dequeue();
      queue.Dequeue();
      Console.WriteLine("Queue...UPDATED");
      foreach(string i in queue) {
         Console.WriteLine(i);
      }
      Console.Write("Count of elements (updated) = "+queue.Count);
      queue.Clear();
      Console.Write("\nCount of elements (updated AGAIN) = ");
      Console.WriteLine(queue.Count);
   }
}
This will produce the following output −
Count of elements = 8
Queue...
Gary
Jack
Ryan
Kevin
Mark
Jack
Ryan
Kevin
Queue...UPDATED
Ryan
Kevin
Mark
Jack
Ryan
Kevin
Count of elements (updated) = 6
Count of elements (updated AGAIN) = 0
reference_wrapper in C++

03 Dec, 2019
std::reference_wrapper is a class template that wraps a reference in a copy constructible and copy assignable object or reference to function of type T.Instances of std::reference_wrapper are objects (they can be copied or stored in containers) but they are implicitly convertible to ‘T&’ so that they can be used as arguments with the functions that take the underlying type by reference.
Syntax:
template <class T> class reference_wrapper;
template parameter(T): type of the referred element and
                        this can be  either function or object.

Example:
// C++ program to demonstrate the// use of std::reference_wrapper#include <iostream>    #include <functional> using namespace std;  int main () {    char a = 'g', b = 'e', c  = 'e', d = 'k', e = 's';          // creating an array of character "references":    reference_wrapper<char> ref[] = {a, b, c, d, e};          for (char& s : ref)          cout << s;          return 0;}
Output:
geeks

akhlopuzyan
CPP-Library
cpp-references
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
unordered_map in C++ STL
Substring in C++
Object Oriented Programming in C++
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++
C++ Data Types