code-rag-bench/online-tutorials huggingface dataset:
Create a Pivot Table as a DataFrame – Python Pandas

To create a Pivot Table, use the pandas.pivot_table() to create a spreadsheet-style pivot table as a DataFrame.
At first, import the required library −
import pandas as pd
Create a DataFrame with Team records −
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})
Create a Pivot Table: with a single column −
pd.pivot_table(dataFrame, index = ["Team ID"])

Following is the code −
import pandas as pd

# create DataFrame with Team records
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})

print"DataFrame...\n",dataFrame

print"\n... Pivot ..."
print(pd.pivot_table(dataFrame, index = ["Team ID"]))
This will produce the following output −
DataFrame...
   Team ID     Team Name   Team Points   Team Rank
0        5         India            95         One
1        9     Australia            93         Two
2        6    Bangladesh            42         Six
3       11  South Africa            60        Four
4        2     Sri Lanka            80       Three
5        7       England            55        Five

... Pivot ...
          Team Points
Team ID
2                  80
5                  95
6                  42
7                  55
9                  93
11                 60
Difference between String buffer and String builder in Java

String buffer and StringBuilder both are mutable classes which can be used to do operation on string objects such as reverse of string, concating string and etc. We can modify string without creating a new object of the string. A string buffer is thread-safe whereas string builder is not thread-safe.  Therefore, it is faster than a string buffer. Also, a string concat + operator internally uses StringBuffer or StringBuilder class. Below are the differences.
public class StringBuilderExample{
   public static void main(String[] args){
      StringBuilder builder=new StringBuilder("Hi");
      builder.append("Java 8");
      System.out.println("StringBuilderExample" +builder);
   }
}
public class StringBufferExample{
   public static void main(String[] args){
      StringBuffer buffer=new StringBuffer("Hi");
      buffer.append("Java 8");
      System.out.println("StringBufferExample" +buffer);
   }
}
How to create a navigation bar with left-aligned and right-aligned links with CSS?

Following is the code to create a navigation bar with left-aligned and right-aligned links −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
   margin:0px;
   margin-top:60px;
   padding: 0px;
}
nav{
   display: flex;
   position: fixed;
   top:0;
   width: 100%;
   background-color: rgb(251, 255, 196);
   overflow: auto;
   height: auto;
}
.left-links{
   flex:1 1 200px;
}
.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   color: rgb(0, 0, 0);
   text-decoration: none;
   font-size: 17px;
   font-weight: bolder;
}
.links:hover {
   border-bottom: 2px solid purple;
}
.selected{
   border-bottom: 2px solid purple;
}
</style>
</head>
<body>
<nav>
<div class="left-links">
<a class="links selected" href="#">Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
</div>
<div class="right-links">
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#">More Info</a>
</div>
</nav>
<h1>Hover on the above links</h1>
</body>
</html>
The above code will produce the following output −
Rexx - Strings

Strings in Rexx are denoted by a sequence of characters. The following program is an example of strings −
/* Main program */ 
a = "This is a string" 
say a
The output of the above program is as follows −
This is a string 

Let’s discuss some methods which are available in Rexx for strings.
This method returns a certain number of characters from the left of the string.
This method returns a certain number of characters from the right of the string.
This method returns the number of characters in the string.
This method returns the characters in a reverse format.
This method compares 2 strings. Returns "0" if "string1" and "string2" are identical. Otherwise, it returns the position of the first character that does not match.
This method copies a string n number of times.
This method gets a sub string from a particular string.
This method returns the position of one string within another.
This method deletes a sub string from within a string.
 Print
 Add Notes
 Bookmark this page
Is it possible to give arguments in the main() function in C language?

Yes, we can give arguments in the main() function.
Command line arguments in C are specified after the name of the program in the system’s command line, and these argument values are passed on to your program during program execution.
The argc and argv are the two arguments that can pass to main function.
But main() function is actually called by the operating system (or shell program) when you run the program from the terminal.
The syntax is explained below −
int main(int argc, char *argv[]){
   //Code
   return 0;
}
 Live Demo
#include<stdio.h>
int main(int argc, char *argv[]){
   int i;
   for (i = 0; i < argc; i++) {
      printf("Arg %d: %s\n", i, argv[i]);
   }
   return 1;
}
Arg 0: G:\CP\CP programs\main with arguments.exe
Explanation:
The program that prints all the arguments passed to your program, including the program name itself.
SQL Tryit Editor v1.6

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Partial Functions in Python - GeeksforGeeks

10 Feb, 2020
Partial functions allow us to fix a certain number of arguments of a function and generate a new function.
Example:
from functools import partial  # A normal functiondef f(a, b, c, x):    return 1000*a + 100*b + 10*c + x  # A partial function that calls f with# a as 3, b as 1 and c as 4.g = partial(f, 3, 1, 4)  # Calling g()print(g(5))
Output:
3145

In the example we have pre-filled our function with some constant values of a, b and c. And g() just takes a single argument i.e. the variable x.
Another Example :
from functools import *  # A normal functiondef add(a, b, c):    return 100 * a + 10 * b + c  # A partial function with b = 1 and c = 2add_part = partial(add, c = 2, b = 1)  # Calling partial functionprint(add_part(3))
Output:
312

Partial functions can be used to derive specialized functions from general functions and therefore help us to reuse our code.
This feature is similar to bind in C++.
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Partial Functions in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rI8gqpHOyw8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Append row to CSV using R - GeeksforGeeks

28 Apr, 2021
In this article, we will see how to append rows to a CSV file using R Programming Language. 
By default, the write.csv() function overwrites entire file content. In order to append the data to a CSV File, use the write.table() method instead and set the parameter, append = TRUE. The write.table method prints its required argument x, upon conversion of the .csv file into the data frame to a file or connection. 
Syntax:
write.table(x, file = “”, append = FALSE, quote = TRUE, sep = ” “, row.names = TRUE, col.names = TRUE)
Parameters:
x : The row data in the data frame object
file : The file to append row to
sep : The field separator string, that is within each row of x values are separated by this separator.
In case the file is empty, the contents are written on to the .csv file upon creation within the same directory. The following code illustrates the applicability of write.table() method on an empty .csv file. 
Example
R
# defining the data for the csv file # data is organised into 4 columnsdata = data.frame(ID = 1:4, Name = c("A","B","C","D"),                  Post=c("Peon","SDE","Manager","SDE"),                   Age = c(23,39,28,39))  # write data to a sample.csv filewrite.table(data, file = "sample.csv") 
Output
The contents are written onto the empty sample.csv file
The following snippet shows how to append a row to the CSV file already composed of a few rows. The changes are made to the specified CSV file, and upon each operation, one-row count is incremented. 
Example:
R
# defining a row row <- data.frame('1', 'A', 'Manager', '24')  # sample csv namecsv_fname = "sample.csv"  # writing row in the csv filewrite.table(row, file = csv_fname, sep = ",",            append = TRUE, quote = FALSE,            col.names = FALSE, row.names = FALSE)
Output
“sample.csv” : After the execution of Python script
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
Compiling a C++ program with GCC

Here we will see how to compile C++ program using GCC (GNU C Compiler). Let us consider, we want to compile this program.
#include<iostream>
using namespace std;
main() {
   cout << "Hello World. This is C++ program" << endl;
}
If this is a C program, we can compile with GCC like below −
gcc test.c
But if we put c++ filename in that area, it may generate some error.
gcc test.cpp
/tmp/ccf1KGDi.o: In function `main':
1325.test.cpp:(.text+0xe): undefined reference to `std::cout'
1325.test.cpp:(.text+0x13): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& 
std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
1325.test.cpp:(.text+0x1d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, 
std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
1325.test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccf1KGDi.o: In function `__static_initialization_and_destruction_0(int, int)':
1325.test.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::Init()'
1325.test.cpp:(.text+0x6d): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
$
This is not compilation error. This is linking error. To add the correct linker, we have to use –lstdc++ option.
gcc test.cpp -lstdc++
$ ./a.out
Hello World. This is C++ program
$
Convert string to char array in Java

The following is our string.
String str = "Tutorial";
Now, use the toCharArray() method to convert string to char array.
char[] ch = str.toCharArray();
Now let us see the complete example.
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str = "Tutorial";
      System.out.println("String: "+str);
      char[] ch = str.toCharArray();
      System.out.println("Character Array...");
      for (int i = 0; i < ch.length; i++) {
         System.out.print(ch[i]+" ");
      }
   }
}
String: Tutorial
Character Array...
T u t o r i a l
How to detect the Internet connection is offline or not using JavaScript? - GeeksforGeeks

28 Jan, 2020
In some cases, it is necessary to determine whether the browser is online or offline before performing a required task. Many developers use AJAX to determine the connection status of the browser (online or offline) by sending a request to the server. However, this is not a good method for determining the state of the browser because it requires bandwidth and can also affect usability.
Yet JavaScript’s Browser Object Model(BOM) provides a direct way to detect browser’s connectivity status i.e. whether the browser is online or offline.
To perform this check, targeting all possible browsers out there, we will be using the following property :
navigator.onLine
Syntax:
function isOnline() { 
    return ( navigator.onLine) 
}
Example: This example displays a button if it is clicked, It will show the connectivity status.
<!DOCTYPE html><html>  <body>      <p>Click the button to check       if the browser is online.</p>      <button onclick="isOnline()">      Click Me  </button>      <p id="demo"></p>      <script>        function isOnline() {              if (navigator.onLine) {                document.getElementById(                  "demo").innerHTML = "Online";            } else {                document.getElementById(                  "demo").innerHTML = "Offline";            }        }    </script>  </body>  </html>
Note: The minimum version of browsers that supports the property:
Google Chrome: 14.0
Internet Explorer: Yes
Firefox: 3.5
Safari: 5.0.4
Opera: Yes
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
JavaScript-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
HTML Cheat Sheet - A Basic Guide to HTML
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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
CSS Buttons - Pushy Buttons Usage

Pushy Buttons library is a small CSS Pressable Buttons library.
To load the pushy-buttons.min.css library, download the css from github and paste the following line in the <head> section of the webpage.
<head>
   <link rel = "stylesheet" href = "pushy-buttons.min.css">
</head>

Create a button using html button tag and add styles btn, btn-blue with size specifier btn-lg.
<html>
   <head>
      <link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css">
   </head>
   
   <body>
      <button class = "btn btn--blue">Submit</button>
   </body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
   <head>
      <link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css">
   </head>
   
   <body>
      <button class = "btn btn--lg btn--blue">Large</button>
      <button class = "btn btn--df btn--blue">Normal</button>
      <button class = "btn btn--md btn--blue">Medium</button>
      <button class = "btn btn--sm btn--blue">Small</button>
   </body>
</html>
It will produce the following output −
Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button.
<html>
   <head>
      <link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css">
   </head>
   
   <body>
      <button class = "btn btn--lg btn--red">Large</button>
      <button class = "btn btn--df btn--green">Normal</button>
      <button class = "btn btn--md btn--blue">Medium</button>
   </body>
</html>
It will produce the following output −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Check if a large number is divisible by 3 or not in C++

Here we will see how to check a number is divisible by 3 or not. In this case the number is very large number. So we put the number as string.
A number will be divisible by 3, if the sum of digits is divisible by 3.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isDiv3(string num){
   int n = num.length();
   long sum = accumulate(begin(num), end(num), 0) - '0' * n;
   if(sum % 3 == 0)
      return true;
      return false;
}
int main() {
   string num = "3635883959606670431112222";
   if(isDiv3(num)){
      cout << "Divisible";
   } else {
      cout << "Not Divisible";
   }
}
Divisible
PyCairo- Drawing Function curve - GeeksforGeeks

23 Jan, 2022
In this article we will learn how we can draw a simple function curve using PyCairo in python. n mathematics, the graph of a function f is the set of ordered pairs, where f(x) = y. In the common case where x and f(x) are real numbers, these pairs are Cartesian coordinates of points in two-dimensional space.
PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format.  
SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web.
Steps of Implementation :
Import the Pycairo & Math module.Create a SVG surface object and add context to it.Creating list for creating points for functional curveTraversing and plotting PointsSetting color of the context & line width
Import the Pycairo & Math module.
Create a SVG surface object and add context to it.
Creating list for creating points for functional curve
Traversing and plotting Points
Setting color of the context & line width
Below is the Implementation :
Python3
# importing pycairoimport cairo# importing Math to Sin & exp Functionimport math # Variable Xx = 0# Creating list for creating pointspoints = []# Creating Loop for pointswhile x < 5:    # Creating point corresponding x    y = math.sin(10*x)*math.exp(-x/2)    # Adding points to the list    points.append((x*100 + 50, y*100 + 200))    # Incrementing by 0.01 Variable x    x += 0.01 # creating a SVG surface# here geek95 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek95.svg", 700, 700) as surface:     # creating a cairo context object for SVG surface    # using Context method    context = cairo.Context(surface)     context.move_to(*points[0])    # Traversing Points    for p in points[1:]:        # Ploting point        context.line_to(*p)     # setting width of the context    context.set_line_width(2)    # setting color of the context    context.set_source_rgb(0.2, 1, 0.2)    # stroke out the color and width property    context.stroke() # printing message when file is savedprint("File Saved")
Output :
saurabh1990aror
Python-PyCairo
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
What is use of $error variable in PowerShell?

Error variable in PowerShell is to view the errors generated in the current PowerShell session. We can say that the $Error variable is the container that stores all the errors and the latest error will be displayed first. For the example below, we will set the $Errorview to Category view to minimizing the error display content. By default $ErrorView is a Normal view.
$ErrorView = "Categoryview"
Now we will see the $error variable example,
PS C:\WINDOWS\system32> asdds
ObjectNotFound: (asdds:String) [], CommandNotFoundException
PS C:\WINDOWS\system32> Get-process asddsd
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
Here, there is one wrong command and one wrong input we have written so let see what $error variable contains.
PS C:\WINDOWS\system32> $error
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException
In the above output, the last error will be displayed first, and so on. $Errorvariable has become an array now. You can get the individual output as an array typical method.
PS C:\WINDOWS\system32> $error[0]
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
PS C:\WINDOWS\system32> $error[1] ObjectNotFound: (asdds:String) [], CommandNotFoundException
To get the count of errors generated,
PS C:\WINDOWS\system32> $error.Count
2
To check the error capacity, you can run the below command.
PS C:\WINDOWS\system32> $error.Capacity
4
When the capacity of storing error reaches 4, again this variable automatically increases its capacity by 4, so the total capacity becomes 8. So every time the error variable reaches its capacity, it increases the capacity by 4.
For example,
We already created 4 errors here,
PS C:\WINDOWS\system32> $error
ObjectNotFound: (221dsd:String) [], CommandNotFoundException
ObjectNotFound: (7sdse:String) [], CommandNotFoundException
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException
When you add one more error count,
PS C:\WINDOWS\system32> 5look
ObjectNotFound: (5look:String) [], CommandNotFoundException
Now check the capacity,
PS C:\WINDOWS\system32> $error.Capacity
8
And the output,
PS C:\WINDOWS\system32> $error
ObjectNotFound: (5look:String) [], CommandNotFoundException
ObjectNotFound: (221dsd:String) [], CommandNotFoundException
ObjectNotFound: (7sdse:String) [], CommandNotFoundException
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException
So question is, what is the threshold for this error variable capacity? To check it, you need to use the command $MaximumErrorCount.
PS C:\WINDOWS\system32> $MaximumErrorCount
256
Here, the limit of the maximum error count is 256.
Convert a number to a string in JavaScript - GeeksforGeeks

05 Mar, 2021
In JavaScript, you can change any number into string format using the following methods.
1. Using toString(): This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type.
Syntax:
num.toString();
Example:JavascriptJavascript<script>  let a = 20;    console.log(a.toString());  console.log((50).toString());  console.log((60).toString());  console.log((7).toString(2)); // (7 in base 2, or binary)</script>Output:20
50
60
111
Example:
Javascript
<script>  let a = 20;    console.log(a.toString());  console.log((50).toString());  console.log((60).toString());  console.log((7).toString(2)); // (7 in base 2, or binary)</script>
Output:
20
50
60
111
2. Using String() function: This method accepts an integer or floating-point number as a parameter and converts it into string type.
Syntax:
String(object);
Example:JavascriptJavascript<script>  let a = 30;    console.log(String(a));  console.log(String(52));  console.log(String(35.64));</script>Output:30
52
35.64
Example:
Javascript
<script>  let a = 30;    console.log(String(a));  console.log(String(52));  console.log(String(35.64));</script>
Output:
30
52
35.64
Note: It does not do any base conversations as .toString() does.
3. Concatenating an empty string: This is arguably one of the easiest ways to convert any integer or floating-point number into a string.
Syntax:
let variable_name =' ' + value;
Example:JavascriptJavascript<script>  let a = '' + 50;  console.log(a);</script>Output:50
Example:
Javascript
<script>  let a = '' + 50;  console.log(a);</script>
Output:
50
4.Template Strings: Injecting a number inside a String is also a valid way of parsing an Integer data type or Float data type.
Syntax:
let variable_name = '${value}';
Example:JavascriptJavascript<script>  let num = 50;  let flt = 50.205;  let string = "${num}";  let floatString = "${flt}";  console.log(string);  console.log(floatString);</script>Output:50
50.205
Example:
Javascript
<script>  let num = 50;  let flt = 50.205;  let string = "${num}";  let floatString = "${flt}";  console.log(string);  console.log(floatString);</script>
Output:
50
50.205
The above 4 methods can be used to convert any integer or floating-point number into a string.
JavaScript-Questions
javascript-string
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to use ‘while loop’ in Java?

A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop is −
while(Boolean_expression) {
   // Statements
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value.When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.When the condition becomes false, program control passes to the line immediately following the loop.
Here, the key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
public class Test {
   public static void main(String args[]) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }
   }
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Entering JSON data into MySQL?

Use the JSON data type to first set JSON data and then insert. Let us first create a table −
mysql> create table DemoTable1876
   (
   EmployeeInformation JSON
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1876 values('{
   '> "EmployeeData":{
   '> "Name": "Chris",
   '> "Age": 27
   '> }
   '> }'
    );
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1876 values('{
   '> "EmployeeData":{
   '> "Name": "David",
   '> "Age": 24
   '> }
   '> }'
    );
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1876;
This will produce the following output −
+------------------------------------------------+
| EmployeeInformation                            |
+------------------------------------------------+
| {"EmployeeData": {"Age": 27, "Name": "Chris"}} |
| {"EmployeeData": {"Age": 24, "Name": "David"}} |
+------------------------------------------------+
2 rows in set (0.00 sec)
Matplotlib.axes.Axes.get_lines() in Python - GeeksforGeeks

27 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.get_lines() function in axes module of matplotlib library is used to return a list of lines contained by the Axes
Syntax: Axes.get_lines(self)
Parameters: This method does not accept any parameters.
Returns: This method return a list of lines contained by the Axes.
Below examples illustrate the matplotlib.axes.Axes.get_lines() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatterimport numpy as npimport matplotlib.pyplot as plt    N_points = 100000x = np.random.randn(N_points)y = .4 * x + np.random.randn(100000) + 5   fig, ax = plt.subplots()ax.hist2d(x, y, bins = 100,          norm = colors.LogNorm(),           cmap ="Greens")  w = list(ax.get_lines())if len(w)== 0:    ax.text(-2, 8.5,             "No line contained by the Axes \n")else:    ax.text(-3, 8.5,            "List of the lines contained by the Axes \n")    x = 8.5    for i in w:                  ax.text(-3, x-0.5, str(i))        x-= 0.5  fig.suptitle('matplotlib.axes.Axes.get_lines() \function Example', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as mpatches    fig, ax = plt.subplots()x, y = 10 * np.random.rand(2, 1000)ax.plot(x, y, 'go', alpha = 0.2)  circ = mpatches.Circle((0.5, 0.5),                       0.25,                       transform = ax.transAxes,                       facecolor ='blue',                       alpha = 0.75)  ax.add_patch(circ)  w = list(ax.get_lines())  if len(w)== 0:    ax.text(1, 8.5,            "No line contained by the Axes \n")      else:    ax.text(1, 8.5,            "List of the lines contained by the Axes \n")    x = 8.5          for i in w:        ax.text(1, x-0.5, str(i))        x-= 0.5  fig.suptitle('matplotlib.axes.Axes.get_lines() \function Example', fontweight ="bold")  plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
MySQL query to count rows in multiple tables

Let us first create a table −
mysql> create table DemoTable1 (FirstName varchar(100));
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values('Bob');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1 values('James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1 values('David');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output -
+-----------+
| FirstName |
+-----------+
| Bob       |
| James     |
| John      |
| David     |
+-----------+
4 rows in set (0.00 sec)
Here is the query to create second table −
mysql> create table DemoTable2 (Marks int);
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(89);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable2 values(67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(34);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable2 values(32);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable2 values(42);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output -
+-------+
| Marks |
+-------+
| 98    |
| 89    |
| 67    |
| 34    |
| 32    |
| 42    |
+-------+
6 rows in set (0.00 sec)
Here is the query to count rows in multiple tables −
mysql> select
   (select count(*) from DemoTable1) AS First_Table_Row,
   (select count(*) from DemoTable2) AS Second_Table_Row;
This will produce the following output -
+-----------------+------------------+
| First_Table_Row | Second_Table_Row |
+-----------------+------------------+
| 4               | 6                |
+-----------------+------------------+
1 row in set (0.00 sec)
I want to resize and position a JFrame in Java. How can I achieve that?

To resize and position JFrame, use the Dimensions class. Here, we have set the bounds for the frame −
int width = 500;
int height = 400;
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((int) size.getWidth() - width, 0, width, height);
The following is an example to resize and poisiton a frame −
package my;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame.setDefaultLookAndFeelDecorated(true);
      JFrame frame = new JFrame("Register!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label2 = new JLabel("Age", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField emailId = new JTextField(20);
      JTextField age = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(age);
      frame.add(passwd);
      int width = 500;
      int height = 400;
      Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
      frame.setBounds((int) size.getWidth() - width, 0, width, height);
      frame.setVisible(true);
   }
}
Tryit Editor v3.7

Tryit: HTML aside element
Difference between readObject and readResolve method in serialization

Serialization is the process of converting object to stream byte and storing byte stream in database or memory. Class which implements java.io.Serializable interface can be serialized. 
Class which is implementing this interface gives the responsibility to JVM for serialize or persist java object 
As per the oracle docs −
readObject method − Each subclass of a serializable object may define its own readObject method. If a class does not implement the method, the default serialization provided by defaultReadObject will be used. When implemented, the class is only responsible for restoring its own fields, not those of its supertypes or subtypes.The readObject method of the class, if implemented, is responsible for restoring the state of the class. The values of every field of the object whether transient or not, static or not are set to the default value for the fields type.
The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.
1
Basic 
The readObject method is used to deserialize an object from the stream
The readResolve method is called when objectInputStream has read an object from the stream and is preparing to return it to the caller
2
Class 
It is part of ObjectInputStream class 
It is part of ObjectInputStream 
3
It does not check the construction of object 
The readResolve method is not invoked on the object until the object is fully constructed
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
   public static void main(String[] args) {
      User object = new User(1, "Ram");
      String filename = "tutorialPoints.ser";
      User object1 = null;
      try {
         // Reading the object from a file
         FileInputStream file = new FileInputStream(filename);
         ObjectInputStream in = new ObjectInputStream(file);
         object1 = (User) in.readObject();
         in.close();
         file.close();
      }
      catch (IOException ex) {
         ex.printStackTrace();
      }
      catch (ClassNotFoundException ex) {
         ex.printStackTrace();
      }
   }
}
class User implements java.io.Serializable {
   public int id;
   public String name;
   // Default constructor
   public User(int id, String name) {
      this.id = id;
      this.name = name;
   }
}
YearMonth format() method in Java

04 Sep, 2021
The format() method of YearMonth class in Java is used to format this YearMonth instance according to a specified DateTimeFormatter for year-month passed as parameter to this method. 
Syntax: 
public String format(DateTimeFormatter formatter)
Parameter: This method accepts a single parameter formatter which is the DateTimeFormatter according to which this YearMonth instance will be formatted.Return Value: It returns the value of this YearMonth as a string after formatting it according to the specified formatter.Below programs illustrate the format() method of YearMonth in Java: Program 1:  
Java
// Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG {    public static void main(String[] args)    {         // Create a YearMonth object        YearMonth thisYearMonth = YearMonth.of(2017, 8);         // Create a DateTimeFormatter string        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/MM");         // Format this year-month        System.out.println(thisYearMonth.format(formatter));    }}
17/08
 
Program 2: 
Java
// Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG {    public static void main(String[] args)    {         // Create a YearMonth object        YearMonth thisYearMonth = YearMonth.of(2018, 5);         // Create a DateTimeFormatter string        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy");         // Format this year-month        System.out.println(thisYearMonth.format(formatter));    }}
05/18
 
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#format-java.time.format.DateTimeFormatter-
anikakapoor
Java-Functions
Java-time package
Java-YearMonth
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
How to compare two NumPy arrays?

03 Jun, 2022
Here we will be focusing on the comparison done using NumPy on arrays. Comparing two NumPy arrays determines whether they are equivalent by checking if every element at each corresponding index is the same. 
Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray.all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent. 
Python3
import numpy as np an_array = np.array([[1, 2], [3, 4]])another_array = np.array([[1, 2], [3, 4]]) comparison = an_array == another_arrayequal_arrays = comparison.all() print(equal_arrays)
Output:
True
Method 2: We can also use greater than, less than and equal to operators to compare. To understand, have a look at the code below.
Syntax : numpy.greater(x1, x2[, out])
Syntax : numpy.greater_equal(x1, x2[, out])
Syntax : numpy.less(x1, x2[, out])
Syntax : numpy.less_equal(x1, x2[, out])
Python3
import numpy as np  a = np.array([101, 99, 87])b = np.array([897, 97, 111]) print("Array a: ", a)print("Array b: ", b) print("a > b")print(np.greater(a, b)) print("a >= b")print(np.greater_equal(a, b)) print("a < b")print(np.less(a, b)) print("a <= b")print(np.less_equal(a, b))
Output:
 
This array_equal() function checks if two arrays have the same elements and same shape.
Syntax:
numpy.array_equal(arr1, arr2) 
Parameters:
arr1    : [array_like]Input array or object whose elements, we need to test.
arr2    : [array_like]Input array or object whose elements, we need to test.
Return Type: True, two arrays have the same elements and same shape.; otherwise False
Example
Python3
import numpy as np arr1 = np.array([[1, 2], [3, 4]])arr2 = np.array([[1, 2], [3, 4]])  # Comparing the arraysif np.array_equal(arr1, arr2):    print("Equal")else:    print("Not Equal")
Output:
Equal
kothavvsaakash
pulamolusaimohan
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
vector shrink_to_fit() function in C++ STL

09 Jun, 2022
The vector::shrink_to_fit() is a built-in function in C++ STL which reduces the capacity of the container to fit its size and destroys all elements beyond the capacity. Syntax:
vector_name.shrink_to_fit()
Parameters: The function does not accept any parameters. Return value: The function does not returns anything. 
Time Complexity – Linear O(N)
Below program illustrate the above function: 
CPP
// C++ program to illustrate// the vector::shrink_to_fit()#include <bits/stdc++.h>using namespace std; int main(){     // Initialized vector    vector<int> v(10);     for (int i = 0; i < 10; i++)        v[i] = i;     // Initial vector    cout << "Vector size initially: " << v.size();     cout << "\nVector elements are: ";    for (int i = 0; i < 10; i++)        cout << v[i] << " ";     // changes the size of the Vector    // but does not destroys the elements    v.resize(5);     cout << "\n\nVector size after resize(5): "    << v.size();     cout << "\nVector elements after resize(5) are: ";    for (int i = 0; i < 10; i++)        cout << v[i] << " ";     // Shrinks to the size    // till which elements are    // destroys the elements after 5    v.shrink_to_fit();     cout << "\n\nVector size after shrink_to_fit(): "    << v.size();     cout << "\nVector elements after shrink_to_fit() are: ";    for (int i = 0; i < 10; i++)        cout << v[i] << " ";     return 0;}
Vector size initially: 10
Vector elements are: 0 1 2 3 4 5 6 7 8 9 

Vector size after resize(5): 5
Vector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9 

Vector size after shrink_to_fit(): 5
Vector elements after shrink_to_fit() are: 0 1 2 3 4 0 127889 0 0 0
AdityaKumawat1
utkarshgupta110092
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create a Numpy array filled with all ones

21 Feb, 2022
In this article, we will learn how to create a Numpy array filled with all one, given the shape and type of array. We can use Numpy.ones() method to do this task. This method takes three parameters, discussed below –  
shape : integer or sequence of integers
order  : C_contiguous or F_contiguous
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
dtype : [optional, float(byDefault)] Data type of returned array.  
Code #1:  
Python3
# Python Program to create array with all onesimport numpy as geek a = geek.ones(3, dtype = int)print("Matrix a : \n", a) b = geek.ones([3, 3], dtype = int)print("\nMatrix b : \n", b)
Output:  
Matrix a : 
 [1 1 1]

Matrix b : 
 [[1 1 1]
 [1 1 1]
 [1 1 1]]
  Code #2:  
Python3
# Python Program to create array with all onesimport numpy as geek c = geek.ones([5, 3])print("\nMatrix c : \n", c) d = geek.ones([5, 2], dtype = float)print("\nMatrix d : \n", d)
Output:  
Matrix c : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

Matrix d : 
 [[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]]
 
avtarkumar719
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.