code-rag-bench/online-tutorials huggingface dataset:
JavaScript | Uint8Array.from() Method

28 Jan, 2020
The Uint8Array array represents an array of 8-bit unsigned integers. By default, the contents of Uint8Array are initialized to 0.
The Uint8Array.from() method is used to create a new Uint8Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object then you can be used this function by passing the object as a parameter to this function along with map function and value used for map function if needed.
Syntax:
Uint8Array.from( source, mapFn, thisArg )
parameters: This method accept three parameters as mentioned above and described below:
source: This parameter contains an array-like or iterable object which is used to convert to a Uint8Array object.
mapFn: It is an optional parameter which is Map function to call on every element of the Uint8Array array.
thisArg: It is an optional parameter which store the value to use as this when executing mapFn.
Return Value: This method returns a new Uint8Array instance.
Below example illustrate the working of Uint8Array.from() method in JavaScript:
Program 1:
<script>  // Create a Uint8Array from a string like structurevar  array = Uint8Array.from('45465768654323456');  // Print the resultdocument.write(array);</script>
4, 5, 4, 6, 5, 7, 6, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6
Program 2:
<script>  // Create a Uint8Array from a array by adding// 3 to each number using functionvar  array = Uint8Array.from([1, 2, 3, 4, 5, 6], z => z+3);  // Print the resultdocument.write(array);</script>
4, 5, 6, 7, 8, 9
References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from
javascript-array
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js | fs.writeFileSync() Method
How do you run JavaScript script through the Terminal?
Difference between var, let and const keywords in JavaScript
JavaScript | console.log() with Examples
Differences between Functional Components and Class Components in React
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
REST API (Introduction)
How to fetch data from an API in ReactJS ?
Java - String toUpperCase() Method

This method has two variants. The first variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.getDefault()).
The second variant takes locale as an argument to be used while converting into upper case.
Here is the syntax of this method −
public String toUpperCase()

Here is the detail of parameters −
NA
NA
It returns the String, converted to uppercase.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");

      System.out.print("Return Value :" );
      System.out.println(Str.toUpperCase() );
   }
}
This will produce the following result −
Return Value :WELCOME TO TUTORIALSPOINT.COM
Python PIL | ImageEnhance.Brightness() and ImageEnhance.Sharpness() method

29 Jun, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageEnhance module contains a number of classes that can be used for image enhancement.
This class can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
Syntax:
obj = ImageEnhance.Brightness(image)
obj.enhance(factor)

First, it is required to create an object of corresponding class in order to enhance image.
# This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance  # Opening Imageim = Image.open(r"C:\Users\Admin\Pictures\images.png")  # Creating object of Brightness classim3 = ImageEnhance.Brightness(im)  # showing resultant imageim3.enhance(2.0).show()
Output:For first image factor is 2.0 and for second 5.0
This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.
Syntax:
obj = ImageEnhance.Sharpness(image)
obj.enhance(factor)

First, it is required to create an object of corresponding class in order to enhance image.
# This will import Image and ImageChops modulesfrom PIL import Image, ImageEnhance  # Opening Imageim = Image.open(r"C:\Users\Admin\Pictures\images.png")  # Creating object of Sharpness classim3 = ImageEnhance.Sharpness(im)  # showing resultant imageim3.enhance(-2.0).show()
Output:For first image factor is -2.0 and for second image it is 5.0
Image-Processing
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Types of HTML Lists

There are three types of lists in HTML −
unordered list <ul>This list has bullets list items with no specific order.
This list has bullets list items with no specific order.
ordered list <ol>This list is used for ordered list items
This list is used for ordered list items
definition list <dl>This list is used to display definitions for terms.
This list is used to display definitions for terms.
We can nest these lists and style them as desired. CSS property list-style helps us style the list items.
The syntax of HTML lists is as follows −
<type of list>
<li></li>
</type of list>
The following examples illustrate HTML lists −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
   background-color: papayawhip;
   list-style-type: square;
   font-style: italic;
}
ol {
   background-color: azure;
}
</style>
</head>
<body>
<ol>
<li>demo1</li>
<li>
demo 2
<ul>
<li>demo a</li>
<li>demo b</li>
</ul>
</li>
<li>demo 3</li>
</ol>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
dt {
   font-weight: bold;
   font-style: italic;
}
dd {
   border: thin dotted;
}
</style>
</head>
<body>
<h2>Programming Languages and Databases</h2>
<dl>
<dt>Java</dt>
<dd>A programming language developed by James Gosling.</dd>
<dt>C++</dt>
<dd>A programming language developed by Bjarne Stroustrup.</dd>
<dt>MySQL</dt>
<dd>MySQL is an open-source relational database management system.</dd>
</dl>
</body>
</html>
This gives the following output −
HTML | <textarea> readonly Attribute - GeeksforGeeks

