code-rag-bench/online-tutorials huggingface dataset:
How to validate a credit card number in ReactJS ? - GeeksforGeeks

16 Dec, 2020
Credit card validation is an important step in every application in order to authenticate the user’s credit card number so that the application can proceed to the payment process if needed. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user entered credit card number and check whether it is valid or not using the npm module in the ReactJS application.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app creditcardvalidatedemo
Step 2: After creating your project folder i.e. creditcardvalidatedemo, move to it using the following command:
cd creditcardvalidatedemo
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to validate credit card numbers with basic UI.
Javascript
import React, { useState } from "react";import validator from 'validator'  const App = () => {    const [errorMessage, setErrorMessage] = useState('')      const validateCreditCard = (value) => {        if (validator.isCreditCard(value)) {      setErrorMessage('Valid CreditCard Number')    } else {      setErrorMessage('Enter valid CreditCard Number!')    }  }    return (    <div style={{      marginLeft: '200px',    }}>      <pre>        <h2>Validating CreditCard in ReactJS</h2>        <span>Enter CreditCard: </span><input type="text"         onChange={(e) => validateCreditCard(e.target.value)}></input> <br />        <span style={{          fontWeight: 'bold',          color: 'red',        }}>{errorMessage}</span>      </pre>    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters an invalid credit card number as shown below:
The following will be the output if the user enters a valid credit card number as shown below:
react-js
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Find Element and FindElements by XPath in Selenium

The findElement(By.xpath) method is used to identify an element which matches with the xpath locator passed as a parameter to this method. The findElements(By.xpath) method is used to identify a collection of elements which match with xpath locator passed as a parameter to that method.
The method findElement(By.xpath) returns a web element whereas the method findElements(By.xpath) returns a list of web elements. An exception is thrown by the method findElement(By.xpath) if there is no matching element. An empty list of elements is returned if there is no matching element obtained from the findElements(By.xpath) method.
Let us try to identify the number of children of the ul tag and also the first subelement of ul( li[1] having text Selected Reading).
List<WebElement> n =
driver.findElements(By.xpath("//ul[@class=' toc reading']/li"));
WebElement m =driver.findElement(By.xpath("//ul[@class=' toc reading']/li[1]"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class XpathFindElment{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify elements with findElements xpath
      List p = driver.findElements(By.xpath("//ul[@class='toc reading']/li"));
      //count of list of matching elements
      int s = p.size();
      //identify element with xpath
      WebElement m = driver.findElement(By.xpath("//ul[@class='toc reading']/li[1]"));
      System.out.println("Element text is: "+ m.getText());

      driver.quit();
   }
}
Stacked area chart with R - GeeksforGeeks

16 Mar, 2021
Area Charts are defined as the filled regions between two series that share common areas. A stacked area chart is easily understandable if you know the area chart. This plot display evolution of cost/value of several groups on the same plot. The values of each group are displayed on top of every other. Using this plot, we can analyze the total numerical value of variables present in each group section-wise and the importance of each group.
R uses the function geom_area() to create Stacked area charts.
Syntax: ggplot(Data, aes(x=x_variable, y=y_variable, fill=group_variable)) + geom_area()
Parameters:
Data: This parameter contains whole dataset which are used in stacked-area chart.
x: This parameter contains numerical value of variable for x axis in stacked-area chart.
y: This parameter contains numerical value of variables for y axis in stacked-area chart.
fill: This parameter contains group column of Data which is mainly used for analyse in stacked-area chart.
Creating a basic Stacked area chart:
Step 1: Import Packages
R
library(ggplot2)library(dplyr)library(tidyverse)
Step 2: Create Dataset
In the Group column, Four Direction is replicated 4 times. Year column, the sequence is generated from 2017 to 2020, each 4 times. Price column, generated by runif(n, min, max) function.
R
group <- rep(c("NORTH","SOUTH","EAST","WEST"),times=4)  year <- as.numeric(rep(seq(2017,2020),each=4)) price <- runif(16, 50, 100)  data <- data.frame(year, price, group)
Output:
Step 3: Plot the Data
R
ggplot(data, aes(x=year, y=price, fill=group)) + geom_area()
Output:
In the basic stacked-area chart, if we interested in the relative interest of each group, then we can draw a percentage stacked-area chart. This plot will normalize our data then plot. This can be done using dplyr library.
Step 1: Calculate the percentage
R
data <- data  %>%+     group_by(year, group) %>%+     summarise(n = sum(price)) %>%+     mutate(percentage = n / sum(n))
Output:
Step 2: Plot data
We can add color in a plot by Viridis library, Title by ggtitle, and theme_ipsum of the hrbrthemes package
R
library(viridis)library(hrbrthemes)  ggplot(data, aes(x=year, y=percentage, fill=group)) +     geom_area(alpha=0.8 , size=.5, colour="white") +    scale_fill_viridis(discrete = T) +    theme_ipsum() +     ggtitle("Percentage Stacked-Area Plot")
Output:
Picked
R-Charts
R-Graphs
R-plots
Technical Scripter 2020
R Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
R - if statement
How to filter R dataframe by multiple conditions?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
Path toAbsolutePath() method in Java with Examples - GeeksforGeeks

03 Dec, 2019
The Java Path interface was added to Java NIO in Java 7. toAbsolutePath() method of java.nio.file.Path used to return a Path object representing the absolute path of this path object. If the path is already absolute then the method returns path else this method resolves this path in an implementation-dependent manner by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.
Syntax:
int toAbsolutePath()

Parameters: This method accepts nothing.
Return value: This method returns a Path object representing the absolute path.
Exception: This method throws following Exceptions:
IOError – if an I/O error occurs
SecurityException – In the case of the default provider, a security manager is installed, and this path is not absolute, then the security manager’s
checkPropertyAccess method is invoked to check access to the system property user.dir
Below programs illustrate toAbsolutePath() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.toAbsolute() method  import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path = Paths.get("\\temp\\Spring");          // call toAbsolutePath() to get        // absolute path        Path absPath = path.toAbsolutePath();          // print absolute path        System.out.println("Absolute Path: "                           + absPath);    }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.toAbsolutePath() method  import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)    {          // create object of Path        Path path = Paths.get("Program Files\\Java");          // call toAbsolutePath() to get        // absolute path        Path absPath= path.toAbsolutePath();          // print absolute path        System.out.println("Absolute Path: "                           + absPath);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toAbsolutePath()
jacekwitkowski1
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
Python | Check if element is present in tuple - GeeksforGeeks

26 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to check if data we are working with has a particular element. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force method to perform this task. In this, we iterate through the tuple and check each element if it’s our, if found we return True.
# Python3 code to demonstrate working of# Check if element is present in tuple# using loop  # initialize tupletest_tup = (10, 4, 5, 6, 8)  # printing original tupleprint("The original tuple : " + str(test_tup))  # initialize N N = 6  # Check if element is present in tuple# using loopres = False for ele in test_tup :    if N == ele :        res = True        break  # printing resultprint("Does tuple contain required value ? : " + str(res))
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

 
Method #2 : Using in operatorUsing in operator is most Pythonic way to perform this task. It is a one-liner and recommened to perform this task.
# Python3 code to demonstrate working of# Check if element is present in tuple# Using in operator  # initialize tupletest_tup = (10, 4, 5, 6, 8)  # printing original tupleprint("The original tuple : " + str(test_tup))  # initialize N N = 6  # Check if element is present in tuple# Using in operatorres = N in test_tup  # printing resultprint("Does tuple contain required value ? : " + str(res))
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
HTTP headers | Accept-CH - GeeksforGeeks

22 Nov, 2019
The HTTP Accept-CH header is a response-type header that indicates the client hints that the server can support and should include in further requests.
Syntax:
Accept-CH: client hints
Note: The client hints can be more than one and are to be separated by commas.
Directives: The HTTP Accept-CH header accepts a single directive as mentioned above and described below:
client hints: This directive contains a set of HTTP request header fields for proactive content negotiation for indicating a list of device and agent specific preferences.
Below examples will illustrate the HTTP Accepts-CH header:
Examples:
When one client hint is used. In this example, Viewport-Width is the client hint and it indicates the layout viewport width in CSS pixels.Accept-CH: Viewport-Width
Accept-CH: Viewport-Width
When multiple client hints are used. In this example Viewport-Width and Width are the client hints.Accept-CH: Viewport-Width, Width
Accept-CH: Viewport-Width, Width
To check the Accept-CH in action go to Inspect Element -> Network check the response header for Accept-CH like below.
Supported Browsers: The browsers are compatible with the HTTP Accept-CH header are listed below:
Google Chrome
Opera
HTTP-headers
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
How to redirect to another page in ReactJS ?
Smart Mirror using the concept of IoT

14 May, 2020
A Smart Mirror may be a two-way mirror with an inbuilt display behind the glass.The device was to look like a regular mirror but would have a screen inside and you would be able to interact with it using voice commands, hand gestures and smartphone. The raspberry pi is programmed using python and connects to a monitor with inbuilt speaker to provide onscreen interface and voice assistance.
Requirements:
Two way mirrorMonitorRaspberry pi 3Power adapter for raspberry piMicro SD card (32GB) and HDMI cableHC-SRO4 ultrasonic distances sensorJumper wires, Registers, PlatesFrame and back support
Two way mirror
Monitor
Raspberry pi 3
Power adapter for raspberry pi
Micro SD card (32GB) and HDMI cable
HC-SRO4 ultrasonic distances sensor
Jumper wires, Registers, Plates
Frame and back support
Working Procedure:On start, after giving power supply to mirror the raspberry loads the Operating System and directly runs the User Interface of the mirror.A power saving mode is additionally provided to the mirror by attaching a ultrasonic range detector sensor on the highest of the mirror.On fully loading the knowledge required the mirror now shows notification from different social sites as per the user has logged in.
Features:
Touch Screen
LED Lighting
Motion sensor
Voice control
Facial recognition
Advantages:
Easy to communicateUser friendlyVoice inputFast and easy images replacementAdjustable images switching times
Easy to communicate
User friendly
Voice input
Fast and easy images replacement
Adjustable images switching times
Disadvantages:
Swipe gestures are sometimes unreliable.Lack of human interaction.
Swipe gestures are sometimes unreliable.
Lack of human interaction.
We believe that the future of the home will be a brilliantly connected ecosystem of smart technology designed to make your life easier, more enjoyable, and efficient.Obviously, there are plenty of opportunities within the home for technology integration but a mirror is one among the simplest places to start out.
computer-graphics
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to print the content of current window using JavaScript ?

20 Jan, 2022
The task is to print the content of the current window by using the window.print() method in the document. It is used to open the Print Dialog Box to print the current document. It does not have any parameter value. Syntax:  
window.print()
Example: This example representing how to print the content of current window using JavaScript. 
html
<!DOCTYPE html><html> <body>    <h1>Hello GeeksForGeeks Users</h1>     <h3>        Print the content of the current        window using HTML and JavaScript    </h3>     <form>        <input type="button" value="Print"            onclick="print_current_page()" />    </form>     <script type="text/javascript">        function print_current_page() {            window.print();        }    </script></body> </html>
Before Clicking On Print Button: 
After Clicking On Print Button: 
Supported Browser are listed below: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
surinderdawra388
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Grouping Categorical Variables in Pandas Dataframe

17 Aug, 2020
Firstly, we have to understand what are Categorical variables in pandas. Categorical are the datatype available in pandas library of python. A categorical variable takes only a fixed category (usually fixed number) of values. Some examples of Categorical variables are gender, blood group, language etc. One main contrast with these variables are that no mathematical operations can be performed with these variables.
A dataframe can be created in pandas consisting of categorical values using Dataframe constructor and specifying dtype = ”category”. 
Python3
# importing pandas as pd import pandas as pd   # Create the dataframe # with categorical variable df = pd.DataFrame({'A': ['a', 'b', 'c',                         'c', 'a', 'b'],                   'B': [0, 1, 1, 0, 1, 0]},                  dtype = "category")# show the data typesdf.dtypes
Output: 
Here one important thing is that categories generated in each column are not same, conversion is done column by column as we can see here:
Output:
Now, in some works, we need to group our categorical data. This is done using the groupby() method given in pandas. It returns all the combinations of groupby columns. Along with groupyby we have to pass an aggregate function with it to ensure that on what basis we are going to group our variables. Some aggregate function are mean(), sum(), count() etc.
Now applying our groupby() along with count() function.
Python3
# initial stateprint(df)  # counting number of each categoryprint(df.groupby(['A']).count().reset_index())
Output:
dataframe
Group by column ‘A’
Now, one more example with mean() function. Here column A is converted to categorical and all other are numerical and mean is calculated according to categories of column A and column B.
Python3
# importing pandas as pd import pandas as pd   # Create the dataframe df = pd.DataFrame({'A': ['a', 'b', 'c',                          'c', 'a', 'b'],                    'B': [0, 1, 1,                          0, 1, 0],                    'C':[7, 8, 9,                        5, 3, 6]})  # change tha datatype of # column 'A' into category# data typedf['A'] = df['A'].astype('category')                                                                                                                                                                                                     # initial stateprint(df)  # calculating mean with # all combinations of A and Bprint(df.groupby(['A','B']).mean().reset_index())
  
Output:
Dataframe
Group by both column ‘A’ and ‘B’
Other aggregate functions are also implemented in the same way using groupby().
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Parse Tree in Compiler Design

14 Jul, 2022
Here we will study the concept and uses of Parse Tree in Compiler Design. First, let us check out two terms :
Parse : It means to resolve (a sentence) into its component parts and describe their syntactic roles or simply it is an act of parsing a string or a text.
Tree: A tree may be a widely used abstract data type that simulates a hierarchical tree structure, with a root value and sub-trees of youngsters with a parent node, represented as a group of linked nodes.
Parse Tree:
Parse tree is the hierarchical representation of terminals or non-terminals.
These symbols (terminals or non-terminals) represent the derivation of the grammar to yield input strings.
In parsing, the string springs using the beginning symbol.
The starting symbol of the grammar must be used as the root of the Parse Tree.
Leaves of parse tree represent terminals.
Each interior node represents productions of a grammar.
Rules to Draw a Parse Tree:
All leaf nodes need to be terminals.All interior nodes need to be non-terminals.In-order traversal gives the original input string.
All leaf nodes need to be terminals.
All interior nodes need to be non-terminals.
In-order traversal gives the original input string.
Example 1: Let us take an example of Grammar (Production Rules).
S -> sAB
A -> a
B -> b
The input string is “sab”, then the Parse Tree is:
  
Example-2: Let us take another example of Grammar (Production Rules).
S -> AB
A -> c/aA
B -> d/bB
The input string is “acbd”, then the Parse Tree is as follows: 
 
Uses of Parse Tree:
It helps in making syntax analysis by reflecting the syntax of the input language.
It uses an in-memory representation of the input with a structure that conforms to the grammar.
The advantages of using parse trees rather than semantic actions: you’ll make multiple passes over the info without having to re-parse the input.
dongrimohammedafreed
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | file_exists( ) Function

31 Jul, 2021
The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not.
The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure.
Syntax:
file_exists($path)
Parameters: The file_exists() function in PHP accepts only one parameter $path. It specifies the path of the file or directory you want to check.
Return Value: It returns True on success and False on failure.
Errors And Exception:
The file_exists() function returns False if the path specified points to non-existent files.For files larger than 2gb, some of the filesystem functions may give unexpected results since PHP’s integer type is signed and many platforms use 32bit integers.
The file_exists() function returns False if the path specified points to non-existent files.
For files larger than 2gb, some of the filesystem functions may give unexpected results since PHP’s integer type is signed and many platforms use 32bit integers.
Examples:
Input : echo file_exists('/user01/work/gfg.txt');
Output : 1

Input : $file_pointer = '/user01/work/gfg.txt';
        if (file_exists($file_pointer)) {
            echo "The file $file_pointer exists";
        }else {
            echo "The file $file_pointer does 
                                   not exists";
        }
Output : 1

Below programs illustrate the file_exists() function.
Program 1:
<?php  // checking whether file exists or notecho file_exists('/user01/work/gfg.txt');  ?>
Output:
1
Program 2:
<?php  // checking whether file exists or not$file_pointer = '/user01/work/gfg.txt';  if (file_exists($file_pointer)) {    echo "The file $file_pointer exists";}else {    echo "The file $file_pointer does                             not exists";}  ?>
Output:
1
Reference:http://php.net/manual/en/function.file-exists.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-file-handling
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Turn Pandas Multi-Index into column

06 Oct, 2021
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method.
DataFrame.reset_index() is used to reset the index to default and make the index a column of the dataframe.
Step 1: Creating a multi-index dataframe.
Let’s see an example by making a multi-index dataframe first.
Code:
Python3
import pandas as pd # Creating index for multi-index dataframetuples = [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')]index = pd.MultiIndex.from_tuples(tuples) # Value corresponding to the indexdata = [2, 4, 6, 8] # Creating dataframe using 'data' and 'index'df = pd.DataFrame(data = data, index = index, columns = ['value'])print(df)
Output:
Step 2: Converting index into the column.
Here we can see the hierarchical indexing, we are going to convert it into a column using the reset_index() method.
Python3
reset_df = df.reset_index()print(reset_df)
 
 
Output:
 
 
Here we can see that the index is default now and our multi-index now becomes columns with the default. We can also select which level of multi-index to reset using parameter level.
 
Code:
 
Python3
# rest only index 'indx1'reset_indx1 = df.reset_index(level='indx1')print(reset_indx1)
 
 
Output:
 
 
Here, we can see that only indx1 is reset becomes a column, not both the indices. Also, notice that there is no default index in this case because there is still an index (indx2) left.
 
sumitgumber28
Picked
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.
SQL Query To Show Top 5 Selling Products - GeeksforGeeks

08 Oct, 2021
To display the top 5 selling products ORDER BY can be used with the  SELECT TOP clause. So let us see the SQL Query for Showing Top 5 Selling Products using ORDER BY and SELECT TOP clause using MSSQL as the server.
Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Step 2: To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Step 3: Now we creating a table. Create a table sales_details with  4 columns using the following SQL query.
Query:
CREATE TABLE sales_details(
item_id VARCHAR(20),
item_price INT,
items_sold INT
)
Step 4: Viewing the description of the table.
Query:
EXEC sp_columns sales_details
Step 5: The query for Inserting rows into the Table. Inserting rows into sales_details  table using the following SQL query.
Query:
INSERT INTO sales_details VALUES
('I4001',20000, 5000),
('I4098',1000, 10000),
('I4010',200, 800),
('I4056',30000, 100000),
('I4068',990, 780),
('I4072',10000, 9000),
('I4078',100000, 10),
('I4090',200000, 500)
 Step 6: Viewing the inserted data and order by descending order of the number of units sold.
Query:
SELECT * FROM sales_details  
ORDER BY items_sold DESC
Step 7: Query to find the top 5 selling products.
Syntax:
SELECT TOP N column_name 
FROM table_name ORDER BY column_name ordering_type
Query:
SELECT TOP 5  item_id , items_sold  
FROM sales_details ORDER BY  items_sold DESC
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
How to create a JAR file?

You can create a JAR file using the following command.
jar cf jar-file input-file(s)  
You can also create JAR files using IDE’s. To create a JAR file using eclipse follow the procedure given below.
The Jar File wizard can be used to export the content of a project into a jar file. To bring up the Jar File wizard −
In the Package Explorer select the items that you want to export. If you want to export all the classes and resources in the project just select the project.
Click on the File menu and select Export.
In the filter text box of the first page of the export wizard type in JAR.
Under the Java category select JAR file.
 Click on Next.
In the JAR File Specification page −
Enter the JAR file name and folder.
The default is to export only the classes. To export the source code also, click on the Export Java source files and resources checkbox.
Click on Next to change the JAR packaging options.
Click on Next to change the JAR Manifest specification
Click on Finish.
Python Group tuples in list with same first value

In this tutorial, we are going to write a program that groups all the tuples with the same first element. Let's see an example to understand it clearly.
[(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]
[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]
Let's see the steps to solve the problem.
Initialize the list.
Initialize an empty dictionary.
Iterate over the list of tuples.
Check if the first element of the tuple is present as a key in the dictionary or not.
If it is present, then append the current tuple values without the first one to the previous values.
If not present, then initialize the key with the current tuple elements including the first element.
Print the values of the dict as a list.
 Live Demo
# initializing the list
tuples = [(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]
# empty dict
result = {}
# iterating over the tuples
for sub_tuple in tuples:
   # checking the first element of the tuple in the result
   if sub_tuple[0] in result:
      # adding the current tuple values without first one
      result[sub_tuple[0]] = (*result[sub_tuple[0]], *sub_tuple[1:])
   else:
      # adding the tuple
      result[sub_tuple[0]] = sub_tuple
# printing the result in list
print(list(result.values()))
If you run the above code, then you will get the following result.
[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]
You can try to solve the problem in different ways. And if you have any doubts in the tutorial, mention them in the comment section.
Get the maximum of two numbers using Math.max in Java

To obtain the maximum of two numbers using Math.max in Java, we use the java.lang.Math.max() method. The Math.max() accepts two numbers and returns the greater of the two. The result is closer to positive infinity on the number line. Even if one of the values is not a number(NaN), the result is NaN.
Declaration - The java.lang.Math.max() method is declared as follows −
public static int max(int a, int b)
public static double max(double a, double b)
public static long max(long a, long b)
public static float max(float a, float b)
Let us see a program to get the maximum of two numbers using the Math.max() method
 Live Demo
import java.lang.Math;
public class Example {
   public static void main(String[] args) {
      // declaring and intializing some integer values
      int a = 10;
      int b = 9;
      // declaring and intializing some float values
      float c = 10.00f;
      float d = 9.99f;
      // declaring and initializing some double values
      double x = 300.01d;
      double y = 290.344d;
      // declaring and initializing some long values
      long r = 123456l;
      long s = 35678l;
      System.out.println("Maximum of " + a +" and " + b +" is " + Math.max(a,b));
      System.out.println("Maximum of " + c +" and " + d +" is " + Math.max(c,d));
      System.out.println("Maximum of " + x +" and " + y +" is " + Math.max(x,y));
      System.out.println("Maximum of " + r +" and " + s +" is " + Math.max(r,s));
   }
}
Maximum of 10 and 9 is 10
Maximum of 10.0 and 9.99 is 10.0
Maximum of 300.01 and 290.344 is 300.01
Maximum of 123456 and 35678 is 123456
static keyword in C#

We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.
The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.
The following is an example showing the usage of static variables −
 Live Demo
using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }

      public int getNum() {
         return num;
      }
   }

   class StaticTester {
      static void Main(string[] args) {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();

         s1.count();
         s1.count();
         s1.count();

         s2.count();
         s2.count();
         s2.count();

         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}
Variable num for s1: 6
Variable num for s2: 6
GATE CS 2020 - GeeksforGeeks

29 Oct, 2021
We use 'since' to refer back to a previous point in time. We use 'since' as a preposition with a date, a time or a noun phrase.
We use 'for' with a period of time to refer to duration (how long something lasts).
Cook : Cook :: Fly : _______ 
Verb : Noun 
The dawn of the 21st century witnessed the melting glaciers oscillating between giving too much and too little to billions of people who depend on them for fresh water. The UN climate report estimates that without deep cuts to man-made emissions, at least 30% of the northern hemisphere’s surface permafrost could melt by the end of the century. Given this situation of imminent global exodus of billions of people displaced by rising seas, nation-states need to rethink their carbon footprint for political concerns, if not for environmental ones. Which one of the following statements can be inferred from the given passage ? 
Nation-states do not have environmental concerns. 
Nation-states are responsible for providing fresh water to billions of people. 
Billions of people are responsible for man-made emissions. 
Billions of people are affected by melting glaciers. 
Option (D) clearly explains the second last line of the passage. 
200 + 200 + 100 + 100 + 100 = 700
(B) Cost of 1-f-b-2 :  
100 + 100 + 0 + 100 +200 = 500
(C) Cost of 1-b-2 :  
300 + 100 + 200 = 600 
(D) Cost of 1-f-e-2 :  
100 + 100 + 100 + 200 + 200 = 700
Hence, 1-f-b-2 is having minimum cost. Option (B) is correct.
P = 31 = 3 
Q = 32 = 9
R = 33 = 27
S = 34 = 81
T = 35 = 243 
Q+S = 9+81 = 90 
= π((b-a)/2)2
= nπ((b-a)/2)2
= πb2 – πa2 
= (Area of annular ring) – (Area of n blue color circles)
= ( πb2 – πa2 ) - ( nπ((b-a)/2)2 )
= π( b2 – a2 ) - π( (n/4)(b-a)2 )
= π[(b2−a2)−(n/4)(b−a)2] 
→ ∠a + ∠b + ∠c = 180°
→ α + β + 90° = 180° 
→ α + β = 180° - 90° = 90°
→ α + β = 90°
= 500 million/year 
= 500 × 5 
= 2500 million 
= 400 + 500 + 600 + 700 + 800
= 3000 million 
= 3000 - 2500 = 500 
= (500/2500)*100 %
= 20 % profit 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Get Date and Time in different Formats in R Programming - date(), Sys.Date(), Sys.time() and Sys.timezone() Function - GeeksforGeeks

12 Jun, 2020
date() function in R Language is used to return the current date and time.
Syntax: date()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# date function  # Calling date() function to # return current date and timedate()
Output:
[1] "Thu Jun 11 04:29:39 2020"

Sys.Date() function is used to return the system’s date.
Syntax: Sys.Date()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# Sys.Date function  # Calling Sys.Date() function to # return the system's dateSys.Date()
Output:
[1] "2020-06-11"

Sys.time() function is used to return the system’s date and time.
Syntax: Sys.time()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# Sys.time function  # Calling Sys.time() function to # return the system's date and timeSys.time()
Output:
[1] "2020-06-11 05:35:49 UTC"

Sys.timezone() function is used to return the current time zone.
Syntax: Sys.timezone()
Parameters:Does not accept any parameters
Example:
# R program to illustrate# Sys.timezone function  # Calling Sys.timezone() function to # return the current time zoneSys.timezone()
Output:
[1] "Etc/UTC"

R Date-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Remove rows with NA in one column of R DataFrame
K-Means Clustering in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
JavaScript - Date toDateString() Method

Javascript date toDateString() method returns the date portion of a Date object in human readable form.
Its syntax is as follows −
Date.toDateString()

Returns the date portion of a Date object in human readable form.
Try the following example.
<html>   
   <head>
      <title>JavaScript toDateString Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var dt = new Date(1993, 6, 28, 14, 39, 7);
         document.write( "Formated Date : " + dt.toDateString() );
      </script>   
   </body>
</html>
Formated Date : Wed Jul 28 1993


    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
Python String upper() Method

Python string  method upper() returns a copy of the string in which all case-based characters have been uppercased.
Following is the syntax for upper() method −
str.upper()

NA
NA
This method returns a copy of the string in which all case-based characters have been uppercased.
The following example shows the usage of upper() method.
#!/usr/bin/python

str = "this is string example....wow!!!";
print "str.capitalize() : ", str.upper()
When we run above program, it produces following result −
str.capitalize() :  THIS IS STRING EXAMPLE....WOW!!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Angular 2 - User Input

In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let’s look at some in detail.
In the app.component.ts file place the following code.
import { 
   Component 
} from '@angular/core';  

@Component ({ 
   selector: 'my-app', 
   template: ' 
      <div> 
         <input [value] = "name" (input) = "name = $event.target.value"> 
         {{name}} 
      </div> 
   ' 
}) 
export class AppComponent { }
Following things need to be noted about the above code.
[value] = ”username” − This is used to bind the expression username to the input element’s value property.
[value] = ”username” − This is used to bind the expression username to the input element’s value property.
(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event.
(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event.
username = $event.target.value − The expression that gets executed when the input event is fired.
username = $event.target.value − The expression that gets executed when the input event is fired.
$event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload.
$event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload.
Once you save all the code changes and refresh the browser, you will get the following output.
You can now type anything and the same input will reflect in the text next to the Input control.
In the app.component.ts file place the following code.
import {
   Component
} from '@angular/core';

@Component ({
   selector: 'my-app',
   template: '<button (click) = "onClickMe()"> Click Me </button> {{clickMessage}}'
})

export class AppComponent {
   clickMessage = 'Hello';
   onClickMe() {
      this.clickMessage = 'This tutorial!';
   }
}
Once you save all the code changes and refresh the browser, you will get the following output.
When you hit the Click Me button, you will get the following output.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Skip method in C#

Use the Skip() method in C# to skip number of elements in an array.
Let’s say the following is our array −
int[] arr = { 10, 20, 30, 40, 50 };
To skip the first two elements, use the Skip() method and add argument as 2 −
arr.Skip(2);
Let us see an example −
 Live Demo
using System.IO;
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      int[] arr = { 10, 20, 30, 40, 50 };
      Console.WriteLine("Initial Array...");
      foreach (var res in arr) {
         Console.WriteLine(res);
      }
      // skipping first two elements
      var ele = arr.Skip(2);
      Console.WriteLine("New Array after skipping elements...");
      foreach (var res in ele) {
         Console.WriteLine(res);
      }
   }
}
Initial Array...
10
20
30
40
50
New Array after skipping elements...
30
40
50
Python – Reshape the data in a Pandas DataFrame

We can easily reshape the data by categorizing a specific column. Here, we will categorize the “Result”column i.e. Pass and Fail values in numbers form.
Import the required library −
import pandas as pd
Create a DataFrame with 2 columns −
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']

   }
)
Reshape the data using the map() function and just set ‘Pass’ to 1 and ‘Fail’ to 0 −
dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })

Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']
   }
)

