code-rag-bench/online-tutorials huggingface dataset:
Geeks and Groceries || | Practice | GeeksforGeeks

Geek went to a grocery shop with a bag in his hand, where he found there are two sections of products and he wanted to take P products from the first section and Q products from the second section. As geek is greedy, he wanted to fill his bag such that he spends a lesser amount. If two products have the same price then geek chooses the lexicographically smaller named product.

Given N products with their prices of the first section and M products with their prices of the second section, help the geek to choose those products. Print the names of the products in the order they have chosen
Input: 
1. The first line of the input contains a single integer  T denoting the number of test cases. The description of T test cases follows.
2. The first line of each test case contains four space-separated integers N, M, P, and Q.
3. Next N lines contain a string (contains English lower case letters) and an integer separated by a space.
4. Next M lines contain a string (contains English lower case letters) and an integer separated by a space. 

Output: For each test case, print the product names in the order they have chosen.

Constraints:
1. 1 <= T <= 10
2. 1 <= P <= N <= 100000
3. 1 <= Q <= M <= 100000
4. 1 <= product prices <= 100000
5. 1 <= size of prodcut name <= 10

Example:
Input:
1
3 3 1 2
maggi 10
pasta 50
noodles 30
cake 10
butter 30
bread 30
Output:
cake maggi bread

Explanation: Geek has to choose one product from the first section and two products from second section. So, he has chosen cake from the second section first (even cake and maggi have same price, a cake is lexicographically smaller.) and then he chose maggi from the first section and bread from the second section ( bread is lexicographically smaller than butter)
 
0
Pankaj sharma9 months ago
Pankaj sharma
Can anyone please tell me why test cases gives right output when checked using custom input but when I submit it produces wrong output.
0
Shobhit Yadav1 year ago
Shobhit Yadav
USE COMPARATOR
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
GATE | GATE-CS-2005 | Question 72 - GeeksforGeeks

07 Jul, 2020
Consider the following code fragment:
  if (fork() == 0)
  { a = a + 5; printf(“%d,%d\n”, a, &a); }
  else { a = a –5; printf(“%d, %d\n”, a, &a); } 
Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE?(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != yAnswer: (C)Explanation: fork() returns 0 in child process and process ID of child process in parent process.In Child (x), a = a + 5In Parent (u), a = a – 5;Therefore x = u + 10.The physical addresses of ‘a’ in parent and child must be different. But our program accesses virtual addresses (assuming we are running on an OS that uses virtual memory). The child process gets an exact copy of parent process and virtual address of ‘a’ doesn’t change in child process. Therefore, we get same addresses in both parent and child. But in python3 v and y will not be equal. See this (for Python) and See this (for C).Quiz of this Question
om_mishra
GATE-CS-2005
GATE-GATE-CS-2005
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
Convert.ToByte Method in C#

The Convert.ToByte method is used to convert a specified value to an 8-bit unsigned integer.
Let’s say we have a char variable.
Char charVal = ‘a’;
Now, convert it to an 8-bit unsigned integer.
byte byteVal = Convert.ToByte(charVal);
Let us see another example now.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      char[] charVal = { 'p', 'q', 'r', 's' };
      foreach (char c in charVal) {
         byte byteVal = Convert.ToByte(c);
         Console.WriteLine("{0} is converted to = {1}", c, byteVal);
      }
   }
}
p is converted to = 112
q is converted to = 113
r is converted to = 114
s is converted to = 115
Program to find the index of first Recurring Character in the given string in Python

Suppose we have a string s, we have to find the index of the first recurring character in it. If we
cannot find no recurring characters, then return -1.
So, if the input is like "abcade", then the output will be 3, as 'a' is again present at index 3.
To solve this, we will follow these steps −
define a map chars
for i in range 0 to size of s, doif s[i] in chars, thenreturn iotherwise,chars[s[i]] := chars[s[i]] + 1
if s[i] in chars, thenreturn i
return i
otherwise,chars[s[i]] := chars[s[i]] + 1
chars[s[i]] := chars[s[i]] + 1
return -1
Let us see the following implementation to get better understanding −
 Live Demo
from collections import defaultdict
class Solution:
   def solve(self, s):
      chars = defaultdict(int)
      for i in range(len(s)):
         if s[i] in chars:
            return i
         else:
            chars[s[i]] += 1
      return -1