08 Jul, 2021
The <textarea> readonly attribute in HTML is used to specify that the textarea element is read-only. If the textarea is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute.Syntax:  
<textarea readonly> Contents... </textarea>
Example 1: This example uses <textarea> readonly attribute to write content on input textarea which is readable only.  
html
<!DOCTYPE html><html>    <head>        <title>            HTML Textarea readonly Attribute        </title>    </head>         <body style = "text-align:center">                     <h1 style = "color: green;">            GeeksforGeeks        </h1>                 <h2>            HTML Textarea readonly Attribute        </h2>                  <p>A readonly Textarea.</p>              <!--A readonly Textarea-->        <textarea readonly>This textarea field is readonly.        </textarea>    </body></html>                   
Output:  
Example 2: This example uses <textarea> readonly attribute to write content on input textarea which is readable only.  
html
<!DOCTYPE html><html>    <head>        <title>            HTML Textarea readonly Attribute        </title>    </head>         <body style = "text-align:center">                     <h1 style = "color: green;">            GeeksforGeeks        </h1>                 <h2>            HTML Textarea readonly Attribute        </h2>                  <p>A readonly Textbox.</p>                       <textarea readonly="readonly" cols="15" rows="5">            This textarea can't be edited it is readonly only.        </textarea>    </body></html>                   
Output:  
Supported Browsers: The browser supported by <textarea> readonly attribute are listed below:  
Apple Safari
Google Chrome
Firefox
Opera
Internet Explorer
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ruhelaa48
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
MySQL temporary variable assignment?

