code-rag-bench/online-tutorials huggingface dataset:
Convert array with duplicate values to object with number of repeated occurrences in JavaScript

Suppose, we have an array string that contains some duplicate entries like this −
const arr = ['California','Texas','Texas','Texas','New
York','Missouri','New Mexico','California'];
We are required to write a JavaScript function that takes in one such array. Our function should then construct an array of objects that contains an object for each unique entry and a property "count" that contains its count in the original array.
Therefore, the final output for the above array should look something like this −
const output = [
   {'name':'California', 'count':2},
   {'name':'Texas', 'count':3},
   {'name':'New York', 'count':1},
   {'name':'Missouri', 'count':1},
   {'name':'New Mexico', 'count':1},
];
The code for this will be −
const arr = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'];
const findOccurrences = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      const index = res.findIndex(obj => {
         return obj['name'] === el;
      });
      if(index === -1){
         res.push({
            "name": el,
            "count": 1
         })
      }
      else{
         res[index]["count"]++;
      };
   });
   return res;
};
console.log(findOccurrences(arr));
And the output in the console will be −
[
   { name: 'California', count: 2 },
   { name: 'Texas', count: 3 },
   { name: 'New York', count: 1 },
   { name: 'Missouri', count: 1 },
   { name: 'New Mexico', count: 1 }
]
Python | Removing duplicates from tuple - GeeksforGeeks

29 Oct, 2019
Many times, while working with Python tuples, we can have a problem of removing duplicates. This is a very common problem and can occur in any form of programming set up, be it regular programming or web development. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using set() + tuple()This is the most straight forward way to remove duplicates. In this, we convert the tuple to a set, removing duplicates and then converting it back again using tuple().
# Python3 code to demonstrate working of# Removing duplicates from tuple # using tuple() + set()  # initialize tupletest_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3)  # printing original tuple print("The original tuple is : " + str(test_tup))  # Removing duplicates from tuple # using tuple() + set()res = tuple(set(test_tup))  # printing resultprint("The tuple after removing duplicates : " + str(res))
The original tuple is : (1, 3, 5, 2, 3, 5, 1, 1, 3)
The tuple after removing duplicates : (1, 2, 3, 5)

 
Method #2 : Using OrderedDict() + fromkeys()The combination of above functions can also be used to perform this particular task. In this, we convert the tuples to dictionary removing duplicates and then accessing it’s keys.
# Python3 code to demonstrate working of# Removing duplicates from tuple # using OrderedDict() + fromkeys()from collections import OrderedDict  # initialize tupletest_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3)  # printing original tuple print("The original tuple is : " + str(test_tup))  # Removing duplicates from tuple # using OrderedDict() + fromkeys()res = tuple(OrderedDict.fromkeys(test_tup).keys())  # printing resultprint("The tuple after removing duplicates : " + str(res))
The original tuple is : (1, 3, 5, 2, 3, 5, 1, 1, 3)
The tuple after removing duplicates : (1, 2, 3, 5)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to add Django debug toolbar to your project?

Django toolbox is a debugging tool that is used to debug database queries, Django website loading speed, and many other things. Debug toolbar is very popular among developers and everyone is using it. So, let's dive into to see how to implement it.
Create an app with the name "myapp".
First, install the django-debug-toolbar −
pip install django-debug-toolbar
Now, add 'debug_toolbar' to your INSTALLED_APPS in settings.py −
INSTALLED_APPS = [
   # ...
   'debug_toolbar',
   'myapp'
]
This will add the debug toolbar as an app in our project.
Next, in your middleware, add the following −
MIDDLEWARE = [
   # ...
   'debug_toolbar.middleware.DebugToolbarMiddleware',
   # ...
]
This is used to give access to the database.
Now, in urls.py of your project main directory, add the debug toolbar url −
import debug_toolbar
from django.conf import settings
from django.urls import include, path
urlpatterns = [
   ...
   path('__debug__/', include(debug_toolbar.urls)),
path('', include('myapp.urls'))
]
URL will define where all the debug reports should show and where the debug toolbar is needed to be hosted.
Now, in settings.py, add one more variable INTERNAL_IPS and mention localhost in it −
INTERNAL_IPS = [
   # ...
   '127.0.0.1',
   # ...
]
This variable will define which URL should be debugged and on which debug should be shown.
Next, in views.py of app, add the following −
from django.shortcuts import render

# Create your views here.
def home(request):
   return render(request,"home.html")
It will render the frontend file.
Now, in urls.py of app, add the following −
from django.urls import path
from . import views
urlpatterns = [
   path('',views.home,name="home" ),
]
It will render the main view.
Next, create a folder in the app directory and name it templates and add home.html in it. In home.html, add the following simple code −
<!DOCTYPE html>
<html>
   <head>

   </head>
   <body>
      <h1>success</h1>
   </body>
</html>
It will just render a simple message.
You will see this toolbar at the right side of your screen on every URL
endpoint −
Is there any way in MongoDB to get the inner value of json data?

To get inner value of JSON data, use find() along with dot(.) notation. Let us create a collection with documents −
> db.demo235.insertOne(
...   {
...      "id":101,
...      "details":[
...         {
...            "Name":"Chris Brown",
...            "Age":21
...         },
...         {
...            "Name":"David Miller",
...            "Age":24
...         }
...      ],
...      "otherdetails":[
...         {
...            "Score":56,
...            "Subject":"MongoDB"
...         },
...         {
...            "Score":78,
...            "Subject":"MySQL"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e418d22f4cebbeaebec514b")
}
Display all documents from a collection with the help of find() method −
> db.demo235.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e418d22f4cebbeaebec514b"),
   "id" : 101,
   "details" : [
      {
         "Name" : "Chris Brown",
         "Age" : 21
      },
      {
         "Name" : "David Miller",
         "Age" : 24
      }
   ],
   "otherdetails" : [
      {
         "Score" : 56,
         "Subject" : "MongoDB"
      },
      {
         "Score" : 78,
         "Subject" : "MySQL"
      }
   ]
}
Following is the query to get the inner value of json data −
> db.demo235.find({},{"otherdetails.Subject":1,_id:0});
This will produce the following output −
{ "otherdetails" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }
What is CGI in Python?

The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e., filename.
Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.
Web browser takes response from web server and displays either the received file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc.
Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well.
By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file −
<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc.
How to change Tkinter Button state from disabled to normal?

Tkinter provides Button widgets to create a button for triggering an event. Let us suppose we have created a button that is already disabled in an application. In order to change the state of the button, we can use the state property.
The state property is used to enable and disable a button in an application. In order to change the state of the application, we have two operations: state=DISABLED and state=NORMAL.
#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("650x450")

#Define a function for Button Object
def quit_win():
   win.destroy()

#Create a button to quit the window
Button(win,text="Quit", command=quit_win, font=('Helvetica bold',20),
state= NORMAL).pack(pady=5)

win.mainloop()
The output when the button is disabled,
Output when Button state=NORMAL
Very simple Python script for extracting most common words from a story | by Tirthajyoti Sarkar | Towards Data Science

What is the most used word in all of Shakespeare plays? Was ‘king’ more often used than ‘Lord’ or vice versa?
To answer these type of fun questions, one often needs to quickly examine and plot most frequent words in a text file (often downloaded from open source portals such as Project Gutenberg). However, if you search on the web or on Stackoverflow, you will most probably see examples of nltk and use of CountVectorizer. While they are incredibly powerful and fun to use, the matter of the fact is, you don’t need them if the only thing you want is to extract most common words appearing in a single text corpus.
Below, I am showing a very simple Python 3 code snippet to do just that — using only a dictionary and simple string manipulation methods.
Feel free to copy the code and use your own stopwords to make it better!
import collectionsimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline# Read input file, note the encoding is specified here # It may be different in your text filefile = open('PrideandPrejudice.txt', encoding="utf8")a= file.read()# Stopwordsstopwords = set(line.strip() for line in open('stopwords.txt'))stopwords = stopwords.union(set(['mr','mrs','one','two','said']))# Instantiate a dictionary, and for every word in the file, # Add to the dictionary if it doesn't exist. If it does, increase the count.wordcount = {}# To eliminate duplicates, remember to split by punctuation, and use case demiliters.for word in a.lower().split():    word = word.replace(".","")    word = word.replace(",","")    word = word.replace(":","")    word = word.replace("\"","")    word = word.replace("!","")    word = word.replace("â€œ","")    word = word.replace("â€ ̃","")    word = word.replace("*","")    if word not in stopwords:        if word not in wordcount:            wordcount[word] = 1        else:            wordcount[word] += 1# Print most common wordn_print = int(input("How many most common words to print: "))print("\nOK. The {} most common words are as follows\n".format(n_print))word_counter = collections.Counter(wordcount)for word, count in word_counter.most_common(n_print):    print(word, ": ", count)# Close the filefile.close()# Create a data frame of the most common words # Draw a bar chartlst = word_counter.most_common(n_print)df = pd.DataFrame(lst, columns = ['Word', 'Count'])df.plot.bar(x='Word',y='Count')
An example of the code output and plot of the 10 most frequently used words in the corpus. The text is ‘Pride and Prejudice’ and you can see the familiar names of Elizabeth and Mr. Darcy! :)
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
How to open URL in a new window using JavaScript ? - GeeksforGeeks

31 Dec, 2019
In HTML, the anchor tag is used to open new windows and tabs in a very straightforward manner. However, there is a need to do the same using JavaScript. In JavaScript, window.open() proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values.
Syntax:
window.open(URL, name, specs, replace);
Note: All the parameters are optional.
Approach:
To open a URL in new window, make sure that the second parameter is not _blank.
The other parameters can be varied accordingly as per the need of the new window.
Example 1:
<!DOCTYPE html><html>  <body style="text-align:center;">      <h1 style="color:green">        GeeksforGeeks    </h1>      <p>        Click the button to        open a new window.    </p>      <button onclick="NewTab()">        Open Geeksforgeeks    </button>      <script>        function NewTab() {            window.open("https://www.geeksforgeeks.org",                    "", "width=300, height=300");        }    </script></body>  </html>
Output:
Before Clicking on Button:
After Clicking on Button:
Example 2: Use Anchor tag to open URL in a new window.
<!DOCTYPE html><html>  <body style="text-align:center;">          <h1 style="color:green">        GeeksforGeeks    </h1>          <p>        Click the button to open        GeeksforGeeks in a new window.    </p>      <a onclick=    'window.open("https://www.geeksforgeeks.org/",            "_blank", "width=300, height=300");'>        GeeksforGeeks    </a></body>  </html>
Output:
Before Clicking on GeeksforGeeks:
After Clicking on GeeksforGeeks:
Example 3: Use Input tag to open URL in a new window.
<!DOCTYPE html><html>  <body style="text-align:center;">          <h1 style="color:green">        GeeksforGeeks    </h1>          <p>        Click the button to open        GeeksforGeeks in a new window.    </p>      <input type="button"        onclick="window.open(        'https://www.geeksforgeeks.org/','geeks',        'toolbars=0,width=300,height=300,left=200,        top=200,scrollbars=1,resizable=1');"         value="Open the window"></body>  </html>                    
Output:
Before Clicking on Button:
After Clicking on Button:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
ggplot2 - Background Colors

There are ways to change the entire look of your plot with one function as mentioned below. But if you want to simply change the background color of the panel you can, use the following −
We can change the background color using following command which helps in changing the panel (panel.background) −
> ggplot(iris, aes(Sepal.Length, Species))+geom_point(color="firebrick")+
+ theme(panel.background = element_rect(fill = 'grey75'))

The change in color is clearly depicted in picture below −
We can change the grid lines using property “panel.grid.major” as mentioned in command below −
> ggplot(iris, aes(Sepal.Length, Species))+geom_point(color="firebrick")+
+    theme(panel.background = element_rect(fill = 'grey75'),
+    panel.grid.major = element_line(colour = "orange", size=2),
+    panel.grid.minor = element_line(colour = "blue"))

We can even change the plot background especially excluding the panel using “plot.background” property as mentioned below −
ggplot(iris, aes(Sepal.Length, Species))+geom_point(color="firebrick")+
+   theme(plot.background = element_rect(fill = 'pink'))

 Print
 Add Notes
 Bookmark this page
How to remove disabled attribute using jQuery?

To remove disabled attribute using jQuery, use the removeAttr() method. You need to first remove the property using the prop() method. It will set the underlying Boolean value to false.
You can try to run the following code to learn how to remove disabled attribute using jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $('.disabledCheckboxes').prop("disabled", true);
    $('.disabledCheckboxes').removeAttr("disabled");

    $(document).ready(function(){
        $('button').on('click', function() {
          if (this.hasAttribute("disabled")) {
             alert('The disabled attribute exists')
          } else {
             alert('The disabled attribute does not exist')
          }
        })
    });
 });
</script>
</head>
<body>
<input type="checkbox" class="disabledCheckboxes" disabled>
<input type="checkbox" class="disabledCheckboxes" disabled="disabled">
   <button class='button'>Result</button>
</body>
</html>
GATE | GATE-CS-2003 | Question 90 - GeeksforGeeks

28 Jun, 2021
Let G = ({S}, {a, b} R, S) be a context free grammar where the rule set R isS → a S b | SS | εWhich of the following statements is true?(A) G is not ambiguous(B) There exist x, y, ∈ L (G) such that xy ∉ L(G)(C) There is a deterministic pushdown automaton that accepts L(G)(D) We can find a deterministic finite state automaton that accepts L(G)Answer: (C)Explanation:
An ambiguous grammar can be converted to unambiguous one.

Here we can get grammar in partial GNF form as
S -> ab | abS | aSb | aSbS

We can convert this into GNF too but no need for PDA reasoning
so, above grammar is not a ambiguous thus a definite PDA possible

Trick for this is but just deriving 3-4 strings from grammar, we 
can easily understand its (anbn)* above 
expression anbn is in CFL thus closure of DCFG is a DCFG
i.e., you can get L = {ε, ab, abab, aabb, aabbab, abaabb, 
ababab,......}
PDA will push "a" until "b" is read, start popping "a" for the "b" read.

If "a" is read again from the tape then push only when stack is empty 
else terminate.

Repeat this until string is read.

Remember fastest way to get answer is by elimination other options.
Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE-CS-2017 (Set 2) | Question 42
How to deal with warning message `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. in R while creating a histogram?

The default value for bins is 30 but if we don’t pass that in geom_histogram then the warning message is shown by R in most of the cases. To avoid that, we can simply put bins=30 inside the geom_histogram() function. This will stop showing the warning message.
Consider the below data frame −
x<-rnorm(50000,5,1)
df<-data.frame(x)
Loading ggplot2 package and creating histogram of x −
library(ggplot2) ggplot(df,aes(x))+geom_histogram() `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Creating the histogram by specifying the bins −
ggplot(df,aes(x))+geom_histogram(bins=30)
How to take user input using HTML forms?

Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.
Let’s learn about the <input> tag, which helps you to take user input using the type attribute. The attribute is used with the form elements such as text input, checkbox, radio, etc.
You can try to run the following code to take user input using HTML Forms:
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <head>
         <title>HTML Forms</title>
      </head>
      <p>Add your details:</p>
      <form>
         Student Name:<br> <input type="text" name="name">
         <br>
         Student Subject:<br> <input type="text" name="subject">
         <br>
         Rank:<br> <input type="text" name="rank">
      </form>
   </body>
</html>
Above, you can see the following two attributes:
typeIndicates the type of input control and for text input control it will be set to text
nameUsed to give a name to the control which is sent to the server to be recognized and get the value.
File Searching using C#

To search files from the list of files in a directory, try to run the following code −
using System;
using System.IO;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         //creating a DirectoryInfo object
         DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");

         // getting the files in the directory, their names and size
         FileInfo [] f = mydir.GetFiles();

         foreach (FileInfo file in f) {
            Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length);
         }
         Console.ReadKey();
      }
   }
}
Above, we have firstly added the directory wherein we want to find the files −
DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");
Then read the file −
FileInfo [] f = mydir.GetFiles();

foreach (FileInfo file in f) {
C   onsole.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length);
}
The following is the output −
FileName: Info.txt: Size: 2kb
File Name: New.html: Size: 10kb
Golang Program to count the set bits in an integer.

For example, 101, 11, 11011 and 1001001 set bits count 2, 2, 4 and 3 respectively.
Approach to solve this problem
Step 1 − Convert number into binary representation.
Step 2 − Count the number of 1s; return count.
 Live Demo
package main
import (
   "fmt"
   "strconv"
)
func NumOfSetBits(n int) int{
   count := 0
   for n !=0{
      count += n &1
      n >>= 1
   }
   return count
}
func main(){
   n := 20
   fmt.Printf("Binary representation of %d is: %s.\n", n,
   strconv.FormatInt(int64(n), 2))
   fmt.Printf("The total number of set bits in %d is %d.\n", n, NumOfSetBits(n))
}
Binary representation of 20 is: 10100.
The total number of set bits in 20 is 2.
HTML <meta> content Attribute

The content attribute of the <meta> element is used to set the meta information in an HTML document. This can be the information for the description or the keywords, for name attribute.
Following is the syntax:
<meta content="text">
Above, the text is the meta information.
Let us now see an example to implement the content attribute of the <meta> element:
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Learn for free">
</head>
<body>
<h2>Tutorials</h2>
<p>Programming tutorials for free:</p>
<ol>
   <li>Java</li>
   <li>C++</li>
   <li>C</li>
   <li>C#</li>
</ol>
</body>
</html>
In the above example, under the <head> element, we have set the <meta> description:
<head>
<meta name="description" content="Learn for free">
</head>
The description i.e. the meta information is set using the content attribute of the <meta> element:
content="Learn for free"
Java program to print a prime number

Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example −
7 = 1 × 7
Few prime number are − 1, 2, 3, 5 , 7, 11 etc.
1. Take integer variable A
2. Divide the variable A with (A-1 to 2)
3. If A is divisible by any value (A-1 to 2) it is not prime
4. Else it is prime
import java.util.Scanner;
public class PrimeNumber {
   public static void main(String args[]){
      int loop, number;
      int prime = 1;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number ::");
      number = sc.nextInt();
     
      for(loop = 2; loop < number; loop++) {
         if((number % loop) == 0) {
            prime = 0;
         }
      }
      if (prime == 1)
         System.out.println(number+" is a prime number");
      else
         System.out.println(number+" is not a prime number");
   }
}
Enter a number ::
2
2 is a prime number
How to convert an object x to a string representation in Python?

Most commonly used str() function from Python library returns a string representation of object.
>>> no=100
>>> str(no)
'100'
>>> L1=[1,2,3,4]
>>> str(L1)
'[1, 2, 3, 4]'
>>> d={'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> str(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
However, repr() returns a default and unambiguous representation of the object, where as str() gives an informal representation that may be readable but may not be always unambiguous.
>>> str(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
>>> repr(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
>>> repr(L1)
'[1, 2, 3, 4]'
>>> repr(no)
'100'
Java program to calculate the GCD of a given number using recursion

You can calculate the GCD of given two numbers, using recursion as shown in the following program.
import java.util.Scanner;
public class GCDUsingRecursion {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number :: ");
      int firstNum = sc.nextInt();
      System.out.println("Enter second number :: ");
      int secondNum = sc.nextInt();
      System.out.println("GCD of given two numbers is ::"+gcd(firstNum, secondNum));
   }

   public static int gcd(int num1, int num2) {
      if (num2 != 0){
         return gcd(num2, num1 % num2);
      } else{
         return num1;
      }
   }
}
Enter first number ::
625
Enter second number ::
125
GCD of given two numbers is ::125
How to set a proxy for wget on Linux?

Wget is a Linux command line utility that is used to retrieve files from World Wide Web(WWW) and makes use of protocols like HTTPS and FTP. It is a freely available package and can be downloaded and installed on any Linux supporting architecture.
One of the key features of wget is its ability to automatically start downloading where it was left off in case there is a network issue. It should also be noted that it deletes files recursively and it will keep trying to download all the files until it has been retrieved completely.
sudo apt-get install wget
yum install wget
Now we know about wget, let’s first explore an example where we will try to download a file from a url with the help of the wget command.
wget http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz
immukul@192 linux-code % wget http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz
--2021-07-11 12:12:20-- http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz
Resolving ftp.gnu.org (ftp.gnu.org)... 209.51.188.20
Connecting to ftp.gnu.org (ftp.gnu.org)|209.51.188.20|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 446966 (436K) [application/x-gzip]
Saving to: 'wget-1.5.3.tar.gz'

wget-1.5.3.tar.gz
100%[========================================================>]
436.49K 285KB/s in 1.5s

2021-07-11 12:12:23 (285 KB/s) - 'wget-1.5.3.tar.gz' saved [446966/446966]
Now, if we want to use a proxy with the wget command, we can make use of either of the two approaches mentioned below.
wget -e use_proxy=yes -e http_proxy=localhost:8080 ...
use_proxy=yes

http_proxy=localhost:8080

https_proxy=localhost:8080
Both the above approaches will enable you to run the wget with a proxy on.
How to filter String stream and map to lower case in Java? Perform sort as well.

Let’s say the following is String array, which we have converted to List −
Arrays.asList("DE", "GH", "JK", "MN", "PQ", "RS", "TU", "VW", "XY", "BC")
Now filter String stream and map to lower case −
.stream()
.filter(a-> a.startsWith("V"))
.map(String::toLowerCase)
To sort now, use the sorted() and display using forEach().
The following is an example to filter string stream and map to lowercase −
import java.util.Arrays;
public class Demo {
   public static void main(String[] args) throws Exception {
      Arrays.asList("DE", "GH", "JK", "MN", "PQ", "RS", "TU", "VW", "XY", "BC")
      .stream()
      .filter(a-> a.startsWith("V"))
      .map(String::toLowerCase)
      .sorted()
      .forEach(System.out::println);
   }
}
Vw
HTML <img> referrerpolicy Attribute - GeeksforGeeks

02 Mar, 2022
The HTML <img> referrerpolicy attribute is used to specify the reference information that will be sent to the server when fetching the image. 
Syntax:
<img referrerpolicy="value">  
Attribute Values : 
no-referrer: It specifies that no reference information will be sent along with a request.
no-referrer-when-downgrade: It has a default value. It specifies that refer header will not be sent to origins without HTTPS.
origin: It specifies to send the origin of the document as the referrer in all cases.
origin-when-cross-origin: It sends the origin, path, and query string when performing a same-origin request, but only send the origin of the document for other cases.
unsafe-url: It sends origin. path and query string but not include fragment, password and username.
Example: Below code illustrates the use of <img> referrer policy attribute. 
HTML
<!DOCTYPE html><html> <body>    <h1>GeeksforGeeks</h1>     <h2>        HTML img referrerpolicy Attribute    </h2>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"        alt="GeeksforGeeks logo" referrerpolicy="no-referrer"     ></body> </html>
Output:
Supported Browsers:
Google Chrome 53.0
Internet Explorer Not Supported
Firefox 50.0
Safari 14.0
Opera 40.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
SOAP - Fault

If an error occurs during processing, the response to a SOAP message is a SOAP fault element in the body of the message, and the fault is returned to the sender of the SOAP message.
The SOAP fault mechanism returns specific information about the error, including a predefined code, a description, and the address of the SOAP processor that generated the fault.
A SOAP message can carry only one fault block.
A SOAP message can carry only one fault block.
Fault is an optional part of a SOAP message.
Fault is an optional part of a SOAP message.
For HTTP binding, a successful response is linked to the 200 to 299 range of status codes.
For HTTP binding, a successful response is linked to the 200 to 299 range of status codes.
SOAP Fault is linked to the 500 to 599 range of status codes.
SOAP Fault is linked to the 500 to 599 range of status codes.
The SOAP Fault has the following sub elements −
<faultCode>
It is a text code used to indicate a class of errors. See the next Table for a listing of predefined fault codes.
<faultString>
It is a text message explaining the error.
<faultActor>
It is a text string indicating who caused the fault. It is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needs to know which node caused the error. A node that does not act as the ultimate destination must include a faultActor element.
<detail>
It is an element used to carry application-specific error messages. The detail element can contain child elements called detail entries.
The faultCode values defined below must be used in the faultcode element while describing faults.
SOAP-ENV:VersionMismatch
Found an invalid namespace for the SOAP Envelope element.
SOAP-ENV:MustUnderstand
An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood.
SOAP-ENV:Client
The message was incorrectly formed or contained incorrect information.
SOAP-ENV:Server
There was a problem with the server, so the message could not proceed.
The following code is a sample Fault. The client has requested a method named ValidateCreditCard, but the service does not support such a method. This represents a client request error, and the server returns the following SOAP response −
<?xml version = '1.0' encoding = 'UTF-8'?>
<SOAP-ENV:Envelope
   xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance"
   xmlns:xsd = "http://www.w3.org/1999/XMLSchema">

   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode xsi:type = "xsd:string">SOAP-ENV:Client</faultcode>
         <faultstring xsi:type = "xsd:string">
            Failed to locate method (ValidateCreditCard) in class (examplesCreditCard) at
               /usr/local/ActivePerl-5.6/lib/site_perl/5.6.0/SOAP/Lite.pm line 1555.
         </faultstring>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

    8 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Difference between Inter and Intra Frame Compression - GeeksforGeeks

24 Nov, 2021
In Compression, we reduce the size of our data to achieve high efficiency and easy storage. It is quite cumbersome to transfer files having large size so we need to compress it. Compressed file takes less time for data transmission and reduce the cost of storage. 
Compression Ratio = B1 / B2 
where, B1 = Total Numbers of bits required to represent data before compression B2 = Total Numbers of bits required to represent data after compression 
There are 2 main types of compression:  
Inter Frame Compression Intra Frame Compression 
Inter Frame Compression 
Intra Frame Compression 
Difference between Inter and Intra Frame Compression : 
Inter Frame Compression
Intra Frame Compression
A few popular inter frame codec are: 
H.264-A variant of MPEG-4MPEG-4MPEG-2AVCHD-A variant of H.264 AVCXDCAM-Sony’s babyXAVC-Sony’s new baby
H.264-A variant of MPEG-4
MPEG-4
MPEG-2
AVCHD-A variant of H.264 AVC
XDCAM-Sony’s baby
XAVC-Sony’s new baby
A few popular intra frame codec are:  
MJPEG-JPEGS bunched togetherProres-Apple’s favoriteDN*HD-Avid’s babyALL-I-Found in the newer DSLRsCinema DNG-Adobe’s baby for raw image sequences.  
MJPEG-JPEGS bunched together
Prores-Apple’s favorite
DN*HD-Avid’s baby
ALL-I-Found in the newer DSLRs
Cinema DNG-Adobe’s baby for raw image sequences.  
 
mikeyj125
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
GSM in Wireless Communication
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Multiple Access Protocols in Computer Network
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing
Stack vs Heap Memory Allocation
Assigning multiple characters in an int in C language - GeeksforGeeks

30 Apr, 2018
Consider the following C program.
#include <stdio.h>int main(void){    int a = 'd';      printf("%d\n", a);    /*OUTPUT - 100 (ASCII Code for character d)*/      int b = 'dd';    printf("%d", b);    /*OUTPUT - 25700 (Explanation in detail given below)*/      return 0;}
Output :
100
25700

We can easily guess that the output for ‘d’ is 100 as 100 is ASCII value of character ‘d’.
Let us consider below line
int a = 'dd' 
(%d, a) prints 25700 as output01100100 01100100 (Binary of 100 100)Assuming int is of 2 bytes, starting byte is occupied by first character ‘d’ and second byte by second character ‘d’. Therefore overall binary involves 0110010001100100 i.e 2^14 + 2^13 + 2^10 + 2^6 + 2^5 + 2^2 = 25700.
Now guess the output of following code.
#include <stdio.h>int main(void){    int b = 'de';    printf("%d", b);    return 0;}
C Language
Program Output
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Arrow operator -> in C/C++ with Examples
delete keyword in C++
Output of C Programs | Set 1
Output of Java Program | Set 1
Different ways to copy a string in C/C++
XQuery - concat Function

The concat function is used to concatenate various strings.
concat($input as xs:anyAtomicType?) as xs:string
$input − one or more inputs separated by comma.
$input − one or more inputs separated by comma.
let $bookTitle := "Learn XQuery in 24 hours"
let $updatedTitle := concat($bookTitle,",price: 200$")

return
   <result>   
      <title>{$updatedTitle}</title>
   </result>
<result>
   <title>Learn XQuery in 24 hours,price: 200$</title>
</result>

In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result.
 Print
 Add Notes
 Bookmark this page
PostgreSQL - UPDATE Query

The PostgreSQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update the selected rows. Otherwise, all the rows would be updated.
The basic syntax of UPDATE query with WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

You can combine N number of conditions using AND or OR operators.
Consider the table COMPANY, having records as follows −
testdb# select * from COMPANY;
 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)
The following is an example, which would update ADDRESS for a customer, whose ID is 6 −
testdb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3;
Now, COMPANY table would have the following records −
 id | name  | age | address    | salary
----+-------+-----+------------+--------
  1 | Paul  |  32 | California |  20000
  2 | Allen |  25 | Texas      |  15000
  4 | Mark  |  25 | Rich-Mond  |  65000
  5 | David |  27 | Texas      |  85000
  6 | Kim   |  22 | South-Hall |  45000
  7 | James |  24 | Houston    |  10000
  3 | Teddy |  23 | Norway     |  15000
(7 rows)
If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not need to use WHERE clause and UPDATE query would be as follows −
testdb=# UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000;
Now, COMPANY table will have the following records −
 id | name  | age | address | salary
----+-------+-----+---------+--------
  1 | Paul  |  32 | Texas   |  20000
  2 | Allen |  25 | Texas   |  20000
  4 | Mark  |  25 | Texas   |  20000
  5 | David |  27 | Texas   |  20000
  6 | Kim   |  22 | Texas   |  20000
  7 | James |  24 | Texas   |  20000
  3 | Teddy |  23 | Texas   |  20000
(7 rows)

    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
R - If...Else Statement

An if statement can be followed by an optional else statement which executes when the boolean expression is false.
The basic syntax for creating an if...else statement in R is −
if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true.
} else {
   // statement(s) will execute if the boolean expression is false.
}

If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed.
x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found")
} else {
   print("Truth is not found")
}
When the above code is compiled and executed, it produces the following result −
[1] "Truth is not found"

Here "Truth" and "truth" are two different strings.
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if, else if, else statements there are few points to keep in mind.
An if can have zero or one else and it must come after any else if's.
An if can have zero or one else and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
The basic syntax for creating an if...else if...else statement in R is −
if(boolean_expression 1) {
   // Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
   // Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
   // Executes when the boolean expression 3 is true.
} else {
   // executes when none of the above condition is true.
}

x <- c("what","is","truth")

if("Truth" %in% x) {
   print("Truth is found the first time")
} else if ("truth" %in% x) {
   print("truth is found the second time")
} else {
   print("No truth found")
}
When the above code is compiled and executed, it produces the following result −
[1] "truth is found the second time"


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
java.lang.reflect.Method Class in Java

10 Mar, 2021
java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method).
This class allows broadening of conversions to occur when matching the actual parameters to call the underlying method’s formal parameters, but if narrowing conversion would occur, it throws an IllegalArgumentException.
java.lang.Object
            java.lang.reflect.AccessibleObject
                        java.lang.reflect.Executable
                                    java.lang.reflect.Method
Methods:
getDefaultValue() Method:
Java
// Java program to show the// Implementation of getDefaultvalue()  import java.lang.reflect.Method;  public class getDefaultValueExample {      public static void main(String[] args)    {          Method[] methods = Demo.class.getMethods();          // calling method getDefaultValue()        System.out.println(methods[0].getDefaultValue());    }}  class Demo {    private String str;      // member function returning string str    public String getSampleField() { return str; }      public void setSampleField(String str)    {        this.str = str;    }}
null
toString() Method:
Java
// Java program to show the// Implementation of toString()  import java.lang.reflect.Method;  public class MethodDemo {    public static void main(String[] args)    {          Method[] methods = SampleClass.class.getMethods();          // calling method toString()        System.out.println(methods[1].toString());    }}  class SampleClass {    private String str;      public String getSampleField() { return str; }      public void setSampleField(String str)    {        this.str = str;    }}
public void SampleClass.setSampleField(java.lang.String)
java-lang-reflect-package
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Generate five random numbers from the normal distribution using NumPy

29 Aug, 2020
In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distribution. This distribution is also called the Bell Curve this is because of its characteristics shape.
To generate five random numbers from the normal distribution we will use numpy.random.normal() method of the random module.  
Syntax: numpy.random.normal(loc = 0.0, scale = 1.0, size = None) 
Parameters:
loc: Mean of distribution
scale: Standard derivation 
size: Resultant shape.If size argument is empty then by default single value is returned.
Example 1:
Python3
# importing moduleimport numpy as np    # numpy.random.normal() methodr = np.random.normal(size=5)  # printing numbersprint(r)
Output :
[ 0.27491897 -0.18001994 -0.01783066  1.07701319 -0.11356911]

Example 2:
Python3
# importing moduleimport numpy as np    # numpy.random.normal() methodrandom_array = np.random.normal(0.0, 1.0, 5)  # printing 1D array with random numbersprint("1D Array with random values : \n", random_array)
Output :
1D Array with random values :
[ 0.14559212  1.97263406  1.11170937 -0.88192442  0.8249291 ]

Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list