code-rag-bench/online-tutorials huggingface dataset:
OpenCV - Scaling

You can perform scaling on an image using the resize() method of the imgproc class. Following is the syntax of this method.
resize(Mat src, Mat dst, Size dsize, double fx, double fy, int interpolation)

This method accepts the following parameters −
src − A Mat object representing the source (input image) for this operation.
src − A Mat object representing the source (input image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
dsize − A Size object representing the size of the output image.
dsize − A Size object representing the size of the output image.
fx − A variable of the type double representing the scale factor along the horizontal axis.
fx − A variable of the type double representing the scale factor along the horizontal axis.
fy − A variable of the type double representing the scale factor along the vertical axis.
fy − A variable of the type double representing the scale factor along the vertical axis.
Interpolation − An integer variable representing interpolation method.
Interpolation − An integer variable representing interpolation method.
The following program demonstrates how to apply scale transformation to an image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Scaling {
   public static void main(String args[]) {
      // Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      // Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap24/transform_input.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();

      // Creating the Size object
      Size size = new Size(src.rows()*2, src.rows()*2);

      // Scaling the Image
      Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap24/scale_output.jpg", dst);

      System.out.println("Image Processed");
   }
}
Assume that following is the input image transform_input.jpg specified in the above program (size − Width:300px and height:300px).
On executing the program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows (size − Width:600px and height:600px) −

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
Online Election in C++

Suppose in an election, the i-th vote was cast for persons[i] at time times[i]. Now, we have to implement the following query function: TopVotedCandidate.q(int t) this will find the number of the person that was leading the election at time t. Votes cast at time t will count towards our query. If there is a tie, the most recent vote (among tied candidates) wins.
So if we initialize this with TopVotedCandidate([0,1,1,0,0,1,0], [0,5,10,15,20,25,30]), then call q() like: q(3), q(12), q(25), q(15), q(24), q(8), then the result will be [0, 1, 1, 0, 0, 1] for each call of q(). This is because at time 3, the votes are [0], and 0 is leading. At time 12, the votes are [0,1,1], and here 1 is leading. At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.). This continues for 3 more queries at time 15, 24, and finally 8.
To solve this, we will follow these steps −
Create two maps m and count
Create two maps m and count
In the initializer, do the following tasks
In the initializer, do the following tasks
lead := -1
lead := -1
for i in range 0 to size of times arrayx := times[i]increase the value of count[persons[i]] by 1if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead
for i in range 0 to size of times array
x := times[i]
x := times[i]
increase the value of count[persons[i]] by 1
increase the value of count[persons[i]] by 1
if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead
if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead
the q() method will be likedecrease the upper bound of t in m, and return the corresponding value
the q() method will be like
decrease the upper bound of t in m, and return the corresponding value
decrease the upper bound of t in m, and return the corresponding value
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TopVotedCandidate {
   public:
   map <int, int> m;
   map <int, int> count;
   TopVotedCandidate(vector<int>& persons, vector<int>& times) {
      int lead = -1;
      for(int i = 0; i < times.size(); i++){
         int x = times[i];
         count[persons[i]]++;
         if(count[lead] <= count[persons[i]]){
            lead = persons[i];
            m[x] = lead;
         }else{
            m[x] = lead;
         }
      }
   }
   int q(int t) {
      return ((--m.upper_bound(t)) -> second);
   }
};
main(){
   vector<int> v1 = {0,1,1,0,0,1,0}, v2 = {0,5,10,15,20,25,30};
   TopVotedCandidate ob(v1, v2);
   cout << (ob.q(3)) << endl;
   cout << (ob.q(12)) << endl;
   cout << (ob.q(25)) << endl;
   cout << (ob.q(15)) << endl;
   cout << (ob.q(24)) << endl;
   cout << (ob.q(8)) << endl;
}
Initialize the class using [0,1,1,0,0,1,0] and [0,5,10,15,20,25,30]. Call q()
method like below:
q(3)
q(12)
q(25)
q(15)
q(24)
q(8)
0
1
1
0
0
1
Difference Between Pointer and Reference

In this post, we will understand the difference between pointer and reference.
It can be initialized to any value.
It can be initialized to any value.
It can be initialized any time after its declaration.
It can be initialized any time after its declaration.
It can be assigned to point to a NULL value.
It can be assigned to point to a NULL value.
It can be dereferenced using the ‘*’ operator.
It can be dereferenced using the ‘*’ operator.
It can be changed to point to a different variable of the same type only.
It can be changed to point to a different variable of the same type only.
int val = 5;
//code//
int *p = &val;
It has to be initialized when it is declared.
It has to be initialized when it is declared.
It can’t be a NULL value.
It can’t be a NULL value.
It can be used by a name.
It can be used by a name.
Once it has been initialized to a variable, it can’t be changed to refer to a variable object.
Once it has been initialized to a variable, it can’t be changed to refer to a variable object.
int val = 52;
int &ref = val;
Bulma Text weight - GeeksforGeeks

08 Dec, 2021
Bulma text weight class is used to set the text into bold text. There are 5 text weights and you can transform the text weight with the use of one of 5 text weight helpers.
Text weight classes:
has-text-weight-light: This class is used to transform text weight to light.
has-text-weight-normal: This class is used to transform text weight to normal.
has-text-weight-medium: This class is used to transform text weight to medium.
has-text-weight-semibold: This class is used to transform text weight to semi-bold.
has-text-weight-bold: This class is used to transform text weight to bold.
Example: Below example illustrate the text size class in Bulma.
HTML
<!DOCTYPE html><html>  <head>    <title>Bulma Typography</title>    <link rel='stylesheet'          href='https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css'></head>  <body class="has-text-centered">    <h1 class="is-size-2 has-text-success">        GeeksforGeeks    </h1>    <b>Bulma Text weight</b>    <br>    <div class="container">        <p class="is-size-5 has-text-weight-light">GeeksforGeeks</p>          <p class="is-size-5 has-text-weight-normal">GeeksforGeeks</p>          <p class="is-size-5 has-text-weight-medium">GeeksforGeeks</p>          <p class="is-size-5 has-text-weight-semibold">GeeksforGeeks</p>          <p class="is-size-5 has-text-weight-bold">GeeksforGeeks</p>      </div></body></html>
Output: 
Bulma Text weight 
Reference: https://bulma.io/documentation/helpers/typography-helpers/#text-weight
Bulma
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
How to create a file upload button in HTML ? - GeeksforGeeks

27 Sep, 2021
In this article, we will see how to make a file upload button to upload a file using HTML. As we know, uploading a file is an important aspect in simple HTML form. The file upload button is used to upload a user photo or any type of file in a form. 
Approach: For uploading the file using HTML, we will
create a HTML document that contains an <input> tag.
use the type attribute which is set to value “file”.
Syntax:
<input type="file">
Example:
HTML
<!DOCTYPE html><html> <head>    <title>HTML input type file</title>     <!--CSS code-->    <style>        h1 {            color: green;        }         h2,        h3 {            font-family: Impact;        }         body {            text-align: center;        }    </style></head> <body>    <h2>GeeksforGeeks</h2>    <h3>        How to create a file Upload        Button using html?    </h3>         <label> Choose the File to upload: </label>    <input type="file" id="myFile" /> <br /><br />         <input type="submit" value="submit" /></body> </html>
Output: You can see that after the file is uploaded, the name of the file is displayed in front of the button. 
File upload button in HTML
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
simranarora5sos
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Print all the permutations of a string without repetition using Collections in Java - GeeksforGeeks

03 Sep, 2019
Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. A permutation should not have repeated strings in the output.
Examples:
Input: str = “aa”Output:aaNote that “aa” will be printed only onceas duplicates are not allowed.
Input: str = “ab”Output:abba
Approach: Write a recursive function that removes a character one by one from the original string and generates a new string by appending these removed characters. The base condition will be when all the characters have been used. In that case, insert the generated string (a permutation of the original string) in a set in order to avoid duplicates.
Below is the implementation of the above approach:
// Java implementation of the approachimport java.util.*;public class GFG {      static Set<String> hash_Set = new HashSet<>();      // Recursive function to generate    // permutations of the string    static void Permutation(String str, String ans)    {          // If string is empty        if (str.length() == 0) {              // Add the generated permutation to the            // set in order to avoid duplicates            hash_Set.add(ans);            return;        }          for (int i = 0; i < str.length(); i++) {              // ith character of str            char ch = str.charAt(i);              // Rest of the string after excluding            // the ith character            String ros = str.substring(0, i)                         + str.substring(i + 1);              // Recurvise call            Permutation(ros, ans + ch);        }    }      // Driver code    public static void main(String[] args)    {        String s = "ab";          // Generate permutations        Permutation(s, "");          // Print the generated permutations        hash_Set.forEach((n) -> System.out.println(n));    }}
ab
ba

java-hashset
Backtracking
Recursion
Recursion
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path of more than k length from a source
Difference between Backtracking and Branch-N-Bound technique
Tug of War
Minimum Cost Path in a directed graph via given set of intermediate nodes
N-Queen Problem | Local Search using Hill climbing with random neighbour
Recursion
Recursive Practice Problems with Solutions
Program for Sum of the digits of a given number
Print all possible combinations of r elements in a given array of size n
Write a program to reverse digits of a number
Python program to Sort Matrix by Maximum Row element - GeeksforGeeks

11 Oct, 2020
Given a Matrix, sort rows by maximum element.
Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted.Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [0, 3, 5]] Explanation : 18, 10, and 5 are maximum elements in rows, hence sorted.  
Method #1 : Using sort() + max()
In this, we perform task of sorting using sort() with key being maximum element from each row. The reverse keyword is used to sort by keeping maximum element rows at start and decreasing from there.
Python3
# Python3 code to demonstrate working of # Sort Matrix by Maximum Row element# Using sort() + max()  def max_sort(row):    return max(row)  # initializing listtest_list = [[5, 7, 8], [9, 10, 3],             [10, 18, 3], [0, 3, 5]]  # printing original listprint("The original list is : " + str(test_list))  # sort() for sorting, max to get maximum valuestest_list.sort(key = max_sort, reverse = True)  # printing result print("The maximum sorted Matrix : " + str(test_list))
Output:
The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]
Method #2 : Using sorted() + lambda + max()
In this, we perform task of sorting using sorted() for non-inplace sort, and lambda function is used instead of external function to include maximum element from row logic.
Python3
# Python3 code to demonstrate working of # Sort Matrix by Maximum Row element# Using sorted() + lambda + max()  # initializing listtest_list = [[5, 7, 8], [9, 10, 3],             [10, 18, 3], [0, 3, 5]]  # printing original listprint("The original list is : " + str(test_list))  # sorted() for sorting, max to get maximum values# reverse for reversed orderres = sorted(test_list, key = lambda row : max(row), reverse=True)  # printing result print("The maximum sorted Matrix : " + str(res))
Output:
The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
PyQt5 – How to create circular image from any image ?

26 Mar, 2020
In this article, we will see how to display only circular/round image from any image with any width and height i.e
In order to do so we have to do the following steps :
1. Load the image2. Crop image to make it square3. Mask it and make circle from it using Painter4. Convert it back to pixmap image
Code :
Below is the original image :
# importing librariesfrom PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import *  # function to alter imagedef mask_image(imgdata, imgtype ='png', size = 64):      # Load image    image = QImage.fromData(imgdata, imgtype)      # convert image to 32-bit ARGB (adds an alpha    # channel ie transparency factor):    image.convertToFormat(QImage.Format_ARGB32)      # Crop image to a square:    imgsize = min(image.width(), image.height())    rect = QRect(        (image.width() - imgsize) / 2,        (image.height() - imgsize) / 2,        imgsize,        imgsize,     )           image = image.copy(rect)      # Create the output image with the same dimensions     # and an alpha channel and make it completely transparent:    out_img = QImage(imgsize, imgsize, QImage.Format_ARGB32)    out_img.fill(Qt.transparent)      # Create a texture brush and paint a circle     # with the original image onto the output image:    brush = QBrush(image)      # Paint the output image    painter = QPainter(out_img)    painter.setBrush(brush)      # Don't draw an outline    painter.setPen(Qt.NoPen)      # drawing circle    painter.drawEllipse(0, 0, imgsize, imgsize)      # closing painter event    painter.end()      # Convert the image to a pixmap and rescale it.     pr = QWindow().devicePixelRatio()    pm = QPixmap.fromImage(out_img)    pm.setDevicePixelRatio(pr)    size *= pr    pm = pm.scaled(size, size, Qt.KeepAspectRatio,                                Qt.SmoothTransformation)      # return back the pixmap data    return pm    class Window(QWidget):          """Simple window that shows our masked image and text label."""    def __init__(self):        super().__init__()          # setting up the geometry        self.setGeometry(100, 100, 600, 400)          # image path        imgpath = "image.png"          # loading image        imgdata = open(imgpath, 'rb').read()          # calling the function        pixmap = mask_image(imgdata)          # creating label        self.ilabel = QLabel(self)          # putting image on label        self.ilabel.setPixmap(pixmap)          # moving the label        self.ilabel.move(240, 180)          # another label to put text        self.tlabel = QLabel('This is circular image', self)        self.tlabel.move(200, 250)      # main functionif __name__ == '__main__':    import sys    from PyQt5.QtWidgets import QApplication      # app created    app = QApplication(sys.argv)    w = Window()    w.show()      # begin the app    sys.exit(app.exec_())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy np.coords() method

03 Nov, 2019
With the help of np.coords() method, we can get the coordinates of a next value in iteration using np.coords() method.
Syntax : np.coords()Return : Return the coordinates of next iterator.
Example #1 :In this example we can see that by using np.coords() method, we are able to get the coordinates of a next iterator using this method.
# import numpyimport numpy as np  a = np.array([1, 2, 3])# using np.coords() methodgfg = a.flatnext(gfg)print(gfg.coords)
Output :
(1, )
Example #2 :
# import numpyimport numpy as np  a = np.array([[1, 2, 3], [4, 5, 6]])# using np.coords() methodgfg = a.flatnext(gfg)next(gfg)next(gfg)next(gfg)print(gfg.coords)
Output :
(1, 1)
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DAX Date & Time - YEARFRAC function

Calculates the fraction of the year represented by the number of whole days between two dates.
YEARFRAC (<start_date>, <end_date>, [<basis>]) 

start_date
The start date in datetime format.
end_date
The end date in datetime format.
basis
Optional.
The type of day count basis to use.
An integer between 0 and 4. If not an integer, the parameter will be truncated.
0 - US (NASD) 30/360.
1 - Actual/actual.
2 - Actual/360.
3 - Actual/365.
4 - European 30/360.
If omitted, default is 0.
A decimal number. The internal data type is a signed IEEE 64-bit (8-byte) double-precision floating-point number.
You can use the YEARFRAC function to identify the proportion of a whole year's benefits or obligations to assign to a specific term.
DAX uses a datetime format to work with dates and times.
If start_date or end_date are not valid dates, YEARFRAC returns an error.
If basis < 0 or if basis > 4, YEARFRAC returns an error.
= YEARFRAC ([InventoryDate], [UsageDate]) 
This formula returns a calculated column with fraction values representing InventoryDuration.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Search by value in a Map in C++ - GeeksforGeeks

03 Mar, 2021
Given set of N pairs as a (key, value) pairs in a map and an integers K, task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”.Examples: 
Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3 Output: 1 2 10 Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 10 Output: -1 Explanation: There is no any key value that is mapped to value 10. 
Approach: The idea is to traverse the given map and print all the key value which are mapped to the given value K. Below is the loop used to find all the key value: 
for(auto &it : Map) { if(it.second == K) { print(it.first) } }  
If there is no value mapped with K then print “-1”.Below is the implementation of the above approach:
CPP
// C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to find the key values// according to given mapped value Kvoid printKey(map<int, int>& Map,              int K){     // If a is true, then we have    // not key-value mapped to K    bool a = true;     // Traverse the map    for (auto& it : Map) {         // If mapped value is K,        // then print the key value        if (it.second == K) {            cout << it.first << ' ';            a = false;        }    }     // If there is not key mapped with K,    // then print -1    if (a) {        cout << "-1";    }} // Driver Codeint main(){    map<int, int> Map;     // Given map    Map[1] = 3;    Map[2] = 3;    Map[4] = -1;    Map[7] = 2;    Map[10] = 3;     // Given value K    int K = 3;     // Function call    printKey(Map, K);    return 0;}
1 2 10
 
Time Complexity: O(N), where N is the number of pairs stored in map. This is because we are traversing all the pairs once.Auxiliary Space: O(1)
ParthKapadia
cpp-map
C++ Programs
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
CSV file management using C++
delete keyword in C++
Shallow Copy and Deep Copy in C++
cin in C++
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
Static Keyword in C++ - GeeksQuiz

29 Jul, 2020
#include <iostream >
using namespace std;

class A
{
private:
    int x;
public:
    A(int _x)  {  x = _x; }
    int get()  { return x; }
};

class B
{
    static A a;
public:
   static int get()
   {  return a.get(); }
};

A B::a(0);

int main(void)
{
    B b;
    cout << b.get();
    return 0;
}

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Drop Rows that Contain a Specific String in Pandas?
How to Read Text Files with Pandas?
Sort by index of an array in JavaScript

Suppose we have the following array of objects −
const arr = [
   {
      'name' : 'd',
      'index' : 3
   },
   {
      'name' : 'c',
      'index' : 2
   },
   {
      'name' : 'a',
      'index' : 0
   },
   {
      'name' : 'b',
      'index' : 1
   }
];
We are required to write a JavaScript function that takes in one such array.
The function should sort this array in increasing order according to the index property of objects.
Then the function should map the sorted array to an array of strings where each string is the corresponding name property value of the object.
Therefore, for the above array, the final output should look like −
const output = ["a", "b", "c", "d"];
The code for this will be −
const arr = [
   {
      'name' : 'd',
      'index' : 3
   },
   {
      'name' : 'c',
      'index' : 2
   },
   {
      'name' : 'a',
      'index' : 0
   },
   {
      'name' : 'b',
      'index' : 1
   }
];
const sortAndMap = (arr = []) => {
   const copy = arr.slice();
   const sorter = (a, b) => {
      return a['index'] - b['index'];
   };
   copy.sort(sorter);
   const res = copy.map(({name, index}) => {
      return name;
   });
   return res;
};
console.log(sortAndMap(arr));
And the output in the console will be −
[ 'a', 'b', 'c', 'd' ]
Python Pandas – Merge DataFrame with many-to-one relation

To merge Pandas DataFrame, use the merge() function. The many-to-one relation is implemented on both the DataFrames by setting under the “validate” parameter of the merge() function i.e. −
validate = “many-to-one”
or
validate = “m:1”
The many-to-one relation checks if merge keys are unique in right dataset.
At first, let us create our 1st DataFrame −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 110, 80, 110, 90]
   }
)


Now, let us create our 2nd DataFrame −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
   }
)


Following is the code −
#
# Merge Pandas DataFrame with many-to-one relation
#

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 110, 80, 110, 90]
   }
)

print("DataFrame1 ...\n",dataFrame1)

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print("\nDataFrame2 ...\n",dataFrame2)

# merge DataFrames with "many-to-one" in "validate" parameter
mergedRes = pd.merge(dataFrame1, dataFrame2, validate ="many_to_one")
print("\nMerged dataframe with many-to-one relation...\n", mergedRes)
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1     Audi     110
2  Mustang      80
3  Bentley     110
4   Jaguar      90

DataFrame1 ...
        Car   Reg_Price
0       BMW        7000
1     Lexus        1500
2     Tesla        5000
3   Mustang        8000
4  Mercedes        9000
5    Jaguar        6000

Merged dataframe with many-to-one relation...
       Car   Units   Reg_Price
0      BMW     100        7000
1  Mustang      80        8000
2   Jaguar      90        6000
MongoDB find() query for nested document?

To fetch a value from the nested document, use dot notation. Let us create a collection with
documents −
> db.demo591.insert([
...    { "Name": "John", "Age": 23 },
...    {"Name": "Carol", "Age": 26},
...    { "Name": "Robert", "Age": 29,
...    details:[
...       {
...          Email:"Robert@gmail.com",CountryName:"US"},{"Post":35}
...       ]}
... ]);
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
Display all documents from a collection with the help of find() method −
> db.demo591.find();
This will produce the following output −
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd3"), "Name" : "John", "Age" : 23 }
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd4"), "Name" : "Carol", "Age" : 26 }
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ {
"Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }
Following is the query to fetch nested document using dot notation −
> db.demo591.find({"details.Email": "Robert@gmail.com"});
This will produce the following output −
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [
   { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } 
] }
size of char datatype and char array in C - GeeksforGeeks

15 Oct, 2019
Given a char variable and a char array, the task is to write a program to find the size of this char variable and char array in C.
Examples:
Input: ch = 'G', arr[] = {'G', 'F', 'G'}
Output: 
Size of char datatype is: 1 byte
Size of char array is: 3 byte

Input: ch = 'G', arr[] = {'G', 'F'}
Output: 
Size of char datatype is: 1 byte
Size of char array is: 2 byte

Approach:In the below program, to find the size of the char variable and char array:
first, the char variable is defined in charType and the char array in arr.
Then, the size of the char variable is calculated using sizeof() operator.
Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.
Below is the C program to find the size of the char variable and char array:
// C program to find the size of// char data type and char array  #include <stdio.h>  int main(){      char charType = 'G';    char arr[] = { 'G', 'F', 'G' };      // Calculate and Print    // the size of charType    printf("Size of char datatype is: %ld byte\n",           sizeof(charType));      // Calculate the size of char array    size_t size = sizeof(arr) / sizeof(arr[0]);      // Print the size of char array    printf("Size of char array is: %ld byte",           size);      return 0;}
Size of char datatype is: 1 byte
Size of char array is: 3 byte

C-Data Types
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
Header files in C/C++ and its uses
C Program to read contents of Whole File
UDP Server-Client implementation in C
GATE | GATE CS 2008 | Question 32 - GeeksforGeeks

19 Nov, 2018
Which of the following is/are true of the auto-increment addressing mode?
I.  It is useful in creating self-relocating code.
II. If it is included in an Instruction Set Architecture, 
    then an additional ALU is required for effective address 
    calculation.
III.The amount of increment depends on the size of the data
     item accessed.
(A) I only(B) II only(C) III Only(D) II and III onlyAnswer: (C)Explanation: In auto-increment addressing mode the address where next data block to be stored is generated automatically depending upon the size of single data item required to store.
Self relocating code takes always some address in memory and statement says that this mode is used for self relocating code so option 1 is incorrect and  no additional ALU is required So option (C) is correct option.Quiz of this Question
GATE-CS-2008
GATE-GATE CS 2008
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
String Literal Vs String Object in Java - GeeksforGeeks

23 Jan, 2018
Compare string initialization performance for String Literal and String object.String Literal
String str = “GeeksForGeeks”;
This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “GeeksForGeeks”, then str will reference of that string and no new String object will be created. Please refer Initialize and Compare Strings in Java for details.
String Object
String str = new String(“GeeksForGeeks”);
This is string object. In this method JVM is forced to create a new string reference, even if “GeeksForGeeks” is in the reference pool.
Therefore, if we compare performance of string literal and string object, string object will always take more time to execute than string literal because it will construct a new string every time it is executed.Note: Execution time is compiler dependent.
Below is the Java program to compare their performances.
// Java program to compare performance // of string literal and string object  class ComparePerformance {      public static void main(String args[])    {            // Initialization time for String        // Literal        long start1 = System.currentTimeMillis();                  for (int i = 0; i < 10000; i++)        {            String s1 = "GeeksForGeeks";            String s2 = "Welcome";        }                  long end1 = System.currentTimeMillis();        long total_time = end1 - start1;          System.out.println("Time taken to execute"+                 " string literal = " + total_time);          // Initialization time for String        // object        long start2 = System.currentTimeMillis();                  for (int i = 0; i < 10000; i++)        {            String s3 = new String("GeeksForGeeks");            String s4 = new String("Welcome");        }                  long end2 = System.currentTimeMillis();        long total_time1 = end2 - start2;          System.out.println("Time taken to execute"+                   " string object=" + total_time1);    }}
Output:
Time taken to execute string literal = 0
Time taken to execute string object = 2

Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Scala Stack toMap() method with example - GeeksforGeeks

03 Nov, 2019
In Scala Stack class, the toMap() method is utilized to return a map consisting of all the elements of the stack.
Method Definition: def toMap[T, U]: Map[T, U]
Return Type: It returns a map consisting of all the elements of the stack.
Example #1:
// Scala program of toMap() // method   // Import Stack import scala.collection.mutable._  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating stack        val s1 = Stack((1, 2), (3, 4), (5, 6))                   // Print the stack         println(s1)                    // Applying toMap method          val result = s1.toMap                  // Display output         print("Elements in the map: " + result)               } } 
Stack((1, 2), (3, 4), (5, 6))
Elements in the map: Map(1 -> 2, 3 -> 4, 5 -> 6)

Example #2:
// Scala program of toMap() // method   // Import Stack import scala.collection.mutable._  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating stack        val s1 = Stack((5, 2), (13, 7), (1, 3))                   // Print the stack         println(s1)                    // Applying toMap method          val result = s1.toMap                  // Display output         print("Elements in the map: " + result)               } } 
Stack((5, 2), (13, 7), (1, 3))
Elements in the map: Map(5 -> 2, 13 -> 7, 1 -> 3)

Scala
scala-collection
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Constructors
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala | Arrays
Scala String substring() method with example
How to get the first element of List in Scala
Scala String replace() method with example
What is the Difference Between i++ and ++i in Java? - GeeksforGeeks

07 Jan, 2021
++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator.
Increment in java is performed in two ways,
1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1.
2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.
Example
int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4
Example 1
Java
// Java program to demonstrate pre and post increment// operators  import java.io.*;  class GFG {    public static void main(String[] args)    {        // initialize i        int i = 0;        System.out.println("Post-Increment");          // i values is incremented to 1 after returning        // current value i.e; 0        System.out.println(i++);          // initialized to 0        int j = 0;        System.out.println("Pre-Increment");          // j is incremented to 1 and then it's value is        // returned        System.out.println(++j);    }}
Post-Increment
0
Pre-Increment
1
Example 2: Cannot apply the increment operator (++) on a constant value
Java
// Applying increment operator on a constant value  import java.io.*;  class GFG {    public static void main(String[] args)    {          int x = ++10;          System.out.println("Hello");    }}
Output
prog.java:8: error: unexpected type
          int x = ++ 10;
                     ^
  required: variable
  found:    value
1 error
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
Babylonian method to find the square root

The Babylonian method to find square root is based on one of the numerical method, which is based on the Newton- Raphson method for solving non-linear equations.
The idea is simple, starting from an arbitrary value of x, and y as 1, we can simply get next approximation of root by finding the average of x and y. Then the y value will be updated with  number / x.
Input:
A number: 65
Output:
The square root of 65 is: 8.06226
sqRoot(number)
Input: The number in real.
Output: Square root of given number.
Begin
   x := number
   y := 1
   precision := 0.000001
   while relative error of x and y > precision, do
      x := (x+y) / 2
      y := number / x
   done
   return x
End
#include<iostream>
#include<cmath>
using namespace std;

float sqRoot(float number) {
   float x = number, y = 1;              //initial guess as number and 1
   float precision = 0.000001;           //the result is correct upto 0.000001

   while(abs(x - y)/abs(x) > precision) {
      x = (x + y)/2;
      y = number/x;
   }
   return x;
}

int main() {
   int n;
   cout << "Enter Number to find square root: "; cin >> n;
   cout << "The square root of " << n <<" is: " << sqRoot(n);
}
Enter Number to find square root: 65
The square root of 65 is: 8.06226
Comparing content of files using Perl - GeeksforGeeks

26 Jul, 2019
In Perl, we can easily compare the content of two files by using the File::Compare module. This module provides a function called compare, which helps in comparing the content of two files specified to it as arguments. If the data present in both the files comes out to be same, the function returns 0 as the output, if the data in the passed files is different, the return value is 1 and if there is any error occurred while accessing the specified/passed files, it returns the value as -1.Syntax:
use File::Compare;
$compare = compare('FILE_NAME_1', 'FILE_NAME_2');

Note:
Same Content: Return Value [0]
Different Content: Return Value [1]
Error in Accessing Files: Return Value [-1]
Example:Files Present in the Folder. When the content of the Files is same:
#!/usr/bin/perlprint "Content-type: text/html\n\n";  # Module to use compare functionuse File::Compare;  # compare function to access the passed files.$compare = compare("gfg_a.txt", "gfg_c.txt");  # checking if the files are sameif ($compare == 0){    print "Files are equal. \n";}  # checking if the files are differentelsif ($compare == 1){    print "Files are not equal. \n";}  # checking if the file is not accessibleelsif($compare == -1){    print "Error Occured. \n";}  exit;
Output: When the content of the Files is different:
#!/usr/bin/perlprint "Content-type: text/html\n\n";  # Module to use compare functionuse File::Compare;  # compare function to access the passed files.$compare = compare("gfg_a.txt", "gfg_b.txt");  # checking if the files are sameif ($compare == 0){    print "Files are equal. \n";}  # checking if the files are differentelsif ($compare == 1){    print "Files are not equal. \n";}  # checking if the file is not accessibleelsif($compare == -1){    print "Error Occured. \n";}  exit;
Output: When the file is not accessible:
#!/usr/bin/perlprint "Content-type: text/html\n\n";  # Module to use compare functionuse File::Compare;  # compare function to access the passed files.$compare = compare("gfg_a.txt", "gfg_d.txt");  # checking if the files are sameif ($compare == 0){    print "Files are equal. \n";}  # checking if the files are differentelsif ($compare == 1){    print "Files are not equal. \n";}  # checking if the file is not accessibleelsif($compare == -1){    print "Error occurred. The file is not accessible. \n";}  exit;
Output:
Perl-files
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Writing to a File
Perl Tutorial - Learn Perl With Examples
Perl | Operators | Set - 1
Perl | Multidimensional Hashes
Perl | Reading Excel Files
Perl | File Handling Introduction
Perl | index() Function
Perl | Data Types
Perl | shift() Function
Perl | Appending to a File
C# Program to Check a Specified Type is a Primitive Data Type or Not - GeeksforGeeks

16 Nov, 2021
In C#, data types are used to specify the type of data that a variable can hold. There are two types of data types available in C# that is, primitive and non-primitive data types. Primitive data types are predefined data types such as Byte, SByte, Boolean, Int16, UInt16, Int32, UInt32, Char, Double, Int64, UInt64, Single, etc. Whereas non-primitive data types are user-defined data types such as enum, class, etc. In this article, we will learn how to check a specified type is a primitive data type or not. So, to do this task we use the IsPrimitive property of the Type class. This property is used to check whether the type of the specified data is one of the primitive types or not. It returns true if the given data type is primitive otherwise it will return false.
Syntax:
public bool IsPrimitive{ get; }
Example:
C#
// C# program to check a specified type // is a primitive data type or notusing System;using System.Reflection;  class GFG{  static void Main(){          // Check the int is an primitiva or not    if (typeof(int).IsPrimitive == true)    {        Console.WriteLine("Primitive data type");    }    else     {        Console.WriteLine("Not a primitive data type");    }          // Check the float is an primitiva or not    if (typeof(float).IsPrimitive == true)     {        Console.WriteLine("Primitive data type");    }    else     {        Console.WriteLine("Not a primitive data type");    }          // Check the int is an primitiva or not    if (typeof(double).IsPrimitive == true)     {        Console.WriteLine("Primitive data type");    }    else     {        Console.WriteLine("Not a primitive data type");    }}}
Output:
Primitive data type
Primitive data type
Primitive data type
CSharp-data-types
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Switch Statement in C#
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to find absolute value of a given number
How to change font size with HTML in Java Swing JEditorPane?

Use HTMLEditorKitt to change the font size with HTML. With that, use the JEditorPane setText() method to set HTML:
HTMLEditorKit kit = new HTMLEditorKit();
editorPane.setEditorKit(kit);
editorPane.setSize(size);
editorPane.setOpaque(true);
editorPane.setText("<b><font face=\"Verdana\" size=\"30\"> This is a demo text with a different font!</font></b>");
The following is an example to change font size with HTML in Java Swing JEditorPane:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.html.HTMLEditorKit;
public class SwingDemo extends JFrame {
   public static void main(String[] args) {
      SwingDemo s = new SwingDemo();
      s.setSize(600, 300);
      Container container = s.getContentPane();
      s.demo(container, container.getSize());
      s.setVisible(true);
   }
   public void demo(Container container, Dimension size) {
      JEditorPane editorPane = new JEditorPane();
      editorPane.setEditable(false);
      HTMLEditorKit kit = new HTMLEditorKit();
      editorPane.setEditorKit(kit);
      editorPane.setSize(size);
      editorPane.setOpaque(true);
      editorPane.setText("<b><font face=\"Verdana\" size=\"30\"> This is a demo text with a different font!</font></b>");
      container.add(editorPane, BorderLayout.CENTER);
   }
}