code-rag-bench/online-tutorials huggingface dataset:
F# - Strings

In F#, the string type represents immutable text as a sequence of Unicode characters.
String literals are delimited by the quotation mark (") character.
Some special characters are there for special uses like newline, tab, etc. They are encoded using backslash (\) character. The backslash character and the related character make the escape sequence. The following table shows the escape sequence supported by F#.
The following two ways makes the compiler ignore the escape sequence −
Using the @ symbol.
Enclosing the string in triple quotes.
When a string literal is preceded by the @ symbol, it is called a verbatim string. In that way, all escape sequences in the string are ignored, except that two quotation mark characters are interpreted as one quotation mark character.
When a string is enclosed by triple quotes, then also all escape sequences are ignored, including double quotation mark characters.
The following example demonstrates this technique showing how to work with XML or other structures that include embedded quotation marks −
// Using a verbatim string
let xmldata = @"<book author = ""Lewis, C.S"" title = ""Narnia"">"
printfn "%s" xmldata
When you compile and execute the program, it yields the following output −
<book author = "Lewis, C.S" title = "Narnia">

The following table shows the basic operations on strings −
The following examples demonstrate the uses of some of the above functionalities −
The String.collect function builds a new string whose characters are the results of applying a specified function to each of the characters of the input string and concatenating the resulting strings.
let collectTesting inputS =
   String.collect (fun c -> sprintf "%c " c) inputS
printfn "%s" (collectTesting "Happy New Year!")
When you compile and execute the program, it yields the following output −
H a p p y N e w Y e a r !

The String.concat function concatenates a given sequence of strings with a separator and returns a new string.
let strings = [ "Tutorials Point"; "Coding Ground"; "Absolute Classes" ]
let ourProducts = String.concat "\n" strings
printfn "%s" ourProducts
When you compile and execute the program, it yields the following output −
Tutorials Point
Coding Ground
Absolute Classes

The String.replicate method returns a string by concatenating a specified number of instances of a string.
printfn "%s" <| String.replicate 10 "*! "
When you compile and execute the program, it yields the following output −
*! *! *! *! *! *! *! *! *! *!

 Print
 Add Notes
 Bookmark this page
Tkinter - Button that changes its properties on hover - GeeksforGeeks

08 Dec, 2020
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task.
In this article, we are going to create a button that changes its properties on hover.
Step-by-step Approach:
Import tkinter module.
Python3
# import required modulefrom tkinter import *
Creating A Universal Function To Give Change On Hover Power To Every Button.
The config() method is used to change the properties of any widget. Note that in config() method bg and background are two different options and background represents background-color.
Syntax:
widget.config(**options)
Below is the implementation:
Python3
# function to change properties of button on hoverdef changeOnHover(button, colorOnHover, colorOnLeave):      # adjusting backgroung of the widget    # background on entering widget    button.bind("<Enter>", func=lambda e: button.config(        background=colorOnHover))      # background color on leving widget    button.bind("<Leave>", func=lambda e: button.config(        background=colorOnLeave))
Create a button in driver code and call the explicit function.
Python3
# Driver Coderoot = Tk()  # create button# assign button text along# with background colormyButton = Button(root,                  text="On Hover - Background Change",                  bg="yellow")myButton.pack()  # call function with background# colors as argumentchangeOnHover(myButton, "red", "yellow")  root.mainloop()
Below is the complete program based on the above approach:
Python3
# import required modulefrom tkinter import *    # function to change properties of button on hoverdef changeOnHover(button, colorOnHover, colorOnLeave):      # adjusting backgroung of the widget    # background on entering widget    button.bind("<Enter>", func=lambda e: button.config(        background=colorOnHover))      # background color on leving widget    button.bind("<Leave>", func=lambda e: button.config(        background=colorOnLeave))    # Driver Coderoot = Tk()  # create button# assign button text along# with background colormyButton = Button(root,                  text="On Hover - Background Change",                  bg="yellow")myButton.pack()  # call function with background# colors as argumentchangeOnHover(myButton, "red", "yellow")  root.mainloop()
Output:
Python-tkinter
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 | Pandas dataframe.groupby()
Python | Get unique values from a list
set clear() in python

In this tutorial, we are going to learn about the clear method of set data structure. Let's see details about the clear method.
The method clear is used to clear all the data from the set data structure. All elements from set will clear. And we will leave with an empty set.
Follow the below steps to see clear method in action.
Initialize a set.
User the clear method and clear the set.
Print the set and you will see an empty one.
 Live Demo
# initialzing a set
number_set = {1, 2, 3, 4, 5}
# clearing the set
number_set.clear()
# printing the set
print(number_set)
If you run the above code, then you will get the following result.
set()
If you have any doubts in the tutorial, mention them in the comment section.
Loading Excel spreadsheet as pandas DataFrame - GeeksforGeeks

08 Jan, 2019
Pandas is a very powerful and scalable tool for data analysis. It supports multiple file format as we might get the data in any format. Pandas also have support for excel file format.
We first need to import Pandas and load excel file, and then parse excel file sheets as a Pandas dataframe.
import pandas as pd  # Import the excel file and call it xls_fileexcel_file = pd.ExcelFile('pandasEx.xlsx')  # View the excel_file's sheet namesprint(excel_file.sheet_names)  # Load the excel_file's Sheet1 as a dataframedf = excel_file.parse('Sheet1')print(df)
Output:
One can also read specific columns using ‘usecols‘ parameter of read_excel() method.
# import pandas lib as pd import pandas as pd     require_cols = [0, 3]     # only read specific columns from an excel file required_df = pd.read_excel('SampleWork2.xlsx', usecols = require_cols)     print(required_df) 
Output:
        Name  Percentage
0      Ankit          95
1      Rahul          90
2    Shaurya          85
3  Aishwarya          80
4   Priyanka          75
For more examples, refer https://www.geeksforgeeks.org/creating-a-dataframe-using-excel-files/
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
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 | Pandas dataframe.groupby()
Python | Get unique values from a list
Python Program to Count number of binary strings without consecutive 1's - GeeksforGeeks

02 Jan, 2019
Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.
Examples:
Input:  N = 2
Output: 3
// The 3 strings are 00, 01, 10

Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
Python3
# Python program to count# all distinct binary strings# without two consecutive 1's  def countStrings(n):      a =[0 for i in range(n)]    b =[0 for i in range(n)]    a[0] = b[0] = 1    for i in range(1, n):        a[i] = a[i-1] + b[i-1]        b[i] = a[i-1]          return a[n-1] + b[n-1]  # Driver program to test# above functions  print(countStrings(3))  # This code is contributed# by Anant Agarwal.
5

Please refer complete article on Count number of binary strings without consecutive 1’s for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python | Get the first key in dictionary
Python Program for Merge Sort
Python | Find most frequent element in a list
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python - Convert JSON to string
Python program to find smallest number in a list
JavaScript Math PI Property - GeeksforGeeks

24 Jan, 2022
Below is the example of the Math PI Property. 
Example:
Javascript
<script>  // Here value of Math.PI is printed.  document.write(Math.PI);</script>
Output: 
3.141592653589793
The Math.PI is a property in JavaScript which is simply used to find the value of Pi i.e, in symbolic form Π which is nothing but it is the ratio of the circumference of a circle to its diameter, whose value is approximately 3.141. It is mainly used in a mathematics problem.
Syntax:  
Math.PI
Return values: It simply returns the value of PI i.e, Π
Below example illustrates the Math PI property in JavaScript.
Example: Here simply value of PI i.e, Π is shown as output.  
Input : Math.PI
Output : 3.141592653589793
More codes for the above property are as follows:
Program 1:Value of PI i.e, Π can be printed as in the form of function as shown below.  
Javascript
<script>  // function is being called.  function get_Value_of_PI()  {      return Math.PI;  }   // function is calling.  document.write(get_Value_of_PI());</script>
Output: 
3.141592653589793
Program 2: Here we consider Math.PI as a function but in actual it is a property that is why error as output is being shown. 
Javascript
<script>  // Here we consider Math.PI as a function but  // in actual it is a property that is why error  // as output is being shown.  document.write(Math.PI(12));</script>
Output: 
Error: Math.PI is not a function
Program 3: Whenever we need to find the value of anything related to PI that time we take the help of this property. In mathematics, it needed a lot. Here we are going to find the value of the area of a circle with the given value of its radius. 
Javascript
<script>  // function is being called with radius 5 as a parameter.  function area_of_circle(radius_of_the_circle)  {      return Math.PI * radius_of_the_circle * radius_of_the_circle;  }   // Here area of the circle is 5 unit.  document.write(area_of_circle(5));</script>
Output: 
78.53981633974483
Supported Browsers: 
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
 
nidhi_biet
arorakashish0911
ysachin2314
javascript-math
JavaScript-Properties
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
GATE | GATE-CS-2004 | Question 11 - GeeksforGeeks

28 Jun, 2021
Consider the following statements with respect to user-level threads and kernel supported threads
 
i.   context switch is faster with kernel-supported threads
ii.  for user-level threads, a system call can block the 
     entire process
iii. Kernel supported threads can be scheduled independently
iv.  User level threads are transparent to the kernel
Which of the above statements are true?(A) (ii), (iii) and (iv) only(B) (ii) and (iii) only(C) (i) and (iii) only(D) (i) and (ii) onlyAnswer: (A)Explanation:
http://en.wikipedia.org/wiki/Thread_%28computer_science%29
https://www.geeksforgeeks.org/difference-between-user-level-thread-and-kernel-level-thread/Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to install Python Pycharm on Windows? - GeeksforGeeks

28 Jan, 2020
Prerequisite: Python Language Introduction Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.Python is a programming language that lets you work quickly and integrate systems more efficiently.We need to have an interpreter to interpret and run our programs. There are certain online interpreters like GFG-IDE, IDEONE or CodePad, etc. Running Python codes on an offline interpreter is much more compatible than using an online IDE. PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides some very useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development in Python.
Installing Python: Before, starting with the process of installing PyCharm in Windows, one must ensure that Python is installed on their system. To check if the system is equipped with Python, go to the Command line(search for cmd in the Run dialog( + R).Now run the following command:
python --version

If Python is already installed, it will generate a message with the Python version available.
If Python is not present, go through How to install Python on Windows? and follow the instructions provided.
Before beginning with the installation process, PyCharm needs to be downloaded. For that, PyCharm is available on jetbrains.com.Download the PyCharm and follow the further instructions for its installation.
Beginning with the installation:
Getting Started:
Choose Installation Location:
Installation Options:
Selecting Start Menu Folder:
Processing Installation:
Finished Installation:
Once the Installation is over, PyCharm can be searched and started from the Start Menu. Follow the steps given below to do the same:
Searching from Start Menu:
Getting done with License Agreement:
Setting UI Theme:
Downloading Plugins:
Get Started with PyCharm:
python-basics
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
fmt.Sprintln() Function in Golang With Examples - GeeksforGeeks

05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprintln() function in Go language formats using the default formats for its operands and returns the resulting string. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Sprintln(a ...interface{}) string

Here, “a ...interface{}” is containing some strings along with the specified constant variables.
Returns: It returns the resulting string.
Example 1:
// Golang program to illustrate the usage of// fmt.Sprintln() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const name, dept = "GeeksforGeeks", "CS"      // Calling Sprintln() function    s := fmt.Sprintln(name, "is a", dept, "Portal.")      // Calling WriteString() function to write the    // contents of the string "s" to "os.Stdout"    io.WriteString(os.Stdout, s)  }
Output:
GeeksforGeeks is a CS Portal.

Example 2:
// Golang program to illustrate the usage of// fmt.Sprintln() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const num1, num2, num3, num4 = 5, 10, 15, 50      // Calling Sprintln() function    s1 := fmt.Sprintln(num1, "+", num2, "=", num3)    s2 := fmt.Sprintln(num1, "*", num2, "=", num4)      // Calling WriteString() function to write the    // contents of the string "s1" and "s2" to "os.Stdout"    io.WriteString(os.Stdout, s1)    io.WriteString(os.Stdout, s2)  }
Output:
5 + 10 = 15
5 * 10 = 50

In the above code, no new line or space is used still this function append new line and space between the operands that can be seen in the above output.
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang
Program to find maximum k-repeating substring from sequence in Python

Suppose we have a sequence of characters called s, we say a string w is k-repeating string if w is concatenated k times is a substring of sequence. The w's maximum k-repeating value will be the highest value k where w is k-repeating in sequence. And if w is not a substring of the given sequence, w's maximum k-repeating value is 0. So if we have s and w we have to find the maximum k-repeating value of w in sequence.
So, if the input is like s = "papaya" w = "pa", then the output will be 2 as w = "pa" is present twice in "papaya".
To solve this, we will follow these steps −
Count:= number of w present in s
Count:= number of w present in s
if Count is same as 0, thenreturn 0
if Count is same as 0, then
return 0
return 0
for i in range Count to 0, decrease by 1, doif i repetition of w is present in s, thenreturn i
for i in range Count to 0, decrease by 1, do
if i repetition of w is present in s, thenreturn i
if i repetition of w is present in s, then
return i
return i
Let us see the following implementation to get better understanding −
 Live Demo
def solve(s, w):
   Count=s.count(w)
   if Count==0:
      return 0
   for i in range(Count,0,-1):

      if w*i in s:
         return i

s = "papaya"
w = "pa"
print(solve(s, w))
"papaya", "pa"
2
How to suppress Matplotlib warning?

Let's take an example. We create a set of data points such that it would generate some warnings. We will create data points x from −1 to 1 and try to find log in that range, which means it will throw an error at value 0, while calculating logs.
Create data points for x and calculate log(x), using numpy.
Plot x and y using plot() method.
Use warnings.filterwarnings("ignore") to suppress the warning.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
import warnings
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
warnings.filterwarnings("ignore")
x = np.linspace(-1, 1, 10)
y = np.log(x)
plt.plot(x, y)
plt.show()
When we execute the code, it will suppress the warning and display the following plot.
Now, remove the line, warnings.filterwarnings("ignore") and execute the code again. It will display the plot, but with a runtime warning.
RuntimeWarning: invalid value encountered in log
What is difference between instantiating a C++ object using new vs. without new?

In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object. This will be stored at the stack section. This will be destroyed when the scope ends. But for the case when we want to allocate the space for the item dynamically, then we can create pointer of that class, and instantiate using new operator.
In C++, the new is used to dynamically allocate memory.
#include <iostream>
using namespace std;
class Point {
   int x, y, z;
   public:
      Point(int x, int y, int z) {
         this->x = x;
         this->y = y;
         this->z = z;
      }
      void display() {
         cout << "(" << x << ", " << y << ", " << z << ")" << endl;
      }
};
int main() {
   Point p1(10, 15, 20);
   p1.display();
   Point *ptr;
   ptr = new Point(50, 60, 70);
   ptr->display();
}
(10, 15, 20)
(50, 60, 70)
Named arguments in JavaScript.

Following is the code for using named arguments in JavaScript functions −
 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 {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,.result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Named arguments in JavaScript functions</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to call a function and pass above object to it
as argument
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   sampleEle.innerHTML = "{a:22,b:44,c:55,d:99}";
   function add({ a = 0, b = 0, c = 0, d = 0 }) {
      return a + b + c + d;
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML += "Sum = " + add({ a: 22, b: 44, c: 55, d: 99 });
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
Python - Fetch columns between two Pandas DataFrames by Intersection

To fetch columns between two DataFrames by Intersection, use the intersection() method. Let us create two DataFrames −
# creating dataframe1
dataFrame1 = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
})

# creating dataframe2
dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})
Fetch common columns −
dataFrame2.columns.intersection(dataFrame1.columns)

Following is the complete code −
import pandas as pd

# creating dataframe1
dataFrame1 = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
})

print"Dataframe1...\n",dataFrame1

# creating dataframe2
dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})

print"Dataframe2...\n",dataFrame2

# getting common columns using intersection()
res = dataFrame2.columns.intersection(dataFrame1.columns)

print"\nCommon columns...\n",res
This will produce the following output −
Dataframe1...
        Car   Cubic_Capacity   Reg_Price
0   Bentley             2000        7000
1     Lexus             1800        1500
2     Tesla             1500        5000
3   Mustang             2500        8000
4  Mercedes             2200        9000
5    Jaguar             3000        6000
Dataframe2...
        Car   Units_Sold
0       BMW          100
1     Lexus          110
2     Tesla          150
3   Mustang           80
4  Mercedes          200
5    Jaguar           90

Common columns...
Index([u'Car'], dtype='object')
How to create Accordion in ReactJS ? - GeeksforGeeks

12 Feb, 2021
Accordions contain creation flows and allow lightweight editing of an element. Material UI for React has this component available for us, and it is very easy to integrate. We can create it in ReactJS using the following approach.
Creating React Application and Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/icons
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from "react";import ExpandMoreIcon from "@material-ui/icons/ExpandMore";import Accordion from "@material-ui/core/Accordion";import AccordionDetails from "@material-ui/core/AccordionDetails";import Typography from "@material-ui/core/Typography";import AccordionSummary from "@material-ui/core/AccordionSummary";  export default function App() {  return (    <div stlye={{}}>      <h4>How to create Accordion in ReactJS?</h4>      <Accordion style={{ width: 400 }}>        <AccordionSummary          expandIcon={<ExpandMoreIcon />}          aria-controls="panel1a-content"        >          <Typography            style={{              fontWeight: 10,            }}          >            Accordion Demo          </Typography>        </AccordionSummary>        <AccordionDetails>          <Typography>Greetings of the day :)</Typography>        </AccordionDetails>      </Accordion>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
How to download a file from a URL in C#?

A file can be downloaded from a URL using web client. It is available in System.Net
namespace.
The WebClient class provides common methods for sending data to or receiving data
from any local, intranet, or Internet resource identified by a URI.
The web client can be said as an application or web browser (like Google Chrome,
Internet Explorer, Opera, Firefox, Safari) which is installed in a computer and used to
interact with Web servers upon user’s request. It is basically a consumer application
which collects processed data from servers.
A Client and a Server are two parts of a connection, these are two distinct machines,
web client requests information, and the web server is basically a PC that is designed
to accept requests from remote computers and send on the information requested.
Web server is responsible for storing the information in order to be viewed by the
clients and is also usually a Web Host. A Web host allows connections to the server
to view said stored info.
The WebClient class in C# uses the WebRequest class to provide access to resources.
WebClient instances can access data with any WebRequest descendant registered
with the WebRequest.RegisterPrefix method. The DownloadFile is used to
download a file.
WebClient Client = new WebClient ();
client.DownloadFile("url","path");
Say we want to download an image from the path "https://downloadfreeimages.jpg"
and save it the computer local directory, below is the code.
using System;
using System.Net;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string url = "https://downloadfreeimages.jpg";
         string savePath = @"D:\Demo\FreeImages.jpg";
         WebClient client = new WebClient();
         client.DownloadFile(url, savePath);
         Console.ReadLine();
      }
   }
}
The above example will download the image from the URL provided and saves it to
the given path.
D:\Demo
Python Blockchain - Block Class

A block consists of a varying number of transactions. For simplicity, in our case we will assume that the block consists of a fixed number of transactions, which is three in this case. As the block needs to store the list of these three transactions, we will declare an instance variable called verified_transactions as follows −
self.verified_transactions = []

We have named this variable as verified_transactions to indicate that only the verified valid transactions will be added to the block. Each block also holds the hash value of the previous block, so that the chain of blocks becomes immutable.
To store the previous hash, we declare an instance variable as follows −
self.previous_block_hash = ""

Finally, we declare one more variable called Nonce for storing the nonce created by the miner during the mining process.
self.Nonce = ""

The full definition of the Block class is given below −
class Block:
   def __init__(self):
      self.verified_transactions = []
      self.previous_block_hash = ""
      self.Nonce = ""

As each block needs the value of the previous block’s hash we declare a global variable called last_block_hash as follows −
last_block_hash = ""

Now let us create our first block in the blockchain.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How can we minimize/maximize a JFrame programmatically in Java?

A JFrame class is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. A JFrame contains a window with title, border, (optional) menu bar and user-specific components. By default, we can minimize a JFrame by clicking on minimize button and maximize a JFrame by clicking on maximize button at the top-right position of the screen. We can also do programmatically by using setState(JFrame.ICONIFIED) to minimize a JFrame and setState(JFrame.MAXIMIZED_BOTH) to maximize a JFrame.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameIconifiedTest extends JFrame implements ActionListener {
   private JButton iconifyButton, maximizeButton;
   public JFrameIconifiedTest() {
      setTitle("JFrameIconified Test");
      iconifyButton = new JButton("JFrame Iconified");
      add(iconifyButton, BorderLayout.NORTH);
      iconifyButton.addActionListener(this);
      maximizeButton = new JButton("JFrame Maximized");
      add(maximizeButton, BorderLayout.SOUTH);
      maximizeButton.addActionListener(this);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public void actionPerformed(ActionEvent ae) {
      if(ae.getSource().equals(iconifyButton)) {
         setState(JFrame.ICONIFIED); // To minimize a frame
      } else if(ae.getSource().equals(maximizeButton)) {
         setExtendedState(JFrame.MAXIMIZED_BOTH); // To maximize a frame
      }
   }
   public static void main(String args[]) {
      new JFrameIconifiedTest();
   }
}
In the above program, if we click on "JFrame Iconified" button, the frame is minimized and click on "JFrame Maximized" button, the frame is maximized.
How to get the disk information using PowerShell?

To get the Windows disk information using PowerShell, we can use the WMI command or the CIM class command.
With the WMI command,
Gwmi Win32_LogicalDisk
With the CIM instance method,
Get−CimInstance Win32_LogicalDisk

You can see both the outputs are identical. Let’s use one of them.
DeviceID DriveType ProviderName VolumeName Size FreeSpace
-------- --------- ------------ ---------- ---- ---------
C: 3 53317988352 44027125760
D: 5 HRM_SSS_X64FREE_EN-US_DV5 3694962688 0
E: 3 Temporary Storage 10734268416 10238513152
Now there are different drive types associated with Windows and they each have an identical number. For example, Drive Type ‘3’ mentions the logical disk. The other types are as below.
2 = "Removable disk"
3="Fixed local disk"
4="Network disk"
5 = "Compact disk"
Here, we will filter only logical system disks. For that, we can use the below command.
Get−CimInstance Win32_LogicalDisk | where{$_.DriveType −eq '3'}

DeviceID DriveType ProviderName VolumeName Size FreeSpace
-------- --------- ------------ ---------- ---- ---------
C: 3 53317988352 44027023360
E: 3 Temporary Storage 10734268416 10238513152
The above size is displayed in bytes. You can convert it to GB using an expression. Use the below command, to convert the Size and FreeSpace into GB.
Get−CimInstance Win32_LogicalDisk | where{$_.DriveType −eq '3'} `
| Select DeviceID, DriveType,VolumeName,
@{N='TotalSize(GB)';E={[Math]::Ceiling($_.Size/1GB)}}, @{N='FreeSize(GB)';E={[Math]::Ceiling($_.FreeSpace/1GB)}} |
ft −AutoSize
DeviceID DriveType VolumeName TotalSize(GB) FreeSize(GB)
-------- --------- ---------- ------------- ------------
C: 3 50 42
E: 3 Temporary Storage 10 10
Size of a Three-dimensional array in C#

To get the size of a 3D array in C#, use the GetLength() method with parameter as the index of the dimensions.
GetLength(dimensionIndex)
To get the size.
arr.GetLength(0)
arr.GetLength(1)
arr.GetLength(2)
 Live Demo
using System;
class Program {
   static void Main() {
      int[,,] arr = new int[3,4,5];
      // length of a dimension
      Console.WriteLine(arr.GetLength(0));
      Console.WriteLine(arr.GetLength(1));
      Console.WriteLine(arr.GetLength(2));
      // length
      Console.WriteLine(arr.Length);
   }
}
3
4
5
60
Python | Sort list of dates given as strings

14 Dec, 2018
Given a list of dates in string format, write a Python program to sort the list of dates in ascending order.
Examples:
Input : dates = [“24 Jul 2017”, “25 Jul 2017”, “11 Jun 1996”, “01 Jan 2019”, “12 Aug 2005”, “01 Jan 1997”]
Output : 01 Jan 200710 Jul 20162 Dec 201711 Jun 201823 Jun 201801 Jan 2019
 Approach:In Python, we can use sort() (for in-place sorting) and sorted() (returns a new sorted list) functions for sorting lists. But by default, these in-built sorting functions will sort the list of strings in alphabetical order which would result in a wrong order in our case. Hence, we need to pass a key argument to tell the sorting function that we need to compare the list items in a particular way and sort them accordingly.
In Python, we have the datetime module which makes date based comparison easier. The datetime.strptime() function is used to convert a given string into datetime object. It accepts two arguments: date (string) and format (used to specify the format. for eg: %Y is used for specifying year) and returns a datetime object.
Syntax:
datetime.strptime(date, format)
The formatting that we require for this problem is as follows:
%d ---> for Day
%b ---> for Month
%Y ---> for Year

Hence, we need to pass the datetime object as the key argument in the sorting function to tell the sorting function that it needs to compare the strings by converting them into dates and sort them in the increasing order.
Below is the implementation of the above approach:
# Python3 program to sort the list of dates# given in string format  # Import the datetime modulefrom datetime import datetime    # Function to print the data stored in the list def printDates(dates):        for i in range(len(dates)):          print(dates[i])               if __name__ == "__main__":        dates =  ["23 Jun 2018", "2 Dec 2017", "11 Jun 2018",               "01 Jan 2019", "10 Jul 2016", "01 Jan 2007"]            # Sort the list in ascending order of dates     dates.sort(key = lambda date: datetime.strptime(date, '%d %b %Y'))        # Print the dates in a sorted order     printDates(dates) 
01 Jan 2007
10 Jul 2016
2 Dec 2017
11 Jun 2018
23 Jun 2018
01 Jan 2019

Python string-programs
python-string
Technical Scripter 2018
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prove that every subgroup of a cyclic group is cyclic

05 Mar, 2021
To Prove :Every subgroup of a cyclic group is cyclic.
Cyclic Group :It is a group generated by a single element, and that element is called a generator of that cyclic group, or a cyclic group G is one in which every element is a power of a particular element g, in the group. That is, every element of G can be written as gn for some integer n for a multiplicative group, or ng for some integer n for an additive group. So, g is a generator of group G.
Proof :Let us suppose that G is a cyclic group generated by a i.e. G = {a}.If another group H is equal to G or H = {a}, then obviously H is cyclic.So let H be a proper subgroup of G. Therefore, the elements of H will be the integral powers of a.If as ∈ H, then the inverse of as i.e;
a-s ∈ H
Therefore, H contains elements that are positive as well as negative integral powers of a.Now, let m be the least positive integer such that
am ∈ H
Then we shall prove that :
H = { am }
i.e., H is cyclic and is generated by am .Let at be any arbitrary element of H.By division algorithm, there exists integers q and r, such that :
t = mq + r,    0 ≤ r <m.
Now,
  am ∈ H 
⇢(am)q ∈ H 
⇢ amq ∈ H
⇢(amq)-1 ∈ H
⇢a-mq  ∈ H.
Also,                 
at  ∈ H
a-mq  ∈ H ⇢ at a-mq  ∈ H
⇢ at-mq  ∈ H
⇢ ar  ∈ H.      (Since, r = t- mq)
Now m is the least positive integer, such that :
am ∈ H,      0 ≤ r <m.
Therefore, r must be equal to 0.Hence, 
 t = mq                    
Therefore,
at = amq =(am)q .
Hence, every element at ∈ H is of the form ( am )q .Therefore, H is cyclic and am is a generate of H.Hence, it is proved that every subgroup ( in this case H) of a cyclic group ( G ) is cyclic.  
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.yscale() in Python

12 Nov, 2020
Matplotlib Is a library in Python and it is a numerical – mathematical extension for the NumPy library. Pyplot Is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The matplotlib.pyplot.yscale() function in pyplot module of matplotlib library is used to set the y-axis scale.
Syntax: matplotlib.pyplot.yscale(value, **kwargs)
Parameters:
value = { “linear”, “log”, “symlog”, “logit”, ... }
These are various axis scale to apply.
 **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)
Example 1:
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport time%matplotlib inline  # Example 1y = np.random.randn(50)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y))  # plot with various axes scalesplt.figure()  # linearplt.subplot(221)plt.plot(x, y)plt.yscale('linear')plt.title('linear')plt.grid(True)    # logplt.subplot(222)plt.plot(x, y)plt.yscale('log')plt.title('log')plt.grid(True)    plt.show()
Output:
yscale plots for linear and log
Example 2:
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport time%matplotlib inline  # Example 2# useful for `logit` scalefrom matplotlib.ticker import NullFormatter  # Fixing random state for reproducibilitynp.random.seed(100)  # make up some data in the# interval ]0, 1[y = np.random.normal(loc=0.5,                      scale=0.4, size=1000)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y))  # plot with various axes scalesplt.figure()  # symmetric logplt.subplot(221)plt.plot(x, y - y.mean())plt.yscale('symlog', linthreshy=0.01)plt.title('symlog')plt.grid(True)  # logitplt.subplot(222)plt.plot(x, y)plt.yscale('logit')plt.title('logit')plt.grid(True)  plt.gca().yaxis.set_minor_formatter(NullFormatter())  # Adjust the subplot layout, because# the logit one may take more space# than usual, due to y-tick labels like "1 - 10^{-3}"plt.subplots_adjust(top=0.80, bottom=0.03,                     left=0.15, right=0.92,                    hspace=0.34,wspace=0.45)  plt.show()
Output:
yscale plots for symlog and logit
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find the power of a number using recursion


09 Jun, 2022

Given a number N and power P. The task is to write a Python program to find the power of a number using recursion.
Definition: The power of a number can be defined as multiplication of the number repetitively the number of times of its power.
Example: 
Input: N=2 , P=3
Output: 8
Input: N=5 , P=2
Output: 25
Approach: The idea is to calculate power of a number ‘N’ is to multiply that number ‘P’ times i.e In first example N=2 and P=3, we are getting the result by multiplying 2 three times repetitively which gives us output 8.
Below is the implementation:
Python
 

 
 










def power(N, P):
 
    # if power is 0 then return 1
    # if condition is true
    # only then it will enter it,
    # otherwise not
    if P == 0:  # base condition
        return 1
   
      # recurrence relation
    return (N*power(N, P-1))  
 
# Driver program
N = 5
P = 0
 
print(power(N, P))






1
subhajitghosh1997
williammxh
simmytarika5

Python function-programs


Technical Scripter 2020


Python


Python Programs


Technical Scripter

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
Python | Pandas Timestamp.days_in_month

08 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.days_in_month attribute return the number of days in the month for the given date in the Timestamp object.
Syntax : Timestamp.days_in_month
Parameters : None
Return : number of days in month
Example #1: Use Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(2017, 2, 15, 12)  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object.
# return the number of days in monthts.days_in_month
Output :
As we can see in the output, the Timestamp.days_in_month attribute has returned 28 indicating that there are 28 days in the month of the given Timestamp object.
Example #2: Use Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 10,            day = 21, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object.
# return the number of days in monthts.days_in_month
Output :
As we can see in the output, the Timestamp.days_in_month attribute has returned 31 indicating that there are 31 days in the month of the given Timestamp object.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axis.Axis.set_data_interval() function in Python

08 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_data_interval() function in axis module of matplotlib library is used to set the axis data limits. This method is for internal use. 
Syntax: Axis.set_data_interval(self, vmin, vmax, ignore=False)  
Parameters: This method accepts the following parameters. 
vmin: This parameter is the minimum data limit.
vmax: This parameter is the maximum data limit.
Return value: This method returns does not any value. 
Below examples illustrate the matplotlib.axis.Axis.set_data_interval() function in matplotlib.axis: 
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np    fig = plt.figure()   x = np.linspace(0,4*np.pi,100)y = 2*np.sin(x)   ax = fig.add_subplot()ax.plot(x,y)  ax.xaxis.set_data_interval(2, 4 ,True)   ax.grid()    fig.suptitle("""matplotlib.axis.Axis.set_data_interval()function Example\n""", fontweight ="bold")       plt.show()
Output:  
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np    np.random.seed(10**7)  geeks = np.random.randn(40)          fig, ax = plt.subplots()  ax.acorr(geeks, usevlines = True,           normed = True,lw = 3)         ax.grid(True)  ax.xaxis.set_data_interval(-10 , 10)   fig.suptitle("""matplotlib.axis.Axis.set_data_interval()function Example\n""", fontweight ="bold")       plt.show()
Output:  
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find the count of duplicate rows if they are greater than n in R data frame?

To find the count of duplicate rows if they are greater than n in R data frame, we can follow the below steps −
First of all, create a data frame.
Then, count the duplicate rows if they are greater than a certain number using group_by_all, count, and filter function of dplyr package.
Let's create a data frame as shown below −
 Live Demo
x<-rpois(30,1)
y<-rpois(30,1)
df<-data.frame(x,y)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
  x y
1 1 3
2 0 2
3 0 2
4 0 2
5 2 1
6 1 0
7 0 0
8 1 2
9 1 2
10 2 1
11 0 3
12 1 1
13 1 1
14 0 0
15 0 0
16 0 1
17 0 0
18 0 1
19 0 1
20 2 0
21 1 2
22 3 1
23 1 0
24 1 0
25 1 3
26 1 0
27 1 1
28 2 1
29 1 2
30 0 4
Loading dplyr package and using group_by_all, count, and filter function to find the
count of duplicate rows if they are greater than 2 −
x<-rpois(30,1)
y<-rpois(30,1)
df<-data.frame(x,y)
library(dplyr)
df%>%group_by_all()%>%count()%>%filter(n>2)
# A tibble: 7 x 3
# Groups: x, y [7]
     x     y     n
  <int> <int> <int>
1    0    0    4
2    0    1    3
3    0    2    3
4    1    0    4
5    1    1    3
6    1    2    4
7    2    1    3