code-rag-bench/online-tutorials huggingface dataset:
Get the duplicate values of a field in MongoDB?

Use aggregate() method to get the duplicate value of a field. Let us first create a collection with documents using the following query
> db.findAllNonDistinctDemo.insertOne({"UserName":"John","UserAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c995078863d6ffd454bb647")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Larry","UserAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c995081863d6ffd454bb648")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Larry","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c995089863d6ffd454bb649")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"David","UserAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c995093863d6ffd454bb64a")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"John","UserAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c99509d863d6ffd454bb64b")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Robert","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9950a7863d6ffd454bb64c")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Robert","UserAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9950b1863d6ffd454bb64d")
}
> db.findAllNonDistinctDemo.insertOne({"UserName":"Mike","UserAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9950bc863d6ffd454bb64e")
}
Following is the query to display all documents from a collection with the help of find() method
> db.findAllNonDistinctDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c995078863d6ffd454bb647"),
   "UserName" : "John",
   "UserAge" : 28
}
{
   "_id" : ObjectId("5c995081863d6ffd454bb648"),
   "UserName" : "Larry",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c995089863d6ffd454bb649"),
   "UserName" : "Larry",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c995093863d6ffd454bb64a"),
   "UserName" : "David",
   "UserAge" : 22
}
{
   "_id" : ObjectId("5c99509d863d6ffd454bb64b"),
   "UserName" : "John",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5c9950a7863d6ffd454bb64c"),
   "UserName" : "Robert",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c9950b1863d6ffd454bb64d"),
   "UserName" : "Robert",
   "UserAge" : 25
}
{
   "_id" : ObjectId("5c9950bc863d6ffd454bb64e"),
   "UserName" : "Mike",
   "UserAge" : 29
}
Following is the query to find all the duplicate values of a field in MongoDB
> db.findAllNonDistinctDemo.aggregate([
...    { "$group": {
...       "_id": "$UserName",
...       "Counter": { "$sum": 1 }
...    }},
...    { "$match": {
...       "Counter": { "$gt": 1 }
...    }}
... ]).pretty();
This will produce the following output. All the duplicate records are visible now
{ "_id" : "Robert", "Counter" : 2 }
{ "_id" : "Larry", "Counter" : 2 }
{ "_id" : "John", "Counter" : 2 }
Find Median from Data Stream in C++

Suppose we have a data stream, in that stream some data element may come and join, we have to make one system, that will help to find the median from the data. As we know that the median is the middle data of a sorted list, if it list length is odd, we can get the median directly, otherwise take middle two elements, then find the average. So there will be two methods, addNum() and findMedian(), these two methods will be used to add numbers into the stream, and find the median of all added numbers
To solve this, we will follow these steps −
Define priority queue left and right
Define priority queue left and right
Define addNum method, this will take the number as input −
Define addNum method, this will take the number as input −
if left is empty or num < top element of left, then,insert num into left
if left is empty or num < top element of left, then,
insert num into left
insert num into left
Otherwiseinsert num into right
Otherwise
insert num into right
insert num into right
if size of left < size of right, then,temp := top element of rightdelete item from rightinsert temp into left
if size of left < size of right, then,
temp := top element of right
temp := top element of right
delete item from right
delete item from right
insert temp into left
insert temp into left
if size of left – size of right > 1, then,temp := top element of leftdelete item from leftinsert temp into right
if size of left – size of right > 1, then,
temp := top element of left
temp := top element of left
delete item from left
delete item from left
insert temp into right
insert temp into right
Define findMedian() method, this will act as follows −return top of left if size of left > size of right, else (top of left + top of right)/2
Define findMedian() method, this will act as follows −
return top of left if size of left > size of right, else (top of left + top of right)/2
return top of left if size of left > size of right, else (top of left + top of right)/2
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef double lli;
class MedianFinder {
   priority_queue <int> left;
   priority_queue <int, vector <int>, greater<int>> right;
   public:
   void addNum(int num) {
      if(left.empty() || num<left.top()){
         left.push(num);
      }else right.push(num);
      if(left.size()<right.size()){
         lli temp = right.top();
         right.pop();
         left.push(temp);
      }
      if(left.size()-right.size()>1){
         lli temp = left.top();
         left.pop();
         right.push(temp);
      }
   }
   double findMedian() {
      return
      left.size()>right.size()?left.top():(left.top()+right.top())*0.5;
   }
};
main(){
   MedianFinder ob;
   ob.addNum(10);
   ob.addNum(15);
   cout << ob.findMedian() << endl;
   ob.addNum(25);
   ob.addNum(30);
   cout << ob.findMedian() << endl;
   ob.addNum(40);
   cout << ob.findMedian();
}
addNum(10);
addNum(15);
findMedian();
addNum(25);
addNum(30);
findMedian();
addNum(40);
findMedian();
12.5
20
25
PHP Resources

In PHP, Resource  is a special data type that refers to any external resource. A resource variable acts as a reference to external source of data such as stream, file, database etc. PHP uses relevent functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable.
PHP's Zend engine uses reference conting system. As a result, a resource with zero reference count is destroyed automatically by garbage collector. Hence, memory used by resource data type need not be freed manually.
Various types of resources can be handled in a PHP script, with the help of coresponding functions. Following table shows a select list −
In this context, PHP has get_resource_type() function that returns resource type of a variable.
To declare an object of a class we need to use new statement
get_resource_type ( resource $handle ) : string
where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type
Following example shows resource type of a disk file
 Live Demo
<?php
$fp=fopen("test.txt","w");
var_dump($fp);
?>
This will produce following result −
resource(5) of type (stream)
Following example uses get_resource_type() function
 Live Demo
<?php
$fp = fopen("test.txt", "w");
echo get_resource_type($fp) . "\n";
?>
This will produce following result −
stream
How to get Response Status Code with Selenium WebDriver?

We can get the Response status code with Selenium webdriver. While executing a test, we can verify the Response code obtained from a server. Some common HTTP Response codes are listed below −
5XX means there is an issue on the server.
5XX means there is an issue on the server.
4XX means that the server resource cannot be identified.
4XX means that the server resource cannot be identified.
3XX means the request has been redirected.
3XX means the request has been redirected.
2XX means the request executed successfully.
2XX means the request executed successfully.
An instance of the class HttpURLConnection is created to obtain the HTTP Response. To have a link to an URL, the method openConnection method is used. Then we have to use the method setRequestMethod and pass HEAD as a parameter.
To have a connection, the method connect should be applied to an object of the class HttpURLConnection. Finally, the method getResponseCode gives the Response code.
HttpURLConnection cont=
(HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm").
.openConnection();
cont.setRequestMethod("HEAD");
cont.connect();
int res = cont.getResponseCode();
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpResponseStatus{
   public static void main(String[] args) throws
   MalformedURLException, IOException {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      //url launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //URL connection
      HttpURLConnection cont=
      (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm")
      .openConnection();
      // pass HEAD as parameter to setRequestMethod
      cont.setRequestMethod("HEAD");
      // obtain Response code
      cont.connect();
      int rs = cont.getResponseCode();
      System.out.println("Http response code: " + rs);
      //driver quit
      driver.quit();
   }
}
Convert array into array of subarrays - JavaScript

We are required to write a JavaScript function that takes in an array of literals and returns a new array that have elements of the original array chunked into subarrays of length exactly 2.
Now if the length of original array is not exactly divisible by 2, then the last subarray should have only one element.
For example,
If the input array is −
const arr = [1, 2, 3, 4, 5, 6, 7];
Then the output should be −
const output = [[1, 2], [3, 4], [5, 6], [7]]
Following is the code −
const arr = [1, 2, 3, 4, 5, 6, 7];
const chunk = arr => {
   const size = 2;
   const chunkedArray = [];
   for (let i = 0; i < arr.length; i++) {
      const last = chunkedArray[chunkedArray.length - 1];
      if(!last || last.length === size){
         chunkedArray.push([arr[i]]);
      }else{
         last.push(arr[i]);
      }
   };
   return chunkedArray;
};
console.log(chunk(arr));
This will produce the following output on console −
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
Print Words Vertically in Python

Suppose we have a string s. We have to find all the words vertically in the same order in which they appear in s. Here words are returned as a list of strings, we have to complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. So if the input string is “HOW ARE YOU”, then the output will be [“HAY”, “ORO”, “WEU”]
To solve this, we will follow these steps −
s := make a list of strings split by the spaces, make one empty array x, set row = 0
s := make a list of strings split by the spaces, make one empty array x, set row = 0
for each word I in s, set row := max of row and length of i
for each word I in s, set row := max of row and length of i
col := length of s
col := length of s
make one array and filled with empty string, and its size is the row
make one array and filled with empty string, and its size is the row
for I in range 0 to col – 1j := 0while j < length of s[i]while i – length of ans[j] >= 1, do ans[j] := ans[j] concatenate “ ”ans[j] := ans[j] concatenate s[i, j]increase j by 1
for I in range 0 to col – 1
j := 0
j := 0
while j < length of s[i]while i – length of ans[j] >= 1, do ans[j] := ans[j] concatenate “ ”ans[j] := ans[j] concatenate s[i, j]increase j by 1
while j < length of s[i]
while i – length of ans[j] >= 1, do ans[j] := ans[j] concatenate “ ”
while i – length of ans[j] >= 1, do ans[j] := ans[j] concatenate “ ”
ans[j] := ans[j] concatenate s[i, j]
ans[j] := ans[j] concatenate s[i, j]
increase j by 1
increase j by 1
return ans
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def printVertically(self, s):
      s = s.split(" ")
      x = []
      row = 0
      for i in s:
         row = max(row, len(i))
      col = len(s)
      ans = ["" for i in range(row)]
      j = 0
      for i in range(col):
         j = 0
         while j < len(s[i]):
            #print(j, i)
            while i - len(ans[j]) >= 1:
               ans[j] += " "
            ans[j] += s[i][j]
            j += 1
      return ans
ob = Solution()
print(ob.printVertically("HOW ARE YOU"))
print(ob.printVertically("TO BE OR NOT TO BE"))
"HOW ARE YOU"
"TO BE OR NOT TO BE"
["HAY","ORO","WEU"]
["TBONTB","OEROOE"," T"]
C# Inheritance

In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories:
Derived Class (child) - the class that inherits from another class
Base Class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class 
(child) inherits the fields and methods from the Vehicle class 
(parent):
class Vehicle  // base class (parent) 
{
  public string brand = "Ford";  // Vehicle field
  public void honk()             // Vehicle method 
  {                    
    Console.WriteLine("Tuut, tuut!");
  }
}

class Car : Vehicle  // derived class (child)
{
  public string modelName = "Mustang";  // Car field
}

class Program
{
  static void Main(string[] args)
  {
    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (From the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
    Console.WriteLine(myCar.brand + " " + myCar.modelName);
  }
}
 


Run example »

- It is useful for code reusability: reuse fields and methods of an existing class when you create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different tasks.
If you don't want other classes to inherit from a class, use the sealed keyword:
If you try to access a sealed class, C# will generate an error:
sealed class Vehicle 
{
  ...
}

class Car : Vehicle 
{
  ...
}

The error message will be something like this:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to display count on Y-axis for line chart using ggplot2 in R?

To display count on Y-axis for line chart using ggplot2 in R, we can follow the below steps −
First of all, create a data frame.
First of all, create a data frame.
Then, create the line chart using geom_line function of ggplot2 package with fill argument counting the values using count function and binwidth set to 1.
Then, create the line chart using geom_line function of ggplot2 package with fill argument counting the values using count function and binwidth set to 1.
Let’s create a data frame as shown below −
 Live Demo
x<-sample(1:10,200,replace=TRUE)
df<-data.frame(x)
head(df,25)
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
  x
1 6
2 5
3 4
4 3
5 2
6 6
7 7
8 4
9 5
10 5
11 1
12 2
13 10
14 7
15 7
16 8
17 3
18 8
19 3
20 1
21 8
22 9
23 5
24 6
25 5
Loading ggplot2 package and using fill=..count.. inside aes of geom_line along with
binwidth of 1 to create the line chart count on Y-axis −
x<-sample(1:10,200,replace=TRUE)
df<-data.frame(x)
library(ggplot2)
ggplot(df,aes(x))+geom_line(aes(fill=..count..),stat="bin",binwidth=1)
Warning message:
Ignoring unknown aesthetics: fill
How to extract the factor levels from factor column in an R data frame?

To extract the factor levels from factor column, we can simply use levels function. For example, if we have a data frame called df that contains a factor column defined with x then the levels of factor levels in x can be extracted by using the command levels(df$x). This extraction is helpful if we have a large number of levels.
 Live Demo
Consider the below data frame −
x1<−factor(sample(letters[1:3],20,replace=TRUE))
y1<−rnorm(20,5,0.31)
df1<−data.frame(x1,y1)
df1
x1 y1
1 a 4.480255
2 b 4.865971
3 a 5.278760
4 a 5.208462
5 c 4.815111
6 a 5.116731
7 a 5.278687
8 b 5.832620
9 c 5.182383
10 a 4.741525
11 b 4.645954
12 c 4.972552
13 a 5.515956
14 c 4.951365
15 b 5.214277
16 c 5.444890
17 b 4.590310
18 a 4.949908
19 a 4.858476
20 c 5.179366
Extracting factor levels of x1 −
levels(df1$x1)
[1] "a" "b" "c"
 Live Demo
If the column values are not recorded as factor level but they represent them then we need to use as.factor with the column as shown in the below example −
x2<−sample(c("Hot","Cold","Warm"),20,replace=TRUE)
y2<−rpois(20,30)
df2<−data.frame(x2,y2)
df2
x2 y2
1 Warm 29
2 Hot 23
3 Cold 26
4 Hot 30
5 Hot 36
6 Hot 25
7 Hot 34
8 Hot 24
9 Warm 29
10 Hot 34
11 Warm 25
12 Cold 26
13 Hot 30
14 Cold 31
15 Warm 28
16 Cold 25
17 Cold 32
18 Hot 25
19 Hot 32
20 Cold 28
levels(df2$x2)
NULL
levels(factor(df2$x2))
[1] "Cold" "Hot" "Warm"
Complex numbers in C++ programming

In this section we will see how to create and use complex numbers in C++. We can create complex number class in C++, that can hold the real and imaginary part of the complex number as member elements. There will be some member functions that are used to handle this class.
In this example we are creating one complex type class, a function to display the complex number into correct format. Two additional methods to add and subtract two complex numbers etc.
 Live Demo
#include<iostream>
using namespace std;
class complex{
   int real, img;
   public:
      complex(){
         //default constructor to initialize complex number to 0+0i
         real = 0; img = 0;
      }
      complex(int r, int i){
         //parameterized constructor to initialize complex number.
         real = r; img = i;
      }
      void set();
      void get();
      void display();
      friend complex add(complex, complex);
      friend complex sub(complex, complex);
};
void complex::set(){
   cout << "Enter Real part: ";
   cin >> real;
   cout << "Enter Imaginary Part: ";
   cin >> img;
}
void complex::get(){
   cout << "The complex number is: "<< real << "+" << img << "i" << endl;
}
void complex::display(){
   if(img < 0)
   if(img == -1)
      cout << "The complex number is: "<< real << "-i" << endl;
   else
      cout << "The complex number is: "<< real << img << "i" << endl;
   else
   if(img == 1)
      cout << "The complex number is: "<< real << " + i"<< endl;
   else
   cout << "The complex number is: "<< real << " + " << img << "i" << endl;
}
complex add(complex c1, complex c2){
   complex res;
   res.real = c1.real + c2.real;//addition for real part
   res.img = c1.img + c2.img;//addition for imaginary part
   return res;//the result after addition
}
complex sub(complex c1, complex c2){
   complex res;
   res.real = c1.real - c2.real;//subtraction for real part
   res.img = c1.img - c2.img;//subtraction for imaginary part
   return res;//the result after subtraction
}
main(){
   complex n1(3, 2), n2(4, -3);
   complex result;
   result = add(n1,n2);
   result.display();
   result = sub(n1,n2);
   result.display();
}
The complex number is: 7-i
The complex number is: -1 + 5i
How to plot masked and NaN values in Matplotlib?

To plot masked and NaN values in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Get x2 and y2 data points such that y > 0.7.
Get masked y3 data points such that y > 0.7.
Mask y3 with NaN values.
Plot x, y, y2, y3 and y4 using plot() method.
Place a legend to the plot.
Set the title of the plot.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

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

x = np.linspace(-np.pi/2, np.pi/2, 31)
y = np.cos(x)**3

# 1) remove points where y > 0.7
x2 = x[y <= 0.7]
y2 = y[y <= 0.7]

# 2) mask points where y > 0.7
y3 = np.ma.masked_where(y > 0.7, y)

# 3) set to NaN where y > 0.7
y4 = y.copy()
y4[y3 > 0.7] = np.nan

plt.plot(x*0.1, y, 'o-', color='lightgrey', label='No mask')
plt.plot(x2*0.4, y2, 'o-', label='Points removed')
plt.plot(x*0.7, y3, 'o-', label='Masked values')
plt.plot(x*1.0, y4, 'o-', label='NaN values')
plt.legend()

plt.title('Masked and NaN data')

plt.show()
How to get the value of the form in Angular ? - GeeksforGeeks

24 May, 2021
In this article, we are going to see how to get value from the form in Angular 10. We will use AbstractControl value property to get the form value in an object.
Syntax:
form.value
Return Value:
object: It is an object containing form value
Approach: 
Create the Angular app to be used
In app.component.html make a form using ngForm directive.
Now get the value using AbstractControl value property
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { NgModule } from '@angular/core';  // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';      import { AppComponent }   from './app.component';   @NgModule({  bootstrap: [    AppComponent  ],  declarations: [    AppComponent  ],  imports: [    FormsModule,    BrowserModule,    BrowserAnimationsModule,        ]})export class AppModule { }
app.component.html
<form #gfg = "ngForm">          <br>    <br>    Name: <input type="text" name = 'name' ngModel>    Date: <input type="date" name = 'date' ngModel></form>{{ gfg.value | json }}
Output:
Reference: https://angular.io/api/forms/AbstractControlDirective#value
Angular10
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
GATE | GATE CS 2019 | Question 32 - GeeksforGeeks

15 Feb, 2019
Consider three concurrent processes P1, P2 and P3 as shown below, which access a shared variable D that has been initialized to 100.The process are executed on a uniprocessor system running a time-shared operating system. If the minimum and maximum possible values of D after the three processes have completed execution are X and Y respectively, then the value of Y–X is __________.
Note: This was Numerical Type question.(A) 80(B) 130(C) 50(D) None of theseAnswer: (A)Explanation: Minimum value (X) of D will possible when,
P2 reads D=100, preempted.P1 executes D=D+20, D=120.P3 executes D=D+10, D=130.Now, P2 has D=100, executes, D = D-50 = 100-50 = 50. P2 writes D=50 final value.
P2 reads D=100, preempted.
P1 executes D=D+20, D=120.
P3 executes D=D+10, D=130.
Now, P2 has D=100, executes, D = D-50 = 100-50 = 50. P2 writes D=50 final value.
So, minimum value (X) of D is 50.
Maximum value (Y) of D will possible when,
P1 reads D=100, preempted.P2 reads D=100, executes, D = D-50 = 100-50 = 50.Now, P1 executes, D = D+20 = 100+20 = 120.And now, P3 reads D=120, executes D=D+10, D=130. P3 writes D=130 final value.
P1 reads D=100, preempted.
P2 reads D=100, executes, D = D-50 = 100-50 = 50.
Now, P1 executes, D = D+20 = 100+20 = 120.
And now, P3 reads D=120, executes D=D+10, D=130. P3 writes D=130 final value.
So, maximum value (Y) of D is 130.
Therefore,
= Y - X
= 130 - 50
= 80 
So, option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Java Output | Practice | GeeksforGeeks

Popular Company Tags

Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs
show more


Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs


Popular Topic Tags

Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph
show more


Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph


'Easy' level Subjective Problems 

							This Question's [Answers : 3] [Views : 2009]
						


'Easy' level Subjective Problems 

							This Question's [Answers : 3] [Views : 2009]
						
class A {
   int a = 1;
   static class B {
      printA() {
         System.out.println(“a: “+a);
      }
    }
}

What will be output of above java program?
Error
Content Related Issue
Sofware Related Issue
How to update data in a MySQL database without removing the old data?

For this, you can use UPDATE and concatenate the new data with the old one to save the old data as well −
update yourTableName set yourColumnName=concat(yourColumnName,",yourValue");
Let us first create a table −
mysql> create table DemoTable
-> (
-> CustomerName varchar(100)
-> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| CustomerName |
+--------------+
| Chris        |
| David        |
| Sam          |
+--------------+
3 rows in set (0.00 sec)
Following is the query to update new data in the database without removing old data −
mysql> update DemoTable set CustomerName=concat(CustomerName,",Brown");
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| CustomerName |
+--------------+
| Chris,Brown  |
| David,Brown  |
| Sam,Brown    |
+--------------+
3 rows in set (0.00 sec)
How to compare two Dates in C#?

To compare dates in C#, you need to first set two dates to be compared using the DateTime object. We will use the DateTime class in C# −
DateTime date1 = new DateTime(2018, 08, 05);
Console.WriteLine("Date 1 : {0}", date1);
DateTime date2 = new DateTime(2018, 08, 07);
Console.WriteLine("Date 2 : {0}", date2);
Now let us compare both the dates in C#. The following is an example to compare dates in C# −
using System;
namespace Program {
   class Demo {
      static int Main() {
         DateTime date1 = new DateTime(2018, 08, 05);
         Console.WriteLine("Date 1 : {0}", date1);

         DateTime date2 = new DateTime(2018, 08, 07);
         Console.WriteLine("Date 2 : {0}", date2);
         if (date1 < date2)
         Console.WriteLine("{0} comes before {1}", date1, date2);
         Console.Read();
         return 0;
      }
   }
}
HiddenEye - Modern Phishing Tool With Advanced Functionality - GeeksforGeeks

19 Nov, 2021
A phishing attack is the most executed attack in the real world. Phishing is a social-engineering attack in which a victim is being tricked and the sensitive data is being captured by the attacker. A genuine website is being cloned and assumed that the cloned website is genuine. There are various techniques to make a phishing page. HiddenEye is an automated tool that is the best in the category of Phishing. HiddenEye tool is developed in the Python Language, available on the GitHub platform, it’s free and open-source to use. HiddenEye tool supports Facebook, Instagram, Twitter, etc social platforms.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/DarkSecDevelopers/HiddenEye-Legacy.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd HiddenEye-Legacy/
Step 3: You are in the directory of the Brutespray. Now you have to install a dependency of the Brutespray using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 HiddenEye.py  -h
Example: Creating Facebook Phishing Page
In this example, we will be creating a Facebook Phishing page. We have selected Option 1 for Facebook.
In the below screenshot, we have selected the standard page which will be the homepage of Facebook.com
In the below screenshot, we will be creating a fake cloud flare redirection page.
We have entered the custom redirect URL.
In the below screenshot, we have specified the port number on which the URL will be hosted.
We have selected the Server on which the Phishing page will be hosted.
We will be vising the highlighted link, which is the Phishing page for Facebook.
In the below screenshot, we have created a phishing page, now if any victim enters the credentials, we will get the credentials on the terminal itself.
We have got the credentials on the terminal itself.
rajeev0719singh
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
'crontab' in Linux with Examples
Batch Script - Renaming Files

For renaming files, Batch Script provides the REN or RENAME command.
RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]

Let’s take a look at some examples of renaming files.
rename *.txt *.bak

The above command will rename all text files to files with .bak extension.
rename "TESTA.txt" "TESTB.txt"

The above command will rename the file TESTA.txt to TESTB.txt.
 Print
 Add Notes
 Bookmark this page
Python Number tan() Method

Python number method tan() returns the tangent of x radians.
Following is the syntax for tan() method −
tan(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the tangent of the parameter x.
The following example shows the usage of tan() method.
#!/usr/bin/python
import math

print "tan(3) : ",  math.tan(3)
print "tan(-3) : ",  math.tan(-3)
print "tan(0) : ",  math.tan(0)
print "tan(math.pi) : ",  math.tan(math.pi)
print "tan(math.pi/2) : ",  math.tan(math.pi/2)
print "tan(math.pi/4) : ",  math.tan(math.pi/4)
When we run above program, it produces following result −
tan(3) :  -0.142546543074
tan(-3) :  0.142546543074
tan(0) :  0.0
tan(math.pi) :  -1.22460635382e-16
tan(math.pi/2) :  1.63317787284e+16
tan(math.pi/4) :  1.0


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Compare tuples in Python

When it is required to compare tuples, the '<', '>', and '==' operators can be used.
it returns True or False depending on whether the tuples are equal to each other, less than or greater than one another.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = (87, 90, 31, 85)
my_tuple_2 = (34, 56, 12, 5)

print("The first tuple is :")
print(my_tuple_1)
print("The second tuple is :")
print(my_tuple_2)
print("Comparing the two tuples")
print(my_tuple_1< my_tuple_2)
print(my_tuple_1==my_tuple_2)
print(my_tuple_2 > my_tuple_1)
The first tuple is :
(87, 90, 31, 85)
The second tuple is :
(34, 56, 12, 5)
Comparing the two tuples
False
False
False
Two tuples are defined, and are displayed on the console.
They are compared using the '<', '>', and '==' operator.
It is displayed as output on the console.
Java String Comparison Methods.

Java String class provides different comparison methods namely:
This method compares two Strings lexicographically. This method returns  a negative integer if current String object lexicographically precedes the argument string.  a positive integer if current String object lexicographically follows the argument  true when the strings are equal.
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "point";
      // comparing str1 and str2
      int retval = str1.compareTo(str2);
      // prints the return value of the comparison
      if (retval < 0) {
         System.out.println("str1 is greater than str2");
      }
      else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}
str1 is less than str2
This method is same as compareTo() method, it compares two strings lexicographically, ignoring case differences.
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "TUTORIALS";
     
      // comparing str1 and str2 with case ignored
      int retval = str1.compareToIgnoreCase(str2);
     
      // prints the return value of the comparison
      if (retval > 0) {
         System.out.println("str1 is greater than str2");
     }
     else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}
str1 is equal to str2
This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "amrood admin";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}
str2 is equal to str1 = false
str2 is equal to str3 = true
This method is equal to the ignoreCase() method, except Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "AMROOD ADMIN";
     
      // checking for equality with case ignored
      boolean retval1 = str2.equalsIgnoreCase(str1);
      boolean retval2 = str2.equalsIgnoreCase(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}
str2 is equal to str1 = false
str2 is equal to str3 = true
std::basic_string::max_size in C++ - GeeksforGeeks

12 Jun, 2019
std::basic_string::max_size is used to compute the maximum number of elements the string is able to hold due to system or library implementation limitations.
size_type max_size() const;
Parameters : None
Return value : Maximum number of characters
Exceptions : None
// CPP program to compute the limit of a string// using max_size#include <iostream>#include <string>  int main(){    std::string str;          // Calling max_size()    std::cout << "Maximum size of a string is " << str.max_size() << std :: endl;} 
Output:
Maximum size of a string is 4294967294

Note : The maximum size can depend on the compiler and system.
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
cpp-string
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Iterators in C++ STL
Convert string to char array in C++
Inline Functions in C++
Multithreading in C++
List in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory
Insert a specified HTML text into a specified position in the JavaScript document?

Javascript has provided insertAdjacentHTML() method to insert a text as HTML, into a specified position. Those legal positions are 
afterbegin
afterbegin
afterend
afterend
beforebegin
beforebegin
beforeend
beforeend
Each legal position has its own unique importance. Let's discuss some of them.
In the following example, using "insertAdjacentHTML()" method and a legal position "afterend", a new text is placed adjacent to the header and the result is displayed in the output.
Live Demo
<html>
<body>
<h2 id="H2">Header</h2>
<script>
var ins = document.getElementById("H2");
ins.insertAdjacentHTML("afterend","<p>Tutorix is the best e-learning platform</p>");
</script>
</body>
</html>
Header
Tutorix is the best e-learning platform
In the following example, using "insertAdjacentHTML()" method and a legal position "beforeend", a new text is placed adjacent to the header and the result is displayed in the output.
Live Demo
<html>
<body>
<h2 id="H2">Header</h2>
<script>
var ins = document.getElementById("H2");
ins.insertAdjacentHTML("beforeend","<p>Tutorix is the best e-learning platform</p>");
</script>
</body>
</html>
Header
Tutorix is the best e-learning platform
C++ Program to Implement Doubly Linked List

Doubly linked list is a type of data structure that is made up of nodes that are created using self referential structures. Each of these nodes contain three parts, namely the data and the reference to the next list node and the reference to the previous list node.
Only the reference to the first list node is required to access the whole linked list. This is known as the head. The last node in the list points to nothing so it stores NULL in that part. Also the doubly linked list can be traversed in both directions as each node points to its previous and next node.
A program to implement doubly linked list is given as follows.
 Live Demo
#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node *prev;
   struct Node *next;
};
struct Node* head = NULL;
void insert(int newdata) {
   struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
   newnode->data = newdata;
   newnode->prev = NULL;
   newnode->next = head;
   if(head != NULL)
   head->prev = newnode ;
   head = newnode;
}
void display() {
   struct Node* ptr;
   ptr = head;
   while(ptr != NULL) {
      cout<< ptr->data <<" ";
      ptr = ptr->next;
   }
}
int main() {
   insert(3);
   insert(1);
   insert(7);
   insert(2);
   insert(9);
   cout<<"The doubly linked list is: ";
   display();
   return 0;
}
The doubly linked list is: 9 2 7 1 3
In the above program, the structure Node forms the doubly linked list node. It contains the data and a pointer to the next and previous linked list node. This is given as follows.
struct Node {
   int data;
   struct Node *prev;
   struct Node *next;
};
The function insert() inserts the data into the beginning of the doubly linked list. It creates a newnode and inserts the number in the data field of the newnode. Then the prev pointer in newnode points to NULL as it is entered at the beginning and the next pointer points to the head. If the head is not NULL then prev pointer of head points to newnode. Finally the head is the newnode i.e. the linked list starts from there. This is given below.
void insert(int newdata) {
   struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
   newnode->data = newdata;
   newnode->prev = NULL;
   newnode->next = head;
   if(head != NULL)
   head->prev = newnode ;
   head = newnode;
}
The function display() displays the whole doubly linked list. First ptr points to head. Then it is continuously forwarded to the next node until all the data values of the nodes are printed. This is given below.
void display() {
   struct Node* ptr;
   ptr = head;
   while(ptr != NULL) {
      cout<< ptr->data <<" ";
      ptr = ptr->next;
   }
}
In the function main(), first various values are inserted into the doubly linked list by calling insert(). Then the doubly linked list is displayed. This is given below.
int main() {
   insert(3);
   insert(1);
   insert(7);
   insert(2);
   insert(9);
   cout<<"The doubly linked list is: ";
   display();
   return 0;
}
Constructor overloading in Java

Yes! Java supports constructor overloading. In constructor loading, we create multiple constructors with the same name but with different parameters types or with different no of parameters.
Live Demo
public class Tester {
 
   private String message;
 
   public Tester(){
      message = "Hello World!";
   }
   public Tester(String message){
      this.message = message;
   }
 
   public String getMessage(){
      return message ;
   }
 
   public void setMessage(String message){
      this.message = message;
   }
 
   public static void main(String[] args) {
      Tester tester = new Tester();
      System.out.println(tester.getMessage());
   
      Tester tester1 = new Tester("Welcome");
      System.out.println(tester1.getMessage());  
   }
}   
Hello World!
Welcome
Java program to generate random numbers

The java.util.Random class instance is used to generate a stream of pseudorandom numbers.
The class uses a 48-bit seed, which is modified using a linear congruential formula.
The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudo randomly generated bits.
The nextInt() method of this class is used to get the next pseudorandom, uniformly distributed int value from this random number generator's sequence.
import java.util.*;
public class RandomNumberGeneration {
   public static void main( String args[] ) {
      // create random object
      Random randomno = new Random();
      Scanner sc = new Scanner(System.in);
      System.out.println("How many random numbers do you need :");
      int n= sc.nextInt();
     
      // check next int value
      for(int i=0; i<n; i++){
         System.out.println(randomno.nextInt());
      }
   }
}
How many random numbers do you need :
4
709914869
-1882917719
-758130689
637944833
Division Operator in C#

Division operator is used in C# to divide numerator by denominator, for example 9/ 3
The division operator comes under Arithmetic Operators in C#. Let us see a complete example to learn how to implement Arithmetic operators in C#, wherein we will see how to work with division operator.
result = num1 / num2;
Console.WriteLine("Division: Value is {0}", result);
Above we have used division operator on num1 and num2.
The following is the complete example.
 Live Demo
using System;
namespace Sample {
   class Demo {
      static void Main(string[] args) {
         int num1 = 50;
         int num2 = 25;
         int result;
         result = num1 + num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 - num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 * num2;
         Console.WriteLine("Value is {0}", result);
         result = num1 / num2;
         Console.WriteLine("Division: Value is {0}", result);
         result = num1 % num2;
         Console.WriteLine("Value is {0}", result);
         result = num1++;
         Console.WriteLine("Value is {0}", result);
         result = num1--;
         Console.WriteLine("Value is {0}", result);
         Console.ReadLine();
      }
   }
}
Value is 75
Value is 25
Value is 1250
Division: Value is 2
Value is 0
Value is 50
Value is 51