You can use SET command for temporary variable assignment.
The syntax is as follows
SET @anyVariableName=(SELECT yourColumnName FROM yourTableName WHERE yourCondition);
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table tempVariableAssignment
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.59 sec)
Now insert some records in the table using insert command
mysql> insert into tempVariableAssignment(Name,Age) values('John',25);
Query OK, 1 row affected (0.14 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Carol',26);
Query OK, 1 row affected (0.17 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Sam',28);
Query OK, 1 row affected (0.13 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('David',19);
Query OK, 1 row affected (0.19 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Bob',23);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from tempVariableAssignment;
The following is the output
+----+-------+------+
| Id | Name   Age   |
+----+-------+------+
| 1 | John   | 25   |
| 2 | Carol  | 26   |
| 3 | Sam    | 28   |
| 4 | David  | 19   |
| 5 | Bob    | 23   |
+----+-------+------+
5 rows in set (0.00 sec)
Here is the query for MySQL temporary variable assignment
mysql> set @findAge=(select Age from tempVariableAssignment where Id=4);
Query OK, 0 rows affected (0.02 sec)
Display the value of variable @findAge.
The query is as follows
mysql> select @findAge;
The following is the output
+----------+
| @findAge |
+----------+
| 19       |
+----------+
1 row in set (0.01 sec)
Here is an alternate query
mysql> select Age INTO @anotherAge
-> from tempVariableAssignment where Id=4;
Query OK, 1 row affected (0.00 sec)
Display the value of variable @anotherAge.
The query is as follows
mysql> select @anotherAge;
The following is the output
+-------------+
| @anotherAge |
+-------------+
| 19          |
+-------------+
1 row in set (0.00 sec)
HTML rowspan Attribute

The HTML rowspan attribute define the number of rows a cell of a table should span in an HTML document. It can only be applied on td or th HTML element.
Following is the syntax −
<tagname rowspan=”number”></tagname>
Let us see an example of HTML rowspan Attribute −
Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      background: lightblue;
      height: 100vh;
      text-align: center;
   }
   table {
      margin: 2rem auto;
      width: 400px;
   }
</style>
<body>
<h1>HTML rowspan Attribute Demo</h1>
<table border="2">
<thead>
<tr>
<th>Name</th>
<th>Language</th>
</tr>
<thead>
<tbody>
<tr>
<td>John</td>
<td>English</td>
</tr>
<tr>
<td rowspan="2">Elon</td>
<td>Germany</td>
</tr>
<tr>
<td>French</td>
</tr>
</tbody>
</table>
</body>
</html>
How to link a submit button to another webpage using HTML?

Submit button automatically submits a form on click. Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.
To link a submit button to another webpage, use the form action attribute. Add the link in the attribute, for example − <form action=”/new.php”>
You can try to run the following code to link a submit button to another webpage −
<!DOCTYPE html>
<html>
   <body>
      <form action="/new.php">
         Student Name:<br> <input type="text" name="sname">
         <br>
         Student Subject:<br> <input type="text" name="ssubject">
         <br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
Implement Conditional MySQL Query in a stored procedure?

For conditional MySQL query, you can use IF ELSE concept in stored procedure. Let us first create a table −
mysql> create table DemoTable1
   (
   Id int
   );
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable1 values(20);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable1 values(30);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+------+
| Id   |
+------+
| 10   |
| 20   |
| 30   |
+------+
3 rows in set (0.00 sec)
Following is the query to create second table.
mysql> create table DemoTable2
   (
   Id int
   );
Query OK, 0 rows affected (1.07 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(40);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable2 values(50);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable2 values(60);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+------+
| Id   |
+------+
| 40   |
| 50   |
| 60   |
+------+
3 rows in set (0.00 sec)
Following is the query to create a stored procedure for conditional MySQL query.
mysql> DELIMITER //
   mysql> CREATE PROCEDURE Conditional_Query(id int)
   BEGIN
      IF id >=40 THEN
         Select * from DemoTable2;
     ELSE
        Select * from DemoTable1;
     END IF;
   END
   //
   Query OK, 0 rows affected (0.21 sec)
mysql> DELIMITER ;
Now you can call the stored procedure with the help of CALL command −
mysql> call Conditional_Query(100);
This will produce the following output −
+------+
| Id   |
+------+
| 40   |
| 50   |
| 60   |
+------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.03 sec)
Call again and pass a different value −
mysql> call Conditional_Query(13);
This will produce the following output −
+------+
| Id   |
+------+
| 10   |
| 20   |
| 30   |
+------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.02 sec)
How to add a legend on Seaborn facetgrid bar plot using Matplotlib?

Set the figure size and adjust the padding between and around the subplots.
Create a dataframe with col1 columns.
Multi-plot grid for plotting conditional relationships.
Use map_dataframe(). This method is suitable for plotting with functions that accept a long-form DataFrame as a 'data' keyword argument and access the data in that DataFrame using string variable names.
Add a legend to the plot().
To display the figure, use show() method.
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

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

df = pd.DataFrame({'col1': [3, 7, 8]})

g = sns.FacetGrid(df, col="col1", hue="col1")
g.map_dataframe(sns.scatterplot)
g.set_axis_labels("X", "Y")
g.add_legend()

plt.show()
How to add two numbers in console using Node.js ? - GeeksforGeeks

26 Oct, 2021
In this article, we will see how to add two numbers in the console using NodeJS. For this purpose, we need to know about a node package called prompt. It helps to take user input from the console. We would use its method prompt.get() to take user input.
Create NodeJS Application: Initialize the NodeJS application using the following command:
npm init
Module Installation: Install the prompt module using the following command.
npm install prompt
Implementation: Create an app.js file and write down the following code in it.
 
app.js
// Require would make the prompt// package available to useconst prompt = require("prompt");  // An utility function to add// two numbersfunction add() {  // Start the prompt  prompt.start();    // Get two numbers/properties  // from user num1 and num2  prompt.get(["num1", "num2"],   function (err, res) {    // To handle any error if occurred    if (err) {      console.log(err);    } else {      // By default get methods takes      // input in string So parseFloat      // is used to convert String      // into Float      var sum = parseFloat(res.num1)         + parseFloat(res.num2);        // Print the sum      console.log("Sum of " + res.num1         + " and " + res.num2 + " is " + sum);    }  });}  // Calling add functionadd();
Step to run the application: Run the app.js file using the following command.
node app.js
Output: Now enter the user input and view output in the console.
output
So this is how you can add two numbers in the console using nodeJs. Prompts help us to take input from users. It also supports validation and defaults over the input.
saurabh1990aror
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
DFA in LEX code which accepts strings ending with 11 - GeeksforGeeks

22 May, 2019
Prerequisite: Designing Finite AutomataProblem: Design a LEX code to construct a DFA which accepts the language: all the strings ending with “11” over inputs ‘0’ and ‘1’.
Examples:
Input: 100011 
Output: Accepted

Input: 100101
Output: Not Accepted

Input: asdf
Output: Invalid 
Approach:LEX provides us with an INITIAL state by default. So in order to make a DFA, use this as the initial state of the DFA. Now we define three more states A, B and DEAD where DEAD state would be use if encounter a wrong or invalid input. When user input invalid character, move to DEAD state and print message “INVALID” and if input string ends at state B then display a message “Accepted”. If input string ends at state INITIAL and A then display a message “Not Accepted”.
Note:To compile a LEX program, user need a UNIX system and flex which can be installed using sudo apt-get install flex. With all the above specification open UNIX terminal and do the following:
Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file.Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file.
Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file.
Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file.
lex lextest
cc lex.yy.c -lfl 
LEX Code:
%{%}  %s A B DEAD  %%<INITIAL>1 BEGIN A;<INITIAL>0 BEGIN INITIAL;<INITIAL>[^01\n] BEGIN DEAD;<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}  <A>1 BEGIN B;<A>0 BEGIN INITIAL;<A>[^01\n] BEGIN DEAD;<A>\n BEGIN INITIAL; {printf("Not Accepted\n");}  <B>1 BEGIN B;<B>0 BEGIN INITIAL;<B>[^01\n] BEGIN DEAD;<B>\n BEGIN INITIAL; {printf("Accepted\n");}   <DEAD>[^\n] BEGIN DEAD;<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");}   %%  int main(){    printf("Enter String\n");    yylex();return 0;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Difference between Top down parsing and Bottom up parsing
Compiler construction tools
Why FIRST and FOLLOW in Compiler Design?
SLR Parser (with Examples)
Lex program to count the number of lines, spaces and tabs
Bottom Up or Shift Reduce Parsers | Set 2
Parsing | Set 1 (Introduction, Ambiguity and Parsers)
Error detection and Recovery in Compiler
Validate IP Address in C++

This article is serving the purpose of validating the correct IP (internet protocol) address by virtue of C++ code programming. The IP address is a 32-bit dot-decimal-notation, broken into four decimal numbers segments ranging from 0 to 255. Furthermore, these numbers are separated by
dots consecutively. The IP address serves the purpose of identifying a host machine in the network in a unique manner in order to establish a connection among them.
So, in order to validate the correct IP address input from the user-end, the following algorithm briefs how exactly the code sequence is materialized to identify the correct IP address as follows;
START
   Step-1: Input the IP address
   Step-2: Spilt the IP into four segments and store in an array
   Step-3: Check whether it numeric or not using
   Step-4: Traverse the array list using foreach loop
   Step-5: Check its range (below 256) and data format
   Step-6: Call the validate method in the Main()
END
Thence, as per the algorithm the following c++ drafted to validate the IP address, in which couple of essentials functions are being employed to determine the numeric form, range, and splitting the input data respectively;
 Live Demo
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// check if the given string is a numeric string or not
bool chkNumber(const string& str){
   return !str.empty() &&
   (str.find_first_not_of("[0123456789]") == std::string::npos);
}
// Function to split string str using given delimiter
vector<string> split(const string& str, char delim){
   auto i = 0;
   vector<string> list;
   auto pos = str.find(delim);
   while (pos != string::npos){
      list.push_back(str.substr(i, pos - i));
      i = ++pos;
      pos = str.find(delim, pos);
   }
   list.push_back(str.substr(i, str.length()));
   return list;
}
// Function to validate an IP address
bool validateIP(string ip){
   // split the string into tokens
   vector<string> slist = split(ip, '.');
   // if token size is not equal to four
   if (slist.size() != 4)
      return false;
   for (string str : slist){
      // check that string is number, positive, and range
      if (!chkNumber(str) || stoi(str) < 0 || stoi(str) > 255)
         return false;
   }
   return true;
}
   // Validate an IP address in C++
int main(){
   cout<<"Enter the IP Address::";
   string ip;
   cin>>ip;
   if (validateIP(ip))
      cout <<endl<< "***It is a Valid IP Address***";
   else
      cout <<endl<< "***Invalid IP Address***";
   return 0;
}
After the compilation of the above code using a standard c++ editor, the following output is being produced which is duly checking whether the input number 10.10.10.2 is a correct IP address or not as follows;
Enter the IP Address:: 10.10.10.2
***It is a Valid IP Assress***
Get last n records of a Pandas DataFrame - GeeksforGeeks

26 Jul, 2020
Let’s discuss how to get last n records of a Pandas DAtaframe. There can be various methods to get the last n records of a Pandas DataFrame. Lets first make a dataframe:Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np  # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel',                 'Sanskriti', 'Abhishek Jain'],        'Age': [22, 20, np.inf, -np.inf, 22],         'Marks': [90, 84, 33, 87, 82]}  # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict)  # Print Dataframedf
Output:  
 
Method 1: Using tail() method
Use pandas.DataFrame.tail(n) to get the last n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the end). By default n = 5, it return the last 5 rows if the value of n is not passed to the method.
Syntax: 
df.tail(n)