ob = Solution()
print(ob.solve("abcade"))
"abcade"
3
Sorting a HashMap according to keys in C#

HashMap is in Java, not C#. The equivalent of HashMap in C# is Dictionary that is used as a collection of key-value pair.
Firstly, set the Dictionary −
Dictionary<string, int> d = new Dictionary<string, int>();

d.Add("soccer", 1);
d.Add("cricket", 2);
d.Add("tennis", 3);
d.Add("rugby", 4);
Now get the keys and sort them using ToList() and Sort() method respectively.
// get keys
var val = d.Keys.ToList();

// sort
val.Sort();
The following is the complete example to sort a HashMap according to keys −
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {

      Dictionary<string, int> d = new Dictionary<string, int>()
      d.Add("soccer", 1);
      d.Add("cricket", 2);
      d.Add("tennis", 3);
      d.Add("rugby", 4);

      // get keys
      var val = d.Keys.ToList();

      // sort
      val.Sort();

      // displaying sorted keys
      foreach (var key in val) {
         Console.WriteLine(key);
      }
   }
}
C# program to get the List of keys from a Dictionary

Set the dictionary elements −
Dictionary<int, string> d = new Dictionary<int, string>();

// dictionary elements
d.Add(1, "One");
d.Add(2, "Two");
d.Add(3, "Three");
d.Add(4, "Four");
d.Add(5, "Five");
d.Add(6, "Six");
d.Add(7, "Seven");
d.Add(8, "Eight");
To get the keys, use a list collection −
List<int> keys = new List<int>(d.Keys);
Loop through the keys and display them.
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Dictionary<int, string> d = new Dictionary<int, string>();
      // dictionary elements
      d.Add(1, "One");
      d.Add(2, "Two");
      d.Add(3, "Three");
      d.Add(4, "Four");
      d.Add(5, "Five");
      d.Add(6, "Six");
      d.Add(7, "Seven");
      d.Add(8, "Eight");
      // getting keys
      List<int> keys = new List<int>(d.Keys);
      Console.WriteLine("Displaying keys...");
      foreach (int res in keys) {
         Console.WriteLine(res);
      }
   }
}
Displaying keys...
1
2
3
4
5
6
7
8
Count distinct elements in an array in Python - GeeksforGeeks

22 Jan, 2019
Given an unsorted array, count all distinct elements in it.
Examples:
Input : arr[] = {10, 20, 20, 10, 30, 10} 
Output : 3

Input : arr[] = {10, 20, 20, 10, 20}
Output : 2

We have existing solution for this article. We can solve this problem in Python3 using Counter method.
from collections import Counter  def countDistinct(arr):      # counter method gives dictionary of elements in list    # with their corresponding frequency.    # using keys() method of dictionary data structure    # we can count distinct values in array    return len(Counter(arr).keys())      if __name__=="__main__":    arr = [10, 20, 20, 10, 30, 10]    print (countDistinct(arr))
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Named captured groups Java regular expressions

Named capturing groups allows you to reference the groups by names. Java started supporting captured groups since SE7.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "(?<globalCode>[\\d]{2})-(?<nationalCode>[\\d]{5})-(?<number>[\\d]{6})";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         System.out.println("Global code: "+matcher.group("globalCode"));
         System.out.println("National code: "+matcher.group("nationalCode"));
         System.out.println("Phone number: "+matcher.group("number"));
      }
   }
}
Enter input text:
91-08955-224558
Global code: 91
National code: 08955
Phone number: 224558
How many types of constructors are there in Java?