print"DataFrame ...\n",dataFrame

# reshaping into numbers
dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })

print"\nReshaped DataFrame ...\n",dataFrame
This will produce the following output
DataFrame ...
   Result   Student
0    Pass      Jack
1    Fail     Robin
2    Fail       Ted
3    Pass  Scarlett
4    Pass       Kat

Reshaped DataFrame ...
   Result   Student
0       1      Jack
1       0     Robin
2       0       Ted
3       1  Scarlett
4       1       Kat
grep - Unix, Linux Command

grep - print lines matching a pattern
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
Example-1:
To Search for the given string in a single file test.sh
$ cat test.sh#!/bin/bashfun()        echo "This is a test."        # Terminate our shell script with success message        exit 1fun()
from above file grep exit:
$ grep "exit" demo_file
output:
        exit 1
Example-2:
To Checking for the given string in multiple files: in this case test.sh and test1.sh
$ cat test.sh#!/bin/bashfun()        echo "This is a test."        # Terminate our shell script with success message        exit 1fun()
$ cat test1.sh#!/bin/bashfun()        echo "This is a test1."        # Terminate our shell script with success message        exit 0fun()
grep exit in both files test.sh and test1.sh:
$ grep exit test*
output:
test1.sh:       exit 0test.sh:        exit 1
 
Example-3:
To Case insensitive search using grep -i, added EXIT in test1.sh
$ cat test1.sh#!/bin/bashfun()        echo "This is a test1."        # Terminate our shell script with success message, EXIT with 0        exit 0fun()
$ grep exit test1.shtest1.sh:       exit 0$ grep -i exit test*
output:
test1.sh:       # Terminate our shell script with success message, EXIT with 0test1.sh:       exit 0
two lines with -i option, as its case insensitive.
output:
        echo "This is a test1."
Example-5:
* To Checking for full words, not for sub-strings using grep -w
$ grep -w "exit" test.sh
output:
        exit 1
Note:
$ grep -w ex test.sh -> no output, as full word with ex is not in test.sh
for substring search we should not use -w option.
$ grep ex test.sh
       exit 1
Example-6:
To Invert match using grep -v
$ cat test.sh#!/bin/bashfun()        echo "This is a test."        # Terminate our shell script with success message        exit 1fun()
$ grep -v  exit test.sh
output:
#!/bin/bashfun()        echo "This is a test."        # Terminate our shell script with success message
Note: exit statement is not seen in output.
Example-7:
To print line number of searched string
$ grep -n exit test.sh
output:
5:      exit 1
 

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page