Example:
Python3
# Getting last 3 rows from dfdf_last_3 = df.tail(3)  # Printing df_last_3print(df_last_3)
Output:  
 
Method 2: Using pandas.DataFrame.iloc
Use pandas.DataFrame.iloc to get last n rows. It is similar to the list slicing.Syntax: 
df.iloc[-n:]

Example:
Python3
# Getting last 3 rows from dfdf_last_3 = df.iloc[-3:]  # Printing df_last_3print(df_last_3)
Output:  
Method 3: Display last n records of specific columnsDisplay last n records for the specific column
Python3
# Getting last 2 rows of columns # Age and Marks from dfdf_last_2 = df[['Age', 'Marks']].tail(2)  # Printing df_last_2print(df_last_2)
Output:  
Method 4: Display last n records from last n columnsDisplay last n records for the last n columns using pandas.DataFrame.iloc
Python3
# Getting last n rows and last n columns from dfdf_last_2_row_col = df.iloc[-2:,-2:]  # Printing df_last_2print(df_last_2_row_col)
Output: 
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
Find Nth term of the series 5, 13, 25, 41, 61... - GeeksforGeeks

15 Mar, 2021
Given a number N. The task is to write a program to find the Nth term in the below series:  
5, 13, 25, 41, 61...
Examples:  
Input : 3
Output : 25
For N = 3
Nth term = 3*3 + (3+1)*(3+1)
         = 25