A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
There are two types of constructors parameterized constructors and no-arg constructors.
A parameterized constructor accepts parameters with which you can initialize the instance variables. Using parameterized constructor, you can initialize the class variables dynamically at the time of instantiating the class with distinct values.
Live Demo
import java.util.Scanner;
public class Test {
   int num;
   String data;
   float flt;
   Test(int num, String data, float flt){
      this.num = num;
      this.data = data;
      this.flt = flt;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int num = sc.nextInt();
      System.out.println("Enter a string value: ");
      String data = sc.next();
      System.out.println("Enter a floating point value: ");
      float flt = sc.nextFloat();      
      Test obj = new Test(num, data, flt);
      System.out.println(obj.num);
      System.out.println(obj.data);
      System.out.println(obj.flt);

   }
}
Enter an integer value:
1024
Enter a string value:
test
Enter a floating point value:
11.2
1024
test
11.2
A no-arg constructor doesn’t accepts any parameters, it instantiates the class variables with their respective default values (i.e. null for objects, 0.0 for float and double, false for Boolean, 0 for byte, short, int and, long).
Live Demo
public class Test {
   int num;
   String data;
   float flt;
   Test(){
      this.num = 100;
      this.data = "test";
      this.flt = 125.33f;
   }
   public static void main(String args[]){  
      Test obj = new Test();
      System.out.println(obj.num);
      System.out.println(obj.data);
      System.out.println(obj.flt);
   }
}
100
test
125.33
HTML DOM touchmove Event

The HTML DOM touchmove event is triggered when touch is moved across the touch screen.
NOTE − This event is only for touch devices.
Following is the syntax −
Trigger touchmove event in HTML −
ontouchmove = "eventFunction()"
Trigger touchmove event in JavaScript −
eventObject.ontouchmove = eventFunction
Note − We ran Touch event examples on Online HTML Editors accessed on Mobile or systems with touch access. This is done so that we can perform touch operations like touch the screen for 2 seconds.
Let us see an example of touchmove event property −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM touchmove event</title>
<style>
   * {
      padding: 2px;
      margin:5px;
   }
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   #outer {
      width:70%;
      margin: 0 auto;
      padding: 0;
      text-align: center;
      border:1px solid black;
      height: 105px;
      background-color: #28a745;
   }
   input[type="button"] {
      border-radius: 10px;
   }
   #upper {
      border-bottom: 1px solid black;
      height: 40px;
      margin: 0 0 15px 0;
      background-color: #DC3545;
   }
   #lower {
      border-top: 1px solid black;
      height: 40px;
      margin: 15px 0 0 0;
      background-color: #DC3545;
   }
</style>
</head>
<body>
   <form>
      <fieldset>
         <legend>HTML DOM touchmove event</legend>
         <div id="outer">
         <div id="upper"><h2>Danger</h2></div>
         <div id="lower"><h2>Danger</h2></div>
         </div>
         <input type="button" id="start" value="Start" onclick="gameStart()">
         <div id="divDisplay"></div>
      </fieldset>
   </form>
<script>
   var divDisplay = document.getElementById('divDisplay');
   var gameDisplay = document.getElementById('outer');
   function playGame(event) {
      var x = event.touches[0].clientX;
      var y = event.touches[0].clientY;
         if(y > 95 && y < 110){
            divDisplay.textContent = 'Keep Going!';
               if(x === 439){
                  divDisplay.textContent = 'Congrats! You Did it!';
                  gameDisplay.removeEventListener('touchmove', playGame);
               }
         }
         else{
            divDisplay.textContent = 'You moved to DANGER area. You loose!';
            gameDisplay.removeEventListener('touchmove', playGame);
         }
   }
   function gameStart(){
      gameDisplay.addEventListener('touchmove',playGame);
   }
</script>
</body>
</html>
After clicking ‘Start’ button and cursor in green (safe) area −
After clicking ‘Start’ button and cursor at end of green (safe) area −
After clicking ‘Start’ button and cursor in red (danger) area −
How to print a diamond using nested loop using C#?

With C#, you can easily display the following diamond shape.
$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$
To display a diamond shape, you need to focus on the following points −
Number of rows
Dollar sign to be displayed
Empty spaces
Considering the above you can easily create the diamond shape as shown in the below code −
 Live Demo
using System;
namespace Program {
   public class Demo {
      public static void Main(String[] args) {
         int i, j, r, d, e;

         // rows = 5
         r = 5;

         // display dollar sign
         d = 1;

         // empty space
         e = r - 1;

         for (i = 1; i < r * 2; i++) {
            // display empty space
            for (j = 1; j <= e; j++)
            Console.Write(" ");

            for (j = 1; j < d * 2; j++)
            Console.Write("$");

            Console.WriteLine();

            if (i < r) {
               e--;
               d++;
            } else {
               e++;
               d--;
            }
         }

      }
   }
}
$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$
Java Encapsulation and Getters and Setters

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden 
from users. To achieve this, you must:

declare class variables/attributes as private
provide public get 
and set methods to access and update the value of a private 
variable
You learned from the previous chapter that private variables can only be 
accessed within the same class (an outside class has no access to it). However, 
it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the 
name of the variable, with the first letter in upper case:
public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}
 
 

The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the
name variable. The this keyword is used to refer to the current 
object.
However, as the name variable is declared as private, we 
cannot access it from outside this class:
public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.name = "John";  // error
    System.out.println(myObj.name); // error 
  }
}


Run Example »

If the variable was declared as public, we would expect the following output:
However, as we try to access a private variable, we get an error:
Instead, we use the getName() and setName() methods to access and update the variable:
public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.setName("John"); // Set the value of the name variable to "John"
    System.out.println(myObj.getName());
  }
}

// Outputs "John"
 
 


Try it Yourself »

Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
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 draw markers on an image using Java OpenCV library?

You can draw makers on an image using the drawMarker() method of the org.opencv.imgproc.Imgproc class. This method accepts the following parameters −
img − A Mat object representing the input image.
img − A Mat object representing the input image.
position − An object of the class Point to specify the position of the marker.
position − An object of the class Point to specify the position of the marker.
color − An object of the class Scalar to specify the color of the marker.
color − An object of the class Scalar to specify the color of the marker.
markerType − An integer constant specifying the type of the marker.
markerType − An integer constant specifying the type of the marker.
size − An integer value specifying the size of the marker.
size − An integer value specifying the size of the marker.
thickness − An integer value specifying the thickness of the marker.
thickness − An integer value specifying the thickness of the marker.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DrawingMarkers {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the contents of the image
      String file ="D:\\Images\\elephant.jpg";
      Mat src = Imgcodecs.imread(file);
      //Preparing color and position of the marker
      Scalar color = new Scalar(0, 0, 125);
      Point point = new Point(150, 260);
      //Drawing marker
      Imgproc.drawMarker(src, point, color, Imgproc.MARKER_SQUARE, 150, 8, Imgproc.LINE_8);
      HighGui.imshow("Drawing Markers", src);
      HighGui.waitKey();
   }
}
On executing the above program generates the following window −
How to sort bars in increasing order in a bar chart in matplotlib?

To sort bars in increasing order in a bar chart in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a data frame, df, of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Add a subplot to the current figure.
Make a bar plot with the dataframe, df.
Add a subplot to the current figure.
Make a df_sorted by a column marks.
Make a bar plot with df_sorted.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

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

df = pd.DataFrame(
   dict(
      names=['John', 'James', 'David', 'Gary', 'Watson'],
      marks=[23, 34, 30, 19, 20]
   )
)

plt.subplot(121)
plt.bar('names', 'marks', data=df, color='red')

plt.subplot(122)
df_sorted = df.sort_values('marks')
plt.bar('names', 'marks', data=df_sorted, color='orange')

plt.show()
It will produce the following output
Notice the bar chart on the right. The bars are sorted in the increasing order of their values.
How can I extract or uncompress gzip file using php?

The zipped files can be unzipped or decompressed using PHP’s gzread function. Below is the code example for the same −
$file_name = name_of/.dump.gz';
$buffer_size = 4096; // The number of bytes that needs to be read at a specific time, 4KB here
$out_file_name = str_replace('.gz', '', $file_name);
$file = gzopen($file_name, 'rb'); //Opening the file in binary mode
$out_file = fopen($out_file_name, 'wb');
// Keep repeating until the end of the input file
while (!gzeof($file)) {
   fwrite($out_file, gzread($file, $buffer_size)); //Read buffer-size bytes.
}
fclose($out_file); //Close the files once they are done with
gzclose($file);
This will produce the following output −
The uncompressed data which is extracted by unzipping the zipped file.
The path of the zipped file is stored in a variable named ‘file_name’. The number of bytes that needs to be read at a time is fixed and assigned to a variable named ‘buffer_size’. The output file would not have the extension of .gz, hence the output file name is stored in a variable named ‘out_file_name’.
The ‘out_file_name’ is opened in a write binary mode to append contents into it after reading from the extracted zip file. The ‘file_name’ is opened in read mode, and the contents are read using the ‘gzread’ function and these contents extracted are written into the ‘out_file’. A while loop runs to make sure that the contents are read until the end of the file.
String Class repeat() Method in Java with Examples - GeeksforGeeks

28 Jan, 2021
The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned. 
Syntax:
string.repeat(count);
Parameter: Accepts an integer count which is the number of times we want to repeat the string.
Returns: String whose value is the concatenation of given String repeated count times
Example:
Input:

string = abc
count = 3

Output:

abcabcabc

Input:

string = xyz
count = 0

Output:

null
Algorithm:
Firstly, we take the input of String.Then we use the repeat() method with the number of counts we want to repeat the string. 
Firstly, we take the input of String.
Then we use the repeat() method with the number of counts we want to repeat the string. 
Example 1:
Java
// Java program to demonstrate the usage of // repeat() method  import java.io.*;  class GFG {    public static void main (String[] args) {              String string="abc";              int count=3;              System.out.println("String :"+string.repeat(count));        }}
String :abcabcabc
Example 2:
Java
// Java program to demonstrate the usage of // repeat() method  import java.io.*;  class GFG {    public static void main (String[] args) {               String string="xyz";       int count=0;               System.out.println("string :"+string.repeat(count));               }}
string :
Java 8
Java-Strings
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Explain in detail about Mark and Sweep algorithm in JavaScript?

Mark and Sweep algorithm looks out for objects 'which are unreachable' rather than objects 'which are no longer needed'. This algorithm is the improvement of Reference-counting algorithm.
 Root: In general, a root is a global variable that is used in the code. A window object in javascript can act as a   root. This algorithm uses global object root to find whether the objects are reachable or unreachable.
This algorithm then monitors every root and also their children. While monitoring, some objects which are reachable are marked and remaining objects which are unreachable are unmarked, based on the provided conditions.
 The objects which are unmarked, that means which are unreachable will be garbage collected. 
In mark phase we can able to find which elements are marked and which are unmarked. Let's suppose assign a property 'hello' to an object 'obj1' as shown in given Example-1. The root, global object used by this algorithm, can reach to obj1 and its property 'hello'. So it is marked now.
var obj1 = {
pro1: "hello" // marked because it can be reached by root.
}
For suppose let this object be assigned a null value as shown in Example-2. Then newly assigned 'null' will be marked and previously assigned 'property hello' will be unmarked. So at the end of the Mark phase we can conclude that object assigned with 'null' got marked and object assigned with 'property hello' was unmarked.
obj1 = null // null will be marked(reachable) and hello will be unmarked(unreachable)
As the name suggests it 'sweeps' the unreachable objects. In mark phase we have seen that object with "property hello" got unmarked, making it unreachable. Since unreachable objects will be garbage collected, the object with 'property hello' will be garbage collected in this phase.
The Mark and Sweep algorithm is also called as a tracing garbage collector because it traces out the entire collection of objects that are directly or indirectly accessible by the program.
In the following example, when the function call returns, the two objects obj1 and obj2 are not referenced by something that is reachable there by eligible for garbage collection. So garbage collector will free the memory of the objects obj1 and obj2.
function f() {
   var obj1 = {};
   var obj2 = {};
   obj1.p = obj2; // obj1 references obj2
   obj2.p = obj1; // obj2 references obj1. This creates a cycle.
}
f();
There are some moments when it is very convenient to manually decide when and what memory is released. In order to release the memory of the object, it has to be made explicitly unreachable. This process of explicitly triggering garbage collection in JavaScript is not possible as of now.
Python - Golomb Encoding for b=2n and b!=2n - GeeksforGeeks

16 Jul, 2020
The Golomb coding is a form of parameterized coding in which integers to be coded are stored as values relative to a constant b
Coding:-A positive number x is spoken to in two sections:
The initial segment is an unary portrayal of q+1, where q is the remainder floor((x/b)), and
The subsequent part is an extraordinary double portrayal of the leftover portion r = x-qb. Note that there are b potential leftovers.
For instance, if b = 3, the potential remnants will be 0, 1 and 2. To spare space, compose the initial couple of remnants utilizing floor(log(b, 2)) bits and the rest utilizing ceil(log(b, 2)) bits. We should do so with the end goal that the decoder knows at the point when floor(log(b, 2)) bits are utilized and when ceil(log(b, 2)) bits are utilized
Examples:
Input  : N = 37, M = 11 
Output : 0001100

Code : Python program to implement Golomb Encoding
# Python programming for Golomb Encodingimport math  # taking input for N and  M where # M == 2 ^ n or M != 2 ^ nN = 37M = 11  # for finding the value of preceding # number of zeros by dividing N by Mq = N//M# for computing the remainder of N by Mr = N % M  # appending that many numbers of zeros in# starting of the encoded code initially quo ='0'*q+'1'  # for computing the value of b ie floor of # log(M) base 2 which will be used for computing value of kb = math.floor(math.log2(M))k = 2**(b + 1)-M# upon comparing the value of remainder with the # value of k if less we we convert remainder r to # binary and add the value from # index 2 because # at index 0, 1 "0b" is presentif r < k:    rem = bin(r)[2:]    l = len(rem)      # upon the calculating value of rem if it is less than# computed value of b we add b-1 number of zeros in# preceding of the # remainder    if l<b:        rem = '0'*(b-l)+remelse:# we convert remainder r to binary and add the # value from index 2 because at index 0, 1 "0b" is present    rem = bin(r + k)[2:]    l = len(rem)# upon calculating value of rem if it is less than# computed value of b we add b-1 number of zeros in# preceding of the # remainder    if l<b + 1:        rem = '0'*(b + 1-l)+remgolomb_code = quo + remprint("The golomb code encoding for x = {} and b = {} is {}".      format(N, M, golomb_code))
Output :
The golomb code encoding for x = 37 and b = 11 is 0001100
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
How to create Menu Item Component in ReactJS ? - GeeksforGeeks

10 Feb, 2021
Menus display a list of choices on temporary surfaces. The menu is an essential part of any application. Material UI for React has this component available for us and it is very easy to integrate. We can use Menu Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from "react";import MenuItem from "@material-ui/core/MenuItem";import Button from "@material-ui/core/Button";import Menu from "@material-ui/core/Menu";  const App = () => {  const [anchorEl, setAnchorEl] = React.useState(null);    const handleClose = () => {    setAnchorEl(null);  };    const handleClick = (event) => {    setAnchorEl(event.currentTarget);  };    return (    <div      style={{        marginLeft: "40%",      }}    >      <h2>How to use Menu Component in ReactJS?</h2>      <Button        aria-controls="simple-menu"        aria-haspopup="true"        onClick={handleClick}      >        Open Menu List      </Button>      <Menu        keepMounted        anchorEl={anchorEl}        onClose={handleClose}        open={Boolean(anchorEl)}      >        <MenuItem onClick={handleClose}>My Account</MenuItem>        <MenuItem onClick={handleClose}>Settings</MenuItem>        <MenuItem onClick={handleClose}>Profile</MenuItem>        <MenuItem onClick={handleClose}>Logout</MenuItem>      </Menu>    </div>  );};  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
JavaScript
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
Create a Responsive Navbar using ReactJS
Python | Remove spaces from a string - GeeksforGeeks

17 Jan, 2019
Given a string, write a Python program to remove all spaces from it.
Examples:
Input :  g e e k
Output : geek

Input : Hello World
Output : HelloWorld

There are various approaches to remove whitespaces in a string. The first one is the Naive approach, which has been discussed in this article. But here we will discuss all the approaches which are specific to Python.
Approach#1 : Using replace()
Using replace() function, we replace all whitespace with no space(“”).
# Python3 code to remove whitespacedef remove(string):    return string.replace(" ", "")      # Driver Programstring = ' g e e k 'print(remove(string))
geek

 
Approach #2 : Using split() and join()
First we use split() function to return a list of the words in the string, using sep as the delimiter string. Then, we use join() to concatenate the iterable.
# Python3 code to remove whitespacedef remove(string):    return "".join(string.split())      # Driver Programstring = ' g e e k 'print(remove(string))
geek

 Approach #3 : Using Python regex
# Python3 code to remove whitespaceimport re  def remove(string):    pattern = re.compile(r'\s+')    return re.sub(pattern, '', string)      # Driver Programstring = ' g e e k 'print(remove(string))
geek

 
Approach #4 : Using translate()
# Python code to remove whitespaceimport string  def remove(string):    return string.translate(None, ' \n\t\r')      # Driver Programstring = ' g e e k 'print(remove(string))
geek

python-string
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
MongoDB - Greater than equals to Operator $gte - GeeksforGeeks

27 Mar, 2020
MongoDB provides different types of comparison operators and greater than equals to operator($gte) is one of them. This operator is used to select those documents where the value of the field is greater than equals to(>=) the given value. You can use this operator in methods (like, find(), update(), etc.) according to your requirements.
Syntax:
{field: {$gte: value}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs.
 Example #1:In this example, we are selecting those documents where the value of the salary field is greater than equals to 35000.
db.employee.find({salary: {$gte: 35000}}).pretty()
 Example #2:In this example, we are selecting only those documents where the age of the employee is greater than equals to 24. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation.
db.employee.find({"personalDetails.age": {$gte: 24}}).pretty()
 Example #3:
In this example, we are selecting only those documents where the points array is greater than equals to the specified array.
db.employee.find({points: {$gte: [6, 7]}}).pretty()
 Example #4:
In this example, we are updating the salary of those employees whose experience year is greater than equals to 2 years. Or in other words, set the value of the salary field to 60000 of those documents whose experienceYear field value is greater than equals to 2.
db.employee.update({experienceYear: {$gte: 2}}, {$set: {salary: 60000}})
Note: The update() method by default update only one document at a time. If you want to update multiple documents, then set the value of its multi parameter to true. So, in this example, the update() method updated the first document that matches the given condition as shown in the below image.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Basics of API Testing Using Postman
ML | What is Machine Learning ?
OpenCV - Overview
Getting Started with System Design
Deep Learning | Introduction to Long Short Term Memory
How to calculate probability in a normal distribution given mean and standard deviation in Python? - GeeksforGeeks

25 Feb, 2021
A normal distribution is a type of continuous probability distribution for a real-valued random variable. It is based on mean and standard deviation. The probability distribution function or PDF computes the likelihood of a single point in the distribution. The general formula to calculate PDF for the normal distribution is
Here, 
μ is the mean
σ is the standard deviation of the distribution
x is the number
for which PDF is to be calculated.. We can calculate probability in a normal distribution using SciPy module.
pip install scipy
We will use scipy.stats.norm.pdf() method to calculate the probability distribution for a number x.
Syntax: scipy.stats.norm.pdf(x, loc=None, scale=None)
Parameter:
x : array-like object, for which probability is to be calculated.
loc : optional (default=0), represents mean of the distribution.
scale : optional (default=1), represents standard deviation of the distribution.
Returns: A probability density function calculated at x as a ndarray object.
In scipy the functions used to calculate mean and standard deviation are mean() and std() respectively.
For mean
Syntax:
mean(data)
For standard deviation
Syntax:
std(data)
Import module
Create necessary data
Supply the function with required values
Display value
Example:
Python3
from scipy.stats import normimport numpy as np  data_start = -5data_end = 5data_points = 11data = np.linspace(data_start, data_end, data_points)  mean = np.mean(data)std = np.std(data)  probability_pdf = norm.pdf(3, loc=mean, scale=std)print(probability_pdf)
Output:
0.0804410163156249
Picked
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Numpy ndarray.T - GeeksforGeeks

02 Apr, 2019
With the help of Numpy ndarray.T object, we can make a Transpose of an array having dimension greater than or equal to 2.
Syntax : ndarray.T
Return : Transpose of an array
Example #1 :In this example we can see that with the help of ndarray.T object, we are able to transform an array.
# import the important module in pythonimport numpy as np         # make an array with numpygfg = np.array([[1, 2, 3], [4, 5, 6]])         # applying ndarray.T objectgeeks = gfg.T   print(geeks)
[[1 4]
 [2 5]
 [3 6]]

Example #2 :
# import the important module in pythonimport numpy as np         # make an array with numpygfg = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 0]])         # applying ndarray.T objectgeeks = gfg.T   print(geeks)
[[1 4 7]
 [2 5 8]
 [3 6 9]
 [4 7 0]]

Python numpy-ndarray
Python-numpy
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How can we assign FOREIGN KEY constraint on multiple columns?

MySQL allows us to add a FOREIGN KEY constraint on multiple columns in a table. The condition is that each Foreign Key in the child table must refer to the different parent table.
Suppose we have a table ‘customer2’ which have a Primary Key constraint on the field ‘cust_unq_id’ as follows −
mysql> describe customer2;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| cust_id     | int(11)     | YES  |     | NULL    |       |
| First_name  | varchar(20) | YES  |     | NULL    |       |
| Last_name   | varchar(20) | YES  |     | NULL    |       |
| City        | varchar(10) | YES  |     | NULL    |       |
| cust_unq_id | int(11)     | NO   | PRI | 0       |       |
+-------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
And we have a table orders1 which is already having a Foreign Key constraint on field ‘Cust_id’ referencing to the parent table ‘customer’.
mysql> describe orders1;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id     | int(11)     | NO   | PRI | NULL    |       |
| Product_name | varchar(25) | YES  |     | NULL    |       |
| orderdate    | date        | YES  |     | NULL    |       |
| Cust_id      | int(11)     | YES  | MUL | NULL    |       |
| cust_unq_id  | int(11)     | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
5 rows in set (0.04 sec)
Now, with the help of following ALTER TABLE query we can add another foreign key constraint on the field ‘cust_unq_id’ referencing to the parent table ‘customer2’
mysql> Alter table orders1 add FOREIGN KEY(cust_unq_id) REFERENCES Customer2(Cust_unq_id);
Query OK, 0 rows affected (0.25 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> describe orders1;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id     | int(11)     | NO   | PRI | NULL    |       |
| Product_name | varchar(25) | YES  |     | NULL    |       |
| orderdate    | date        | YES  |     | NULL    |       |
| Cust_id      | int(11)     | YES  | MUL | NULL    |       |
| cust_unq_id  | int(11)     | YES  | MUL | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
From the above result set, it can be observed that ‘orders1’ table is having two, one on ‘cust_id’ and other on ‘cust_unq_id’ foreign key constraints.
Python OpenCV | cv2.imshow() method

02 Sep, 2020
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imshow() method is used to display an image in a window. The window automatically fits to the image size. 
Syntax: cv2.imshow(window_name, image)Parameters: window_name: A string representing the name of the window in which image to be displayed. image: It is the image that is to be displayed.Return Value: It doesn’t returns anything.  
Image used for all the below examples:  
Example #1:  
# Python program to explain cv2.imshow() method   # importing cv2 import cv2   # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks.png'  # Reading an image in default modeimage = cv2.imread(path)  # Window name in which image is displayedwindow_name = 'image'  # Using cv2.imshow() method # Displaying the image cv2.imshow(window_name, image)  #waits for user to press any key #(this is necessary to avoid Python kernel form crashing)cv2.waitKey(0)   #closing all open windows cv2.destroyAllWindows() 
Output:  
Example #2:  
# Python program to explain cv2.imshow() method  # importing cv2import cv2  # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks.png'  # Reading an image in grayscale modeimage = cv2.imread(path, 0)  # Window name in which image is displayedwindow_name = 'image'  # Using cv2.imshow() method# Displaying the imagecv2.imshow(window_name, image)  # waits for user to press any key# (this is necessary to avoid Python kernel form crashing)cv2.waitKey(0)  # closing all open windowscv2.destroyAllWindows()
Output:  
 
mr.lovalova
2019csb1089
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
PySide2 – How to create window?

04 Oct, 2021
PySide2 is one of the most famous libraries in python for building GUI applications. In this article, we will build an empty window using PySide2 Library.
Steps to create empty window :

1. Import PySide2 in your code
2. Create QApplication object
3. Create object for QWidget
4. Increase the size of the window.
4. Show window using show() function
Python3
# import system moduleimport sys # import PySide2 modulesfrom PySide2.QtWidgets import QApplication, QWidget # create new appapp = QApplication(sys.argv) # create main windowmainwindow = QWidget() # resize window to 550 * 400mainwindow.resize(550, 400) # set title to the window framemainwindow.setWindowTitle('GeeksForGeeks') # invoke show functionmainwindow.show() # to kee in loop invoke exec_() functionapp.exec_()
As we execute this program, a new empty window of size 550*400 will pop up on your screen with the label ‘GeeksforGeeks’.
Output:
ruhelaa48
Python-gui
Python-PySide2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python