code-rag-bench/online-tutorials huggingface dataset:
How to store single cache data in ReactJS ?

21 Jan, 2022
We can use the following approach in ReactJS to store single data into cache in ReactJS. We can cache some data into the browser and use it in our application whenever needed. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested.
Approach: Follow these simple steps in order to store single data into cache in ReactJS. We have created our addDataIntoCache function which takes the user data and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import * as React from 'react';  export default function App() {    // Function to add our give data into cache  const addDataIntoCache = (cacheName, url, response) => {    // Converting our response into Actual Response form    const data = new Response(JSON.stringify(response));      if ('caches' in window) {      // Opening given cache and putting our data into it      caches.open(cacheName).then((cache) => {        cache.put(url, data);        alert('Data Added into cache!')      });    }  };    return (    <div style={{ height: 500, width: '80%' }}>      <h4>How to store data into cache in ReactJS?</h4>      <button onClick={()=>addDataIntoCache('MyCache',      'https://localhost:300','SampleData')} >        Add Data Into Cache</button>    </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:
 
sooda367
simmytarika5
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Working with PNG Images using Matplotlib

15 Apr, 2019
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.
In this article, we will see how can we work with PNG images using Matplotlib.
Code #1: Read a PNG image using Matplotlib
# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img  # reading png image fileim = img.imread('imR.png')  # show imageplt.imshow(im)
Output:
Code #2: Applying pseudocolor to image
Pseudocolor is useful for enhancing contrast of image.
# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img  # reading png imageim = img.imread('imR.png')  # applying pseudocolor # default value of colormap is used.lum = im[:, :, 0]  # show imageplt.imshow(lum)
Output:
Code #3: We can provide another value to colormap with colorbar.
# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img  # reading png imageim = img.imread('imR.png')lum = im[:, :, 0]  # setting colormap as hotplt.imshow(lum, cmap ='hot')plt.colorbar()
Output:
Interpolation Schemes:Interpolation calculates what the color or value of a pixel “should” be and this needed when we resize the image but want the same information. There’s missing space when you resize image because pixels are discrete and interpolation is how you fill that space.
Code # 4: Interpolation
# importing PIL and matplotlibfrom PIL import Image import matplotlib.pyplot as plt  # reading png image  fileimg = Image.open('imR.png')  # resizing the imageimg.thumbnail((50, 50), Image.ANTIALIAS)imgplot = plt.imshow(img)
Output:
Code #6: Here, ‘bicubic’ value is used for interpolation.
# importing pyplot from matplotlibimport matplotlib.pyplot as plt  # importing image from PILfrom PIL import Image   # reading imageimg = Image.open('imR.png')  img.thumbnail((30, 30), Image.ANTIALIAS)   # bicubic used for interpolationimgplot = plt.imshow(img, interpolation ='bicubic')
Output:
Code #7: ‘sinc’ value is used for interpolation.
# importing PIL and matplotlibfrom PIL import Image import matplotlib.pyplot as plt  # reading imageimg = Image.open('imR.png')  img.thumbnail((30, 30), Image.ANTIALIAS)  # sinc used for interpolationimgplot = plt.imshow(img, interpolation ='sinc')
Output: Reference: https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html
Image-Processing
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to start nmap and run a simple scan ?

19 Jul, 2019
Nmap is a free and open-source utility which is used to scan networks and security auditing. Nmap can discover hosts and services on a computer network by sending packets and analyzing the responses. The utility is available on almost every os, it is available for windows, linux and mac.
Download Nmap –To download Nmap you can simply head towards the official website by clicking here. In case if kali Linux and parrot os, it is already available in there so you will not need to download the utility.
Please note that scanning websites from Nmap is not legal, in some cases if you are trying to too much in deep then you will need written permissions from the owner of the website and the IP holder.
In Windows hosts you can simply install nmap and run it from the desktop icon using administrator privileges . In linux hosts there are 2 ways of doing it, in case of kali linux and parrot os you can find the icon and click to start and later give it root privileges by entering your password .The other way is you can simply run
nmap --help
You can use it as a manual for using commands, just scroll down and head towards examples.
As already mentioned, scanning networks and websites using nmap can be illegal, you may need written permissions to so.So, to do scans be legal you can use scanme.org, they offer you to perform scans on their website without any issues, but please read their conditions so that you do not harm their website.Now lets see a simple example to do a scan.To do so simply use nslookup command following the website url or address. If you do not know the IP address of the website and using the command.
nslookup scanme.nmap.org
will give you its address. Now when you get the address you can use the same for scanning the network by
nslookup "address"
the address should be written as IP address which you found on the previous scan and without quotes.This is how you can do a simple network scan. Now you can also save your scans in a text file for simplicity by using the command
nslookup 45.33.32.156 >> result.txt
Please note that nmap is a very noisy scanning utility and you need to be anonymous and legal in some cases to do so. Please ensure that you use it for legal and educational purposes.
Cyber-security
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Overloading Varargs Methods in Java

A method with variable length arguments(Varargs) can have zero or multiple arguments. Also, Varargs methods can be overloaded if required.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   public static void Varargs(int... args) {
      System.out.println("\nNumber of int arguments are: " + args.length);
      System.out.println("The int argument values are: ");
      for (int i : args)
      System.out.println(i);
   }
   public static void Varargs(char... args) {
      System.out.println("\nNumber of char arguments are: " + args.length);
      System.out.println("The char argument values are: ");
      for (char i : args)
      System.out.println(i);
   }
   public static void Varargs(double... args) {
      System.out.println("\nNumber of double arguments are: " + args.length);
      System.out.println("The double argument values are: ");
      for (double i : args)
      System.out.println(i);
   }
   public static void main(String args[]) {
      Varargs(4, 9, 1, 6, 3);
      Varargs('A', 'B', 'C');
      Varargs(5.9, 2.5);
   }
}
Number of int arguments are: 5
The int argument values are:
4
9
1
6
3
Number of char arguments are: 3
The char argument values are:
A
B
C
Number of double arguments are: 2
The double argument values are:
5.9
2.5
HBase - Security

We can grant and revoke permissions to users in HBase. There are three commands for security purpose: grant, revoke, and user_permission.
The grant command grants specific rights such as read, write, execute, and admin on a table to a certain user. The syntax of grant command is as follows:
hbase> grant <user> <permissions> [<table> [<column family> [<column; qualifier>]]

We can grant zero or more privileges to a user from the set of RWXCA, where
R - represents read privilege.
W - represents write privilege.
X - represents execute privilege.
C - represents create privilege.
A - represents admin privilege.
Given below is an example that grants all privileges to a user named ‘Tutorialspoint’.
hbase(main):018:0> grant 'Tutorialspoint', 'RWXCA'

The revoke command is used to revoke a user's access rights of a table. Its syntax is as follows:
hbase> revoke <user>

The following code revokes all the permissions from the user named ‘Tutorialspoint’.
hbase(main):006:0> revoke 'Tutorialspoint'

This command is used to list all the permissions for a particular table. The
syntax of user_permission is as follows:
hbase>user_permission ‘tablename’

The following code lists all the user permissions of ‘emp’ table.
hbase(main):013:0> user_permission 'emp'

 Print
 Add Notes
 Bookmark this page
Angular CLI - Environment Setup

To work with Angular CLI, we need to have Node installed on our system. Let us understand about the environment setup required for Angular CLI in detail.
Download latest version of Node.js installable archive file from Node.js Downloads, which is available at https://nodejs.org/download/. At the time of writing this tutorial, the versions available on different OS are listed below −
Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then, finally move extracted files into/usr/local/nodejs directory.
For example −
$ cd /tmp

$ wgethttp://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz

$ tar xvfz node-v6.3.1-linux-x64.tar.gz

$ mkdir -p /usr/local/nodejs

$ mv node-v6.3.1-linux-x64/*/usr/local/nodejs

Add /usr/local/nodejs/bin to the PATH environment variable.
Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\Program Files\nodejs.
The installer should set the C:\ProgramFiles\nodejs\bin directory in windows PATH environment variable.Restart any open command prompts for the change to take effect.
Create a js file named main.json your machine (Windows or Linux) having the following code −
/* Hello, World! program in node.js */
console.log("Hello, World!")

The link for live demo is https://www.tutorialspoint.com/execute_nodejs_online.php.
Now, execute main.js file using Node.js interpreter to see the result −
$ node main.js

If everything is fine with your installation, this should produce the following result −
Hello, World!

Now, the Node is installed. You can run the following command to install Angular CLI.
npm install -g @angular/cli

Now, run the following command to seethe result −
$ ng --version

If everything is fine with yourinstallation, this should produce the following result −

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 9.1.0
Node: 12.16.1
OS: win32 x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.0
@angular-devkit/core         9.1.0
@angular-devkit/schematics   9.1.0
@schematics/angular          9.1.0
@schematics/update           0.901.0
rxjs                         6.5.4

On Windows, in case of ng being not recognised as internal or external command, update
the system path variable to include the following path.
C:\Users\<User Directory>\AppData\Roaming\npm


    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Which MySQL data type is used for long decimal?

For this, use DECIMAL(21,20). Let us first create a table −
mysql> create table DemoTable1493
   -> (
   -> LongValue DECIMAL(21,20)
   -> );
Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1493 values(1.0047464644664677373);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1493 values(5.999999484757773);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1493 values(0.009994995885885);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1493;
This will produce the following output −
+------------------------+
| LongValue              |
+------------------------+
| 1.00474646446646773730 |
| 5.99999948475777300000 |
| 0.00999499588588500000 |
+------------------------+
3 rows in set (0.00 sec)
C++ program to get the Sum of series: 1 – x^2/2! + x^4/4! -.... upto nth term

In this tutorial, we will be discussing a program to get the sum of series 1 – x^2/2! + x^4/4! ... upto nth term.
For this we will be given with the values of x and n. Our task will be to calculate the sum of the given series upto the given n terms. This can be easily done by computing the factorial and using the standard power function to calculate powers.
#include <math.h>
#include <stdio.h>
//calculating the sum of series
double calc_sum(double x, int n){
   double sum = 1, term = 1, fct, j, y = 2, m;
   int i;
   for (i = 1; i < n; i++) {
      fct = 1;
      for (j = 1; j <= y; j++) {
         fct = fct * j;
      }
      term = term * (-1);
      m = term * pow(x, y) / fct;
      sum = sum + m;
      y += 2;
   }
   return sum;
}
int main(){
   double x = 5;
   int n = 7;
   printf("%.4f", calc_sum(x, n));
   return 0;
}
0.3469
How to Extract filename from a given path in C# - GeeksforGeeks

04 Apr, 2019
While developing an application that can be desktop or web in C#, such kind of requirement to extract the filename from a given path (where the path can be taken while selecting a file using File Open dialog box or any other sources) can arise. A path may contain the drive name, directory name(s) and the filename. To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.
Syntax: public static string GetFileName (string path);Here, path is the string from which we have to obtain the file name and extension.
Return Value: This method will return the characters after the last directory separator character in path. If the last character of the path is a directory or volume separator character, this method returns Empty. If the path is null, this method returns null.
Exception: This method will give ArgumentException if the path contains one or more of the invalid characters defined in GetInvalidPathChars().
Examples:
Input : 

string strPath = "c://myfiles//ref//file1.txt";

//function call to get the filename
filename = Path.GetFileName(strPath);

Output :

file1.txt

// C# program to extract the // filename from a given pathusing System;using System.IO;using System.Text;  namespace Geeks {  class GFG {      // Main Method    static void Main(string[] args)    {          // taking full path of a file        string strPath = "C:// myfiles//ref//file1.txt";          // initialize the value of filename        string filename = null;          // using the method        filename = Path.GetFileName(strPath);        Console.WriteLine("Filename = " + filename);          Console.ReadLine();    }}}
Filename = file1.txt

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netframework-4.7.2
CSharp-method
CSharp-Path-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Delegates
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
Why do we use internal keyword in C#?

Internal keyword allows you to set internal access specifier.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly.
Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
using System;

namespace RectangleApplication {
   class Rectangle {

      internal double length;
      internal double width;

      double GetArea() {
         return length * width;
      }

      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }

   class Demo {
      static void Main(string[] args) {
         Rectangle rc = new Rectangle();
         rc.length = 10.35;
         rc.width = 8.3;
         rc.Display();
         Console.ReadLine();
      }
   }
}
TypeScript | Array concat() Method

18 Jun, 2020
The Array.concat() is an inbuilt TypeScript function which is used to merge two or more arrays together. Syntax:
array.concat(value1, value2, ..., valueN)
Parameter: This method accepts a single parameter multiple time as mentioned above and described below: 
valueN : These parameters are arrays and/or values to concatenate.
Return Value: This method returns the new array. Below examples illustrate the Array concat() method in TypeScriptExample 1: 
JavaScript
<script>    // Driver code    var num1 = [11, 12, 13];    var num2 = [14, 15, 16];    var num3 = [17, 18, 19];       // use of String concat() Method    console.log(num1.concat(num2, num3)); </script>
Output: 
[ 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

Example 2: 
JavaScript
<script>    // Driver code    var num1 = ['a', 'b', 'c'];      // use of String concat() Method    console.log(num1.concat(1, [2, 3])); </script>
Output: 
[ 'a', 'b', 'c', '1,2,3' ]

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python – Maximum in Row Range

12 Nov, 2020
Given a range and a Matrix, extract the maximum element out of that range of rows.
Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 2, 5 Output : 12 Explanation : Checks for rows 2, 3 and 4, maximum element is 12.
Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 1, 4 Output : 10 Explanation : Checks for rows 1, 2 and 3, maximum element is 10. 
Method #1 : Using max() + slicing  
In this, we perform the task of slicing the rows in which maximum has to be found, then the maximum is found for each row using max(), another max() is applied to get maximum upon extracted elements.
Python3
# Python3 code to demonstrate working of# Maximum in Rows Range# Using max() + slicing  # initializing listtest_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2],             [9, 10, 3], [5, 9, 12], [3, 14, 2]]  # printing original listprint("The original list is : " + str(test_list))  # initializing rangei, j = 2, 4  res = 0for idx in range(i, j):      # getting max in range    res = max(max(test_list[idx]), res)  # printing resultprint("The maximum element in row range ? : " + str(res))
Output:
The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]The maximum element in row range ? : 10
Method #2 : Using max() + slicing + list comprehension
In this, we perform the similar task as above using list comprehension to offer one liner to this operation.
Python3
# Python3 code to demonstrate working of# Maximum in Rows Range# Using max() + slicing + list comprehension  # initializing listtest_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2],             [9, 10, 3], [5, 9, 12], [3, 14, 2]]  # printing original listprint("The original list is : " + str(test_list))  # initializing rangei, j = 2, 4  # getting max of maximum of sub listsres = max([max(test_list[idx]) for idx in range(i, j)])  # printing resultprint("The maximum element in row range ? : " + str(res))
Output:
The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]The maximum element in row range ? : 10
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Restrict Dynamic Allocation of Objects in C++?

21 Jun, 2022
C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java & C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scope and dynamically allocated objects must be manually released, using the delete operator otherwise, a memory leak occurs. C++ doesn’t support the automatic garbage collection approach used by languages such as Java & C#. How do we achieve the following behavior from a class ‘Test’ in C++? 
Test* t = new Test; // should produce compile time error
Test t;    // OK 
The idea is to keep the new operator function private so that new cannot be called. See the following program. Objects of the ‘Test’ class cannot be created using new as new operator function is private in ‘Test’. If we uncomment the 2nd line of main(), the program would produce a compile-time error. 
CPP
// CPP Program to restrict dynamic// allocation of objects in C++#include <iostream>using namespace std; // Objects of Test can not be// dynamically allocatedclass Test {    // new operator function is private    void* operator new(size_t size);    int x; public:    Test()    {        x = 9;        cout << "Constructor is called\n";    }    void display() { cout << "x = " << x << "\n"; }    ~Test() { cout << "Destructor is executed\n"; }}; // Driver Codeint main(){     // Test* obj=new Test(); -> Uncommenting this line would    // cause a compile time error.    Test t; // Ok, object is allocated at compile time    t.display();    // object goes out of scope, destructor will be called    return 0;}
Constructor is called
x = 9
Destructor is executed
Also, it is a general query if we can allocate memory for the objects dynamically in C++? 
Yes, we can dynamically allocate objects also. 
Whenever a new object is created, constructor, a member function of a class is called.
Whenever the object goes out of scope, destructor, a class member function is called.
Time complexity : O(1) Auxiliary Space : O(1)
This article is contributed by Pravasi Meet. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
mahendrabagul569
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to detect “shift+enter” and generate a new line in Textarea?

31 Oct, 2019
The text area tag defines a multi-line text input control. The size of a text area can be specified by the cols and rows attributes. By default, whenever we press “enter” or “shift+enter” it creates a new line in the text area. So, to only detect “shift+enter” and generate a new line from it we need to block “enter” from generating a new line and to redirect it to do something else like submitting.
Example 1: Check out the following Example for “enter” and “shift+enter” mechanism. So, here in the below code both “enter” and “shift+enter” do the same. So, all that has to be done is to either block the “enter” mechanism or redirecting it to do something else.
<!DOCTYPE html><html><body>    <center>        <h1 style="color:green;">GeeksforGeeks</h1>        <script>            function geeks(event) {                // 13 is the keycode for "enter"                if (event.keyCode == 13 && event.shiftKey) {                    document.getElementById("d").innerHTML = "Triggered enter+shift";                }                if (event.keyCode == 13 && !event.shiftKey) {                    document.getElementById("d").innerHTML = "Triggered enter";                }            }        </script>        <h4>Press "enter" or "shift+enter" in the textarea, both does the same.</h4>        <textarea rows="8" cols="50" onkeypress="geeks(event)">GeeksforGeeks A Computer science portal for geeks.        </textarea>        <p id="d" style="color:red"></p>    </center></body>  </html>
Output:
Example 2: In the below code, we created a function(submitForm()) to submit the form which just contains a line, because placing this document.geek.submit() under event.preventDefault(), document.geek.submit() will overrides the event.preventDefault() and never blocks the “enter” from creating a line.
<!DOCTYPE html><html>  <head>    <script>        function press(event) {            if (event.keyCode == 13 && !event.shiftKey) {                                //Stops enter from creating a new line                event.preventDefault();                 submitForm();                return true;            }              function submitForm() {                document.geek.submit(); //submits the form.            }        }    </script></head>  <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <h4>        Press "enter" to submit and "shift+enter" to generate a new line.        </h4>        <form action="submit.html" name="geek">            <textarea rows="7" cols="30" onkeypress="press(event)"></textarea>        </form>    </center></body>  </html>
HTML in submit.html:
<!DOCTYPE html><html>   <body>     <h2 style="color:red">List Submitted.</h2>   </body></html>  
Output:
JavaScript-Misc
Picked
JavaScript
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MATLAB – Read images using imread() function

12 Dec, 2021
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984. It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms, and creation of user interfaces. 
In this article, we are going to discuss how to read images using MATLAB.
In-order to read images we are going to use the imread() function in MATLAB. The imread() function reads images from the graphics files.
Syntax:
A = imread(filename)
It simply read the image and stores it in A.
A = imread(filename,fmt)
Reads image in grayscale or color from the specified file.if image is not present in current directory then please provide the full path of image.
A = imread(Name,Value)
It peruses the predefined picture or pictures from a multi-picture record. This grammar applies just to GIF, PGM, PM, PPM, CUR, ICO, TIF, SVS, and HDF4 documents. You should indicate a filename information, and you can alternatively determine fmt.
Example 1:
Below is a program in which we read a color image using imread() function and store it in A (the imread() function restores the picture information in cluster A) and then we display the image using imshow() function. 
C++
% reading imageA = imread('g4g.jpg'); % displaying imageimshow(A);
Output:
 
Example 2:
Here is another example to read an image in MATLAB.
C++
% reading imageA = imread('g4g.jpg'); % displaying imageimshow(A);
Output:
Note: In the event, if the image is grayscale then, A will be a two-dimensional (M-by-N) exhibit, or else A will be a three-dimensional (M-by-N-by-3) exhibit. The class of the returned cluster relies upon the information type utilized by the record design.
adnanirshad158
MATLAB
Advanced Computer Subject
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Markov Decision Process
Getting Started with System Design
Differences between Procedural and Object Oriented Programming
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Decorators with parameters in Python
How to close a window in Tkinter?

09 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.
To close a tkinter window, we can use the destroy() method. The destroy() is a universal widget method i.e we can use this method with any of the available widgets as well as with the main tkinter window.
Example:
In the below example, we are going to implement the destroy() method using a button.  
Python
# import required module from tkinter import *  # create objectroot = Tk()  # create button to implement destroy()Button(root, text="Quit", command=root.destroy).pack()  root.mainloop()
Output:
In the above example, on clicking the button the destroy() method is called and the tkinter window is closed.
Python-gui
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE-CS-2015 (Set 3) - GeeksforGeeks

08 Oct, 2021
Six selected members are P, Q, R, S, T and U

Portfolios are Home, Power, Defence, Telecom, and Finance. 

U does not want any portfolio if S gets one of the five. 

R wants either Home or Finance or no portfolio. 

Q says that if S gets either Power of telecom, then she must 
get the other one.

T insists on a portfolio if P gets one Which is the valid 
distribution of portfolios?

A) P-Home, Q-Power, R-Defence, S-Telecom, T-Finance
Not valid as R doesn't get home or finance here

R-Home, S-Power, P-Defence, Q-Telecom, T-Finance
Is valid and satisfies all conditions.

C) P-Home, Q-Power, T-Defence, S-Telecom, U-Finance
Not valid as U is not satisfied. Condition for U is, S should not
get any portfolio.

D) Q-Home, U-Power, T-Defence, R-Telecom, P-Finance
Like A, not valid as R doesn't get home or finance here


The problem can be easily solved by trying point (2, -1) 
on thick line, i.e., x = 2, y = -1.

None of the options except (B) satisfy above values. 
(i) He was already a successful batsman at the highest level.
(ii) He has to improve his temperament in order to become a great batsman.
(iii) He failed to make many of his good starts count.
(iv) Improving his technical skills will guarantee success.
In 2006 export increased from 70 yo 100 and import increased from 90 to 120.

% increase in import = 30/70 = 42.8 %
% increase in export = 30/90 = 33.33 %

Combined % increase in 2006 is more than any other year.  
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
MongoDB – Inequality Operator $ne

27 Mar, 2020
MongoDB provides different types of comparison operators and inequality or not equals operator( $ne ) is one of them. This operator is used to select those documents where the value of the field does not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(), etc. as per your requirement.
Syntax:
{field: {$ne: value}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs.
Example #1:In this example, we are selecting those documents where the value of the experienceYear field is not equal to 2.
 Example #2:In this example, we are selecting only those documents where the last name of the employees is not Goyal. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation.
 Example #3:In this example, we are selecting those documents where the points array is not equal to the specified array.
 Example #4:In this example, we are updating the salary to 55000 of those employees whose department is not HR. Or in other words, set the value of the salary field to 55000 of those documents whose department field value is not equal to HR.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Fuzzy Logic | Introduction
Mounting a Volume Inside Docker Container
Python - Data Science Tutorial

Data is the new Oil. This statement shows how every modern IT system is driven by capturing, storing and analysing data for various needs. Be it about making decision for business, forecasting weather, studying protein structures in biology or designing a marketing campaign. All of these scenarios involve a multidisciplinary approach of using mathematical models, statistics, graphs, databases and of course the business or scientific logic behind the data analysis. So we need a programming language which can cater to all these diverse needs of data science. Python shines bright as one such language as it has numerous libraries and built in features which makes it easy to tackle the needs of Data science.
In this tutorial we will cover these the various techniques used in data science using the Python programming language.
This tutorial is designed for Computer Science graduates as well as Software Professionals who are willing to learn data science in simple and easy steps using Python as a programming language.
Before proceeding with this tutorial, you should have a basic knowledge of writing code in Python programming language, using any python IDE  and execution of Python programs.
If you are completely new to python then please refer our  Python tutorial  to get a sound understanding of the language.
For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning.
Try following example using Try it option available at the top right corner of the below sample code box 
#!/usr/bin/python

print "Hello, Python!"
set_page_load_timeout driver method – Selenium Python

24 Oct, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around set_page_load_timeout driver method in Selenium. set_page_load_timeout method sets the amount of time to wait for a page load to complete before throwing an error.Syntax –  
driver.set_page_load_timeout(time_To_wait)
Example – Now one can use set_page_load_timeout method as a driver method as below –  
driver.get("https://www.geeksforgeeks.org/")
driver.set_page_load_timeout(30)
 
To demonstrate, set_page_load_timeout method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.Program –  
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # sets timeout to 30driver.set_page_load_timeout(30)
Output – Browse r –  
 
akshaysingh98088
Python-selenium
selenium
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
SQL | INTERSECT Clause

09 Nov, 2020
The INTERSECT clause in SQL is used to combine two SELECT statements but the dataset returned by the INTERSECT statement will be the intersection of the data-sets of the two SELECT statements. In simple words, the INTERSECT statement will return only those rows which will be common to both of the SELECT statements.
Pictorial Representation:
The INTERSECT statement will return only those rows present in the red shaded region. i.e. common to both of the data-sets.
Note: The number and type of fields present in the two data-sets must be same and similar.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Syntax:
SELECT column1 , column2 ....
FROM table_names
WHERE condition

INTERSECT

SELECT column1 , column2 ....
FROM table_names
WHERE condition

Sample Tables:
Customers Table:
Orders Table:
Sample Queries:
SELECT  ID, NAME, Amount, Date
     FROM Customers
     LEFT JOIN Orders
     ON Customers.ID = Orders.Customer_id
INTERSECT
     SELECT  ID, NAME, Amount, Date
     FROM Customers
     RIGHT JOIN Orders
     ON Customers.ID = Orders.Customer_id;

Output:
17. Intersect in SQL (Top 50 SQL Interview Questions) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribers17. Intersect in SQL (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ulu-P55RpDA" 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 Harsh Agarwal. 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.
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a dictionary to a file in Python

29 Dec, 2020
Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it.
Method:1 Storing Dictionary With Object Using Json
Approach:
Import Json
Create A Dictionary  in-order pass it into text file.
Open file in write mode.
Use json.dumps() for json string
Code:
Python3
import json  details = {'Name': "Bob",          'Age' :28}  with open('convert.txt', 'w') as convert_file:     convert_file.write(json.dumps(details))
Output:
Method 2: Using Loop
Approach:
Create a dictionary.
Open a file in write mode.
Here We Use For Loop With Key Value Pair Where “Name”  is Key And  “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs 
Then f.write() Function Just Write’s The Output In Form Of String “%s” 
Code:
Python3
details={'Name' : "Alice",         'Age' : 21,         'Degree' : "Bachelor Cse",         'University' : "Northeastern Univ"}  with open("myfile.txt", 'w') as f:     for key, value in details.items():         f.write('%s:%s\n' % (key, value))
Output:
Method:3 Without Using loads(),dumps().
Here The Steps Are Followed Above Methods But in Write We Use Str() Method Which Will Convert The Given Dictionary Into String
Python3
details = {'Name': "Bob", 'Age' :28}   with open('file.txt','w') as data:       data.write(str(details))
Output:
Picked
Python file-handling-programs
python-file-handling
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
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
How to count the number of times a button is clicked using JavaScript ?

29 Jan, 2021
We have given a button, and the task is to count how many times the button is clicked using JavaScript. 
Approach: First, we will create a HTML button and a paragraph element where we display the button click count. When the button is clicked, the JavaScript function called. We declare a count variable and initialize it to 0. When user clicks the button, the count value increased by 1 and display it on the screen.
Example:
HTML
<!DOCTYPE HTML><html>  <head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>Increment count when button is clicked</title></head>  <body style="text-align: center;">    <h1 style="color: green;">        GeeksforGeeks    </h1>      <h4>        How to count the number of         times a button is clicked?    </h4>      <button id="btn">Click Here!</button>      <p>        Button Clicked <span         id="display">0</span> Times    </p>      <script type="text/javascript">        var count = 0;        var btn = document.getElementById("btn");        var disp = document.getElementById("display");          btn.onclick = function () {            count++;            disp.innerHTML = count;        }    </script></body>  </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
OAuth 2.0 - Accessing a Protected Resource

The client provides an access token to the resource server to access protected resources. The resource server must validate and verify that the access token is valid and has not expired.
There are two standard ways of sending credentials −
Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header.
Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header.
They are included in the authorization header as follows −
Authorization: Bearer [token-value]

For Example −
GET/resource/1 HTTP /1.1
Host: example.com
Authorization: Bearer abc...

MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner.
MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner.
The following table shows the concepts of accessing protected resource.
It is used to get the authorization code token for accessing the owner resources in the system.
The resource server includes the "WWW-Authenticate" response header field, if the protected resource request contains an invalid access token.
 Print
 Add Notes
 Bookmark this page
Java - String intern() Method

This method returns a canonical representation for the string object. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
Here is the syntax  of this method −
public String intern()

Here is the detail of parameters −
This is a default method and this do not accept any parameters.
This method returns a canonical representation for the string object.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialspoint.com");
      String Str2 = new String("WELCOME TO SUTORIALSPOINT.COM");

      System.out.print("Canonical representation:" );
      System.out.println(Str1.intern());

      System.out.print("Canonical representation:" );
      System.out.println(Str2.intern());
   }
}
This will produce the following result −
Canonical representation: Welcome to Tutorialspoint.com
Canonical representation: WELCOME TO SUTORIALSPOINT.COM


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page