Input : 5
Output : 61
 
On observing carefully, the Nth term of the given series can be generalised as:  
Nth term = N2 + (N+1)2
Below is the implementation of the above approach: 
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find N-th term of the series:// 5, 13, 25, 41, 61...#include <iostream>using namespace std; // calculate Nth term of seriesint nthTerm(int N){    return N * N + (N + 1) * (N + 1);} // Driver Functionint main(){    int N = 3;     cout << nthTerm(N);     return 0;}
// Java program to calculate Nth term of// the series: 5, 13, 25, 41, 61... import java.io.*; class Nth {    public static int nthTerm(int N)    {        // By using above formula        return N * N + (N + 1) * (N + 1);    }         public static void main(String[] args)    {        int N = 3; // Nth term is 25                 // call and print Nth term        System.out.println(nthTerm(N));    }   }
# Python 3 program to find# N-th term of the series:# 5, 13, 25, 41, 61... # Function to calculate# Nth term of seriesdef nthTerm(N) :    return N * N + (N + 1) * (N + 1) # Driver Codeif __name__ == "__main__" :     N = 3     # function calling    print(nthTerm(N)) # This code is contributed# by ANKITRAI1
// C# program to calculate Nth term of// the series: 5, 13, 25, 41, 61...using System; class GFG{public static int nthTerm(int N){    // By using above formula    return N * N + (N + 1) * (N + 1);} // Driver Codepublic static void Main(){    int N = 3; // Nth term is 25         // call and print Nth term    Console.Write(nthTerm(N));}} // This code is contributed// by ChitraNayal
<?php// PHP program to find N-th// term of the series:// 5, 13, 25, 41, 61... // calculate Nth term of seriesfunction nthTerm($N){    return $N * $N + ($N + 1) *                     ($N + 1);} // Driver Code$N = 3; echo nthTerm($N); // This code is contributed// by ChitraNayal?>
<script> // JavaScript program to find N-th term of the series:// 5, 13, 25, 41, 61... // calculate Nth term of seriesfunction nthTerm( N){    return N * N + (N + 1) * (N + 1);}// Driver Function     let N = 3;    document.write(nthTerm(N));     // This code contributed by Rajput-Ji </script>
25
 
Time Complexity: O(1) 
ankthon
ukasp
Rajput-Ji
math
series
C++ Programs
Java Programs
School Programming
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Dynamic subplot layout in Seaborn | by Daniel Deutsch | Towards Data Science

Seaborn is one of the most used visualization libraries and I enjoy working with it. In my latest projects, I wanted to visualize multiple subplots in a dynamic way. To my surprise I didn’t find a straight forward solution anywhere online, so I want to share my way of doing it. It can be quite useful in any data analysis endeavor.
The problem
The approach
The solution
Changing it to 2 columns it will look like this
Changing it to 4 columns it will look like this
About
Let’s see the titanic dataset for example:
There are multiple categorical variables, which we might like to visualize with countplots. Doing this by copying the code in every new cell is not optimal:
There is a FacetGrid option for seaborn:
However, I would like to have different subplots, on which I can set each plot for myself.
Thankfully there is the subplot functionality:
categorical_vars = ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch',       'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town',       'alive', 'alone']fig, axs = plt.subplots(nrows=2, ncols=2)for i, var in enumerate(categorical_vars):    row = i//2    pos = i % 2    plot = sns.countplot(x=var, data=titanic, ax=axs[row][pos])
Which leads to:
This demonstrates the issues I always encountered. For multiple variables, I always need to set the number of rows and columns manually. (fig, axs = plt.subplots(nrows=2, ncols=2))
To solve this I, changed it to:
categorical_vars = ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch',       'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town',       'alive', 'alone']num_plots = len(categorical_vars)total_cols = 3total_rows = num_plots//total_cols + 1fig, axs = plt.subplots(nrows=total_rows, ncols=total_cols,                        figsize=(7*total_cols, 7*total_rows), constrained_layout=True)for i, var in enumerate(categorical_vars):    row = i//total_cols    pos = i % total_cols    plot = sns.countplot(x=var, data=titanic, ax=axs[row][pos])
Which leads to this:
Now I can define the layout of the plots to my wishes and also can decide what to plot. Even though it seems quite easy, I didn’t find anything related online. So maybe this helps some of you ;)
Daniel is an entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court.
His knowledge and interests currently revolve around programming machine learning applications and all its related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects.
Don’t hesitate to get in touch if you have ideas, projects, or problems.
You can support me on https://www.buymeacoffee.com/createdd
Java program to print Pascal's triangle

Pascal's triangle is one of the classic example taught to engineering students. It has many interpretations. One of the famous one is its use with binomial equations.
All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire a space in Pascal’s triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0). The output is sandwiched between two zeroes. The process continues till the required level is achieved.
Take a number of rows to be printed, n.
Make outer iteration I for n times to print rows.
Make inner iteration for J to (N - 1).
Print single blank space " ".
Close inner loop.
Make inner iteration for J to I.
Print nCr of I and J.
Close inner loop.
Print NEWLINE character after each inner iteration.
Live Demo
public class PascalsTriangle {
   static int factorial(int n) {
      int f;

      for(f = 1; n > 1; n--){
         f *= n;
      }
      return f;
   }
   static int ncr(int n,int r) {
      return factorial(n) / ( factorial(n-r) * factorial(r) );
   }
   public static void main(String args[]){
      System.out.println();
      int n, i, j;
      n = 5;

      for(i = 0; i <= n; i++) {
         for(j = 0; j <= n-i; j++){
            System.out.print(" ");
         }
         for(j = 0; j <= i; j++){
            System.out.print(" "+ncr(i, j));
         }
         System.out.println();
      }
   }
}
             1
          1     1
        1    2    1
      1    3   3     1
   1    4     6    4    1
1   5   10     10    5    1
Convert list to array in R - GeeksforGeeks

01 Sep, 2021
A list can be converted to array in R by calling unlist( ) function with created list as parameter. Now pass the unlist() function into array() function as parameter, and use dim attribute for specifying number of rows, columns and matrices. unlist() converts list to vector.
 Syntax : 
array( unlist( list_variable ) , dim = ( rows ,columns , matrices ))
Given below are various implementation for the same:
Example 1 :
R
lst1=list(1:10) arr=array(unlist(lst1),dim=c(3,3,3))print(arr)
Output :
Example 2 :
R
lst1=list(c("karthik","nikhil","sravan")) arr=array(unlist(lst1),dim=c(1,3,3))print(arr)
Output:
Example 3 :
R
lst1=list(c("karthik","chandu","nandu")) arr=array(unlist(lst1),dim=c(1,3,2))print(arr)
Output:
gulshankumarar231
R Array-Programs
R List-Programs
R-Arrays
R-List
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
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?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
How to change the order of bars in bar chart in R ?
R - if statement
Replace Specific Characters in String in R
Java - Assignment Operators Example

The following program is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in Test.java file. Compile and run this program −
public class Test {

   public static void main(String args[]) {
      int a = 10;
      int b = 20;
      int c = 0;

      c = a + b;
      System.out.println("c = a + b = " + c );

      c += a ;
      System.out.println("c += a  = " + c );

      c -= a ;
      System.out.println("c -= a = " + c );

      c *= a ;
      System.out.println("c *= a = " + c );

      a = 10;
      c = 15;
      c /= a ;
      System.out.println("c /= a = " + c );

      a = 10;
      c = 15;
      c %= a ;
      System.out.println("c %= a  = " + c );

      c <<= 2 ;
      System.out.println("c <<= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c &= a ;
      System.out.println("c &= a  = " + c );

      c ^= a ;
      System.out.println("c ^= a   = " + c );

      c |= a ;
      System.out.println("c |= a   = " + c );
   }
}
This will produce the following result −
c = a + b = 30
c += a  = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a  = 0
c ^= a   = 10
c |= a   = 10


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to extract a string that lies between two strings in R?

If we have a long string then we might want to extract a part of string that lies between two strings. For example, if we have a string “E-learning changing the education system in the world” and we want to extract the string “the education system” brave then we must be very careful about passing the strings in string function, you get to know this in examples. The extraction is not difficult with gsub function but we have to make sure that we are using the correct syntax, otherwise, the result will become obnoxious.
x1<-"E-learning changing the education system in the world"
gsub(".*changing (.+) in.*", "\\1",x1)
[1] "the education system"
gsub(".*the (.+) system.*", "\\1",x1)
[1] "education"
x2<-"Tutorialspoint helping programmers around the world"
gsub(".*helping (.+) around.*", "\\1",x2)
[1] "programmers"
gsub(".*Tutorialspoint (.+) programmers.*", "\\1",x2)
[1] "helping"
gsub(".*helping (.+) the.*", "\\1",x2)
[1] "programmers around"
x3<-"kindness is a mark of faith, and whoever has not kindness has not faith"
gsub(".*a (.+) of.*", "\\1",x3)
[1] "mark"
gsub(".*and (.+) has.*", "\\1",x3)
[1] "whoever has not kindness"
gsub(".*has (.+) has.*", "\\1",x3)
[1] "not kindness"
gsub(".*has (.+) faith.*", "\\1",x3)
[1] "not"
gsub(".*and (.+) faith.*", "\\1",x3)
[1] "whoever has not kindness has not"
gsub(".*of (.+) whoever.*", "\\1",x3)
[1] "faith, and"
gsub(".*of (.+) and.*", "\\1",x3)
[1] "faith,"
x4<-"None of you truly believes until he wishes for his brother what he wishes for himself."
gsub(".*of (.+) truly.*", "\\1",x4)
[1] "you"
gsub(".*believes (.+) until.*", "\\1",x4)
[1] "None of you truly believes until he wishes for his brother what he wishes for himself."
gsub(".*believes (.+) for.*", "\\1",x4)
[1] "until he wishes for his brother what he wishes"
gsub(".*you (.+) until.*", "\\1",x4)
[1] "truly believes"
gsub(".*his (.+) what.*", "\\1",x4)
[1] "brother"
gsub(".*he (.+) for.*", "\\1",x4)
[1] "wishes"
gsub(".*until (.+) for.*", "\\1",x4)
[1] "he wishes for his brother what he wishes"
gsub(".*truly (.+) until.*", "\\1",x4)
[1] "believes"
gsub(".*truly (.+) what.*", "\\1",x4)
[1] "believes until he wishes for his brother"
gsub(".*truly (.+) for.*", "\\1",x4)
[1] "believes until he wishes for his brother what he wishes"
gsub(".*until (.+) what.*", "\\1",x4)
[1] "he wishes for his brother"
x5<-"To overcome evil with good is good, to resist evil by evil is evil."
gsub(".*To (.+) with.*", "\\1",x5)
[1] "overcome evil"
gsub(".*good (.+) good.*", "\\1",x5)
[1] "is"
gsub(".*resist (.+) evil.*", "\\1",x5)
[1] "evil by evil is"
gsub(".*to (.+) evil.*", "\\1",x5)
[1] "resist evil by evil is"
gsub(".*evil (.+) evil.*", "\\1",x5)
[1] "is"
gsub(".*To (.+) evil.*", "\\1",x5)
[1] "overcome evil with good is good, to resist evil by evil is"
gsub(".*good, (.+) resist.*", "\\1",x5)
[1] "to"
gsub(".with (.+) is.*", "\\1",x5)
[1] "To overcome evilgood is good, to resist evil by evil"
YAML - Flow Styles

Flow styles in YAML can be thought of as a natural extension of JSON to cover the folding content lines for better readable feature which uses anchors and aliases to create the object instances. In this chapter, we will focus on flow representation of the following concepts −
Alias Nodes
Empty Nodes
Flow Scalar styles
Flow collection styles
Flow nodes
The example of alias nodes is shown below −
%YAML 1.2
---
!!map {
   ? !!str "First occurrence"
   : &A !!str "Foo",
   ? !!str "Override anchor"
   : &B !!str "Bar",
   ? !!str "Second occurrence"
   : *A,
   ? !!str "Reuse anchor"
   : *B,
}
The JSON output of the code given above is given below −
{
   "First occurrence": "Foo", 
   "Second occurrence": "Foo", 
   "Override anchor": "Bar", 
   "Reuse anchor": "Bar"
}

Nodes with empty content are considered as empty nodes. The following example shows this −
%YAML 1.2
---
!!map {
   ? !!str "foo" : !!str "",
   ? !!str "" : !!str "bar",
}
The output of empty nodes in JSON is represented as below −
{
   "": "bar", 
   "foo": ""
}

Flow scalar styles include double-quoted, single-quoted and plain types. The basic example for the same is given below −
%YAML 1.2
---
!!map {
   ? !!str "implicit block key"
   : !!seq [
      !!map {
         ? !!str "implicit flow key"
         : !!str "value",
      }
   ]  
}
The output in JSON format for the example given above is shown below −
{
   "implicit block key": [
      {
         "implicit flow key": "value"
      }
   ] 
}

Flow collection in YAML is nested with a block collection within another flow collection. Flow collection entries are terminated with comma (,) indicator. The following example explains the flow collection block in detail −
%YAML 1.2
---
!!seq [
   !!seq [
      !!str "one",
      !!str "two",
   ],
   
   !!seq [
      !!str "three",
      !!str "four",
   ],
]
The output for flow collection in JSON is shown below −
[
   [
      "one", 
      "two"
   ], 
   [
      "three", 
      "four"
   ]
]

Flow styles like JSON include start and end indicators. The only flow style that does not have any property is the plain scalar.
%YAML 1.2
---
!!seq [
!!seq [ !!str "a", !!str "b" ],
!!map { ? !!str "a" : !!str "b" },
!!str "a",
!!str "b",
!!str "c",]
The output for the code shown above in JSON format is given below −
[
   [
      "a", 
      "b"
   ], 
   
   {
      "a": "b"
   }, 
   
   "a", 
   "b", 
   "c"
]


    33 Lectures 
     44 mins

 Tarun Telang
 Print
 Add Notes
 Bookmark this page
Bootstrap class to emphasize text

HTML's default emphasis tags such as <small> sets text at 85% the size of the parent, <strong> emphasizes a text with heavier font-weight, and <em> emphasizes a text in italics.
You can try to run the following code to an emphasis on text −
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap emphasis tags</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <small>This content is within tag</small><br>
      <strong>This content is within tag</strong><br>
      <em>This content is within tag and is rendered as italics</em><br>
      <p class = "text-left">Left aligned text.</p>
      <p class = "text-center">Center aligned text.</p>
      <p class = "text-right">Right aligned text.</p>
      <p class = "text-muted">This content is muted</p>
      <p class = "text-primary">This content carries a primary class</p>
      <p class = "text-danger">This content carries a danger class</p>
   </body>
</html>
Base64 Encoding and Decoding

Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (PEM) and is primarily used in email encryption process.
Python includes a module called BASE64 which includes two primary functions as given below −
base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.
base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object.
Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object.
Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object.
You can use the following piece of code to perform base64 encoding −
import base64
encoded_data = base64.b64encode("Encode this text")

print("Encoded text with base 64 is")
print(encoded_data)
The code for base64 encoding gives you the following output −
You can use the following piece of code to perform base64 decoding −
import base64
decoded_data = base64.b64decode("RW5jb2RlIHRoaXMgdGV4dA==")

print("decoded text is ")
print(decoded_data)
The code for base64 decoding gives you the following output −
You can observe the following differences when you work on ASCII and base64 for encoding data −
When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.
When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.
When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.
When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.
Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
jQuery - Element Name Selector

The element selector selects all the elements that have a tag name of T.
Here is the simple syntax to use this selector −
$('tagname')

Here is the description of all the parameters used by this selector −
tagname − Any standard HTML tag name like div, p, em, img, li etc.
tagname − Any standard HTML tag name like div, p, em, img, li etc.
Like any other jQuery selector, this selector also returns an array filled with the found elements.
$('p') − Selects all elements with a tag name of p in the document.
$('p') − Selects all elements with a tag name of p in the document.
$('div') − Selects all elements with a tag name of div in the document.
$('div') − Selects all elements with a tag name of div in the document.
Following example would select all the divisions and will apply yellow color to their background −
<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            /* This would select all the divisions */
            $("div").css("background-color", "yellow");
         });
      </script>
   </head>
	
   <body>
      <div class = "big" id = "div1">
         <p>This is first division of the DOM.</p>
      </div>

      <div class = "medium" id = "div2">
         <p>This is second division of the DOM.</p>
      </div>

      <div class = "small" id = "div3">
         <p>This is third division of the DOM</p>
      </div>
   </body>
</html>
This will produce following result −
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page