code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE-CS-2017 (Set 1) | Question 30

13 Aug, 2021
Consider the C code fragment given below.
typedef struct node
{
    int data;
    node* next ;
} node;

void join(node* m, node* n)
{
    node* p = n;
    while (p->next != NULL)
    {
        p = p->next;
    }
    p–>next = m;
}

Assuming that m and n point to valid NULL- terminated linked lists, invocation of join will(A) append list m to the end of list n for all inputs(B) either cause a null pointer dereference or append list m to the end of list n(C) cause a null pointer dereference for all inputs.(D) append list n to the end of list m for all inputs.Answer: (B)Explanation: As it is stated in the question, that m and n are valid Lists but not explicitly specified if the lists are empty or not. We can have two cases:
Case 1: If lists are not NULL : Invocation of join will append list m to the end of list n if the lists are not NULL. For Example:Before join operation :m =1->2->3->4->5->nulln =6->7->8->9->nullAfter join operation :6->7->8->9->1->2->3->4->5->nullCase 2: If lists are NULL : If the list n is empty and itself NULL, then joining and referencing would obviously create NULL pointer issue.
Case 1: If lists are not NULL : Invocation of join will append list m to the end of list n if the lists are not NULL. For Example:Before join operation :m =1->2->3->4->5->nulln =6->7->8->9->nullAfter join operation :6->7->8->9->1->2->3->4->5->null
Case 2: If lists are NULL : If the list n is empty and itself NULL, then joining and referencing would obviously create NULL pointer issue.
Therefore option B is correct
GATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:006:09 / 1:11:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j9Vmf5yRw-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 38
How to create tables in HTML?

To create table in HTML, use the <table> tag. A table consist of rows and columns, which can be set using one or more <tr>, <th>, and <td> elements. A table row is defined by the <tr> tag. To set table header, use the <th> tag. For a table cell, use the <td> tag.
Just keep in mind, table attributes such as align, bgcolor, border, cellpadding, cellspacing deprecated and isn’t supported by HTML5. Do not use them.
You can try the following code to create a table in HTML. We’re also using the <style> tag to style the table border
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
         }
      </style>
   </head>

   <body>
      <h1>Programming Languages</h1>
      <table>
         <tr>
            <th>Language</th>
            <th>Release Year</th>
         </tr>
         <tr>
            <td>Java</td>
            <td>1995</td>
         </tr>
         <tr>
            <td>Pascal</td>
            <td>1970</td>
         </tr>
      </table>
   </body>
</html>
Python | Pandas MultiIndex.from_product()

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.from_product() function make a MultiIndex from the cartesian product of multiple iterables.
Syntax: MultiIndex.from_product(iterables, sortorder=None, names=None)
Parameters :iterables : Each iterable has unique labels for each level of the index.sortorder : Level of sortedness (must be lexicographically sorted by that level).names : Names for the levels in the index.
Returns: index : MultiIndex
Example #1: Use MultiIndex.from_product() function to construct a MultiIndex from the cartesian product of multiple iterables.
# importing pandas as pdimport pandas as pd  # Create the first iterablePrice =[20, 35, 60, 85]  # Create the second iterableName =['Vanilla', 'Strawberry']  # Print the first iterableprint(Price)  # Print the second iterableprint("\n", Name)
Output :
Now let’s create the MultiIndex using the above two iterables.
# Creating the MultiIndexmidx = pd.MultiIndex.from_product([Name, Price],                       names =['Name', 'Price'])  # Print the MultiIndexprint(midx)
Output :As we can see in the output, the function has created a MultiIndex object using the cartesian product of these two iterables. Example #2: Use MultiIndex.from_product() function to construct a MultiIndex from the cartesian product of multiple iterables.
# importing pandas as pdimport pandas as pd  # Create the first iterableSnake =['Viper', 'Cobra']  # Create the second iterableVariety =['Brown', 'Yellow', 'Black']  # Print the first iterableprint(Snake)  # Print the second iterableprint("\n", Variety)
Output :
Now let’s create the MultiIndex using the above two iterables.
# Creating the MultiIndexmidx = pd.MultiIndex.from_product([Snake, Variety],                        names =['Snake', 'Variety'])  # Print the MultiIndexprint(midx)
Output :The function has created a MultiIndex using the two iterables.
Python pandas-multiIndex
Python-pandas
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
Python | datetime.timedelta() function
Python PIL | Image.alpha_composite() Method

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.alpha_composite() Alpha composite im2 over im1.
Syntax: PIL.Image.alpha_composite(im1, im2)
Parameters:img1 – The first image.img2 – The second image. Must have the same mode and size as the first image.
Returns: An Image object.
Img1 Used:
Img2 Used:
   # importing image class from PIL packagefrom PIL import Image  # creating image objectimg1 = Image.open(r"C:\Users\System-Pc\Desktop\home.png")  # creating image2 object having alphaimg2 = Image.open(r"C:\Users\System-Pc\Desktop\python.png")img2 = img2.resize(img1.size)  # using alpha_compositeim3 = Image.alpha_composite(img1, img2)im3.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 QListWidget – Setting Resize Mode Property

06 Aug, 2020
In this article we will see how we can set the resize mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether the items are laid out again when the view is resized. If this property is Adjust, the items will be laid out again when the view is resized. If the value is Fixed, the items will not be laid out when the view is resized. By default, this property is set to Fixed.
In order to do this we will use setResizeMode method with the list widget object.
Syntax : list_widget.setResizeMode(mode)
Argument : It takes resize mode object as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting resize mode property        list_widget.setResizeMode(QListView.Fixed)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
plotly.express.scatter_geo() function in Python

17 Jul, 2020
Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use.
This function is used to plot geographical data onto the maps.
Syntax: plotly.express.scatter_geo(data_frame=None, lat=None, lon=None, locations=None, locationmode=None, color=None, text=None, hover_name=None, hover_data=None, custom_data=None, size=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame: DataFrame or array-like or dict needs to be passed for column names.
lat: This parameter is used to position marks according to latitude on a map.
lon: This parameter is used to position marks according to longitude on a map.
locations: This parameter is interpreted according to locationmode and mapped to longitude/latitude.
locationmode: This parameter determines the set of locations used to match entries in locations to regions on the map.
color: This parameters assign color to marks.
size: This parameter is used to assign mark sizes. It is either a name of a column in data_frame, or a pandas Series or array_like object.
title: This parameter sets the title of the figure.
width: This parameter sets the width of the figure
height: This parameter sets the height of the figure.
Example 1:
Python3
import plotly.express as px    df = px.data.gapminder().query("year == 2007")  plot = px.scatter_geo(df, locations="iso_alpha")plot.show()
Output:
Example 2: Using the size and color argument
Python3
import plotly.express as px    df = px.data.gapminder().query("year == 2007")  plot = px.scatter_geo(df, locations="iso_alpha",                      size="gdpPercap",                      color = "country")plot.show()
Output:
Python Plotly express-class
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | pandas.to_numeric method

17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
pandas.to_numeric() is one of the general functions in Pandas which is used to convert argument to a numeric type.
Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None)
Parameters:arg : list, tuple, 1-d array, or Serieserrors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’-> If ‘raise’, then invalid parsing will raise an exception-> If ‘coerce’, then invalid parsing will be set as NaN-> If ‘ignore’, then invalid parsing will return the inputdowncast : [default None] If not None, and if the data has been successfully cast to a numerical dtype downcast that resulting data to the smallest numerical dtype possible according to the following rules:-> ‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)-> ‘unsigned’: smallest unsigned int dtype (min.: np.uint8)-> ‘float’: smallest float dtype (min.: np.float32)
Returns: numeric if parsing succeeded. Note that return type depends on input. Series if Series, otherwise ndarray.
Code #1:
Observe this dataset first. We’ll use ‘Numbers’ column of this data in order to make Series and then do the operation.
# importing pandas module import pandas as pd     # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   df.head(10)
Calling Series constructor on Number column and then selecting first 10 rows.
# importing pandas module import pandas as pd     # making data frame df = pd.read_csv("nba.csv")     # get first ten 'numbers'ser = pd.Series(df['Number']).head(10)ser
Output:
Using pd.to_numeric() method. Observe that by using downcast=’signed’, all the values will be casted to integer.
pd.to_numeric(ser, downcast ='signed')
Output:
 
Code #2: Using errors=’ignore’. It will ignore all non-numeric values.
# importing pandas module import pandas as pd       # get first ten 'numbers'ser = pd.Series(['Geeks', 11, 22.7, 33])  pd.to_numeric(ser, errors ='ignore')
Output: Code #3: Using errors=’coerce’. It will replace all non-numeric values with NaN.
# importing pandas module import pandas as pd       # get first ten 'numbers'ser = pd.Series(['Geeks', 11, 22.7, 33])  pd.to_numeric(ser, errors ='coerce')
Output:
Python pandas-general-functions
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE-CS-2004 - GeeksforGeeks

11 Oct, 2021

1.    9679, 1989, 4199 hash to the same value
2.    1471, 6171 hash to the same value
3.    All elements hash to the same value
4.    Each element hashes to a different value 
1.    P → Q R                    
2.    P → Q s R
3.    P → ε       
4.    P → Q t R r 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
htop command in Linux with examples

21 May, 2019
htop command in Linux system is a command line utility that allows the user to interactively monitor the system’s vital resources or server’s processes in real time. htop is a newer program compared to top command, and it offers many improvements over top command. htop supports mouse operation, uses color in its output and gives visual indications about processor, memory and swap usage. htop also prints full command lines for processes and allows one to scroll both vertically and horizontally for processes and command lines respectively.
Syntax:
htop [-dChusv]
Example:
Options:
-d –delay : Used to show the delay between updates, in tenths of seconds.
-C –no-color –no-colour : Start htop in monochrome mode.
-h –help : Used to display the help message and exit.
-u –user=USERNAME : Used to show only the processes of a given user.htop -u kunwarvikas
htop -u kunwarvikas
-p –pid=PID, PID... : Used to show only the given PIDs.
-s –sort-key COLUMN : Sort by this column (use –sort-key help for a column list).
-v –version : Output version information and exit.
Interactive Commands:
Arrows, Page Up, Page Down, Home, End: Scroll the process list.
Space: Tag or untag a process.
U – Untag all processes (remove all tags added with the Space key).
s – Trace process system calls.
F1 – Help
F2 – setup
F3 – search
F4 – filtering: type in part of a process command line and only processes whose names match will be shown.
F5 – Tree view.
F6 – Sorting.
F7 – Increase the selected process’s priority. This can only be done by the superuser.
F8 – Decrease the selected process’s priority.
F9 – Kill process.
F10 – Quit.
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Component Based Model (CBM)

13 Jun, 2022
The component-based assembly model uses object-oriented technologies. In object-oriented technologies, the emphasis is on the creation of classes. Classes are the entities that encapsulate data and algorithms. In component-based architecture, classes (i.e., components required to build application) can be uses as reusable components. This model uses various characteristics of spiral model. This model is evolutionary by nature. Hence, software development can be done using iterative approach. In CBD model, multiple classes can be used. These classes are basically the prepackaged components. The model works in following manner:
Step-1: First identify all the required candidate components, i.e., classes with the help of application data and algorithms.
Step-2: If these candidate components are used in previous software projects then they must be present in the library.
Step-3: Such preexisting components can be excited from the library and used for further development.
Step-4: But if the required component is not present in the library then build or create the component as per requirement.
Step-5: Place this newly created component in the library. This makes one iteration of the system.
Step-6: Repeat steps 1 to 5 for creating n iterations, where n denotes the number of iterations required to develop the complete application.
Characteristics of Component Assembly Model:
Uses object-oriented technology.
Components and classes encapsulate both data and algorithms.
Components are developed to be reusable.
Paradigm similar to spiral model, but engineering activity involves components. 
The system produced by assembling the correct components.
ankurpatle18
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hex to ASCII conversion in 8051

Now we will see how to convert Hexadecimal number to its ASCII equivalent using 8051. This program can convert 0-9 and A-F to its ASCII value. 
We know that the ASCII of number 00H is 30H (48D), and ASCII of 09H is39H (57D). So all other numbers are in the range 30H to 39H. The ASCII value of 0AH is 41H (65D) and ASCII of 0FH is 46H (70D), so all other alphabets (B, C, D, E) are in the range 41H to 46H.
Here we are providing hexadecimal digit at memory location 20H, The ASCII equivalent is storing at location 30H.
MOVR0,#20H; Initialize the address of the data
MOVA,@R0; Get the data from an address, which is stored in R0
MOVR2,A;Store the content of A into R2
CLRC; Clear the Carry Flag
SUBBA,#0AH;Subtract 0AH from A
JCNUM ; When a carry is present, A is numeric
ADDA,#41H;Add41H for Alphabet
SJMPSTORE; Jump to store the value
NUM:    MOVA,R2; Copy R2 to A
ADDA,#30H; Add 30H with A to get ASCII
STORE:  MOVR0,#30H; Point the destination location
MOV@R0,A; Store A content to the memory location pointed by R0
HALT:   SJMPHALT
The logic behind HEX to ASCII conversion is very simple. We are just checking whether the number is in range 0 – 9 or not. When the number is in that range, then the hexadecimal digit is numeric, and we are just simply adding 30H with it to get the ASCII value. When the number is not in range 0 – 9, then the number is range A – F, so for that case, we are converting the number to 41H onwards.
In the program, at first, we are clearing the carry flag. Then subtracting 0AHfrom the given number. If the value is numeric, then after subtraction the result will be negative, so the carry flag will be set. Now by checking the carry status, we can just add 30H with the value to get ASCII value. 
In other hands when the result of the subtraction is positive or 0, then we are adding 41H with the result of the subtraction.
Assigning values to static final variables in java


In java, a non-static final variable can be assigned a value at two places.
At the time of declaration.
At the time of declaration.
In constructor.
In constructor.
Live Demo
public class Tester {
   final int A;
   //Scenario 1: assignment at time of declaration
   final int B = 2;

   public Tester() {
      //Scenario 2: assignment in constructor
      A = 1;
   }

   public void display() {
      System.out.println(A + ", " + B);
   }

   public static void main(String[] args) {        
      Tester tester = new Tester();
      tester.display();
   }
}
1, 2
But in case of being static final, a variable cannot be assigned at the constructor. The compiler will throw a compilation error. A static final variable is required to be assigned in a static block or at time of declaration. So a static final variable can be assigned a value at the following two places.
At the time of declaration.
At the time of declaration.
In static block.
In static block.
Live Demo
public class Tester {
   final int A;
   //Scenario 1: assignment at time of declaration
   final int B = 2;

   public Tester() {
      //Scenario 2: assignment in constructor
      A = 1;
   }

   public void display() {
      System.out.println(A + ", " + B);
   }

   public static void main(String[] args) {        
      Tester tester = new Tester();
      tester.display();
   }
}
1, 2
The reason behind this behavior of the static final variable is simple. A static final is common across the objects and if it is allowed to be assigned in the constructor, then during the creation of an object, this variable is getting changed per object and thus is not assigned once.
Tryit Editor v3.7

Tryit: HTML link colors
Abstract Classes in C#

An abstract class in C# includes abstract and non-abstract methods. A class is declared abstract to be an abstract class. You cannot instantiate an abstract class.
Let us see an example, wherein we have an abstract class Vehicle and abstract method display()−
public abstract class Vehicle {
   public abstract void display();
} 
The abstract class has derived classes: Bus, Car, and  Motorcycle. The following is an implementation of the Bus derived class −
public class Bus : Vehicle {
   public override void display() {
      Console.WriteLine("Bus");
   }
} 
Let us see the complete example of abstract classes in C# −
Live Demo
using System;
public abstract class Vehicle {
   public abstract void display();
}

public class Bus : Vehicle {
   public override void display() {
      Console.WriteLine("Bus");
   }
}

public class Car : Vehicle {
   public override void display() {
      Console.WriteLine("Car");
   }
}

public class Motorcycle : Vehicle {
   public override void display() {
      Console.WriteLine("Motorcycle");
   }
}

public class MyClass {
   public static void Main() {
      Vehicle v;
      v = new Bus();
      v.display();
      v = new Car();
      v.display();
      v = new Motorcycle();
      v.display();
   }
} 
Bus
Car
Motorcycle
do...while loop vs. while loop in C/C++

Here we will see what are the basic differences of do-while loop and the while loop in C or C++.
A while loop in C programming repeatedly executes a target statement as long as a given condition is true. The syntax is like below.
while(condition) {
   statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
#include <stdio.h>
int main () {
   int a = 10; // Local variable declaration:
   do { // do loop execution
      printf("value of a: %d\n", a);
      a = a + 1;
   } while( a < 20 );
   return 0;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Now let us see the do-while loop.
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
do {
   statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
#include <stdio.h>
int main () {
   /* local variable definition */
   int a = 10;
   /* while loop execution */
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
   }
   return 0;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
So the differences are summarized in the following table −
while(condition){
   //statement
}
do{
   //statement
}while(condition);
Maximum subarray sum modulo m in C++

In this problem, we are given an array of size n and an integer m. our task is to create a program that will find the maximum subarray sum modulo m in C++.
Program description − Here, we will find the maximum value obtained by dividing the sum of all elements of subarray divided by m.
Let’s take an example to understand the problem,
Input − array = {4, 9 ,2} m = 6
Output − 5
Explanation − All subarrays and their remainders on dividing
{4}: 4%6 = 4
{9}: 9%6 = 3
{2}: 2%6 = 2
{4, 9}: 13%6 = 1
{9, 2}: 11%6 = 5
{4, 9, 2}: 15%6 = 3
To solve this problem, we compute prefixSumModulo Array. And the calculating maxSum of each index using the formula, maxSum at i = (prefixi + prefixj + m)%m
Program to illustrate our solution,
 Live Demo
#include<bits/stdc++.h>
using namespace std;
int calcMaxSum(int arr[], int n, int m) {
   int x, prefix = 0, maxSumMod = 0;
   set<int> sums;
   sums.insert(0);
   for (int i = 0; i < n; i++){
      prefix = (prefix + arr[i])%m;
      maxSumMod = max(maxSumMod, prefix);
      auto it = sums.lower_bound(prefix+1);
      if (it != sums.end())
         maxSumMod = max(maxSumMod, prefix - (*it) + m );
      sums.insert(prefix);
   }
   return maxSumMod;
}
int main() {
   int arr[] = {4, 9, 2};
   int n = sizeof(arr)/sizeof(arr[0]);
   int m = 5;
   cout<<"Maximum subarray sum modulo "<<m<<" is "<<calcMaxSum(arr, n, m) < endl;
   return 0;
}
Maximum subarray sum modulo 5 is 4
Find Intersecting Intervals in Python

Suppose we have a list of intervals, where each interval is like [start, end] this is representing
start and end times of an intervals (inclusive), We have to find their intersection, i.e. the
interval that lies within all of the given intervals.
So, if the input is like [[10, 110],[20, 60],[25, 75]], then the output will be [25, 60]
To solve this, we will follow these steps −
start, end := interval after deleting last element from intervals list
while intervals is not empty, dostart_temp, end_temp := interval after deleting last element from intervals liststart := maximum of start, start_tempend := minimum of end, end_temp
start_temp, end_temp := interval after deleting last element from intervals list
start := maximum of start, start_temp
end := minimum of end, end_temp
return an interval [start, end]
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, intervals):
      start, end = intervals.pop()
      while intervals:
         start_temp, end_temp = intervals.pop()
         start = max(start, start_temp)
         end = min(end, end_temp)
      return [start, end]
ob = Solution()
intervals = [[10, 110],[20, 60],[25, 75]]
print(ob.solve(intervals))
[[10, 110],[20, 60],[25, 75]]
[25, 60]
C++ Program to Generate All Possible Combinations of a Given List of Numbers

This is a C++ program to generate all possible combinations of a given list of numbers
Begin
   Take the number of elements and the elements as input.
   function Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) :
   If currLen>reqLen then
   Return
   Else if currLen=reqLen then
      Then print the new generated sequence.
   If s=l then
      Then return no further element is left.
   For every index there are two option:
   either proceed with a start as ‘true’ and recursively call Combi() with incremented value of ‘currLen’ and ‘s’.
   Or proceed with a start as ‘false’ and recursively call Combi() with only incremented value of ‘s’.
End
#include<iostream>
using namespace std;
void Combi(char a[], int reqLen, int s, int currLen, bool check[], int l)
// print the all possible combination of given array set
{
   if(currLen > reqLen)
   return;
   else if (currLen == reqLen) {
      cout<<"\t";
      for (int i = 0; i < l; i++) {
         if (check[i] == true) {
            cout<<a[i]<<" ";
         }
      }
      cout<<"\n";
      return;
   }
   if (s == l) {
      return;
   }
   check[s] = true;
   Combi(a, reqLen, s + 1, currLen + 1, check, l);
      //recursively call Combi() with incremented value of ‘currLen’ and ‘s’.
   check[s] = false;
   Combi(a, reqLen, s + 1, currLen, check, l);
      // recursively call Combi() with only incremented value of ‘s’.
}
int main() {
   int i,n;
   bool check[n];
   cout<<"Enter the number of element array have: ";
   cin>>n;
   char a[n];
   cout<<"\n";
   for(i = 0; i < n; i++) {
      cout<<"Enter "<<i+1<<" element: ";
      cin>>a[i];
      check[i] = false;
   }
   for(i = 1; i <= n; i++) {
      cout<<"\nThe all possible combination of length "<<i<<" for the given array set:\n";
      Combi(a, i, 0, 0, check, n);
   }
   return 0;
}
Enter the number of element array have: 4
Enter 1 element: 4
Enter 2 element: 3
Enter 3 element: 2
Enter 4 element: 1
The all possible combination of length 1 for the given array set:
4
3
2
1
The all possible combination of length 2 for the given array set:
4 3
4 2
4 1
3 2
3 1
2 1
The all possible combination of length 3 for the given array set:
4 3 2
4 3 1
4 2 1
3 2 1
The all possible combination of length 4 for the given array set:
4 3 2 1
Keras - Pooling Layer

It is used to perform max pooling operations on temporal data. The signature of the MaxPooling1D function and its arguments with default value is as follows −
keras.layers.MaxPooling1D (
   pool_size = 2, 
   strides = None, 
   padding = 'valid', 
   data_format = 'channels_last'
)
Here,
pool_size refers the max pooling windows.
pool_size refers the max pooling windows.
strides refer the factors for downscale.
strides refer the factors for downscale.
Similarly, MaxPooling2D and MaxPooling3D are used for Max pooling operations for spatial data.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    68 Lectures 
     2 hours 

 Mike West
 Print
 Add Notes
 Bookmark this page
Python - Sort Records by Kth Index List - GeeksforGeeks

02 Sep, 2021
Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as web development. Let’s discuss certain way in which this task can be performed. 
Input : test_list = [([4, 5], ‘Gfg’), ([8, 4], ‘is’), ([2, 3], ‘best’)] K = 0 Output : [([2, 3], ‘best’), ([4, 5], ‘Gfg’), ([8, 4], ‘is’)]Input : test_list = [([4, 5], ‘Gfg’), ([8, 4], ‘is’), ([2, 3], ‘best’)] K = 1 Output : [([2, 3], ‘best’), ([8, 4], ‘is’), ([4, 5], ‘Gfg’)]  
Method : Using sort() + lambda The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sort, the parameter and index by which sorting has to be performed is provided using lambda function. 
Python3
# Python3 code to demonstrate working of# Sort Records by Kth Index List# Using sort() + lambda # initializing listtest_list = [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'),                                 ([2, 3, 5, 2], 'best')] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 1 # Sort Records by Kth Index List# Using sort() + lambdatest_list.sort(key = lambda sub: sub[0][K]) # printing resultprint("The records after sorting : " + str(test_list))
The original list is : [([4, 5, 7, 3], ‘Gfg’), ([8, 6, 3, 1], ‘is’), ([2, 3, 5, 2], ‘best’)] The records after sorting : [([2, 3, 5, 2], ‘best’), ([4, 5, 7, 3], ‘Gfg’), ([8, 6, 3, 1], ‘is’)] 
 
  
adnanirshad158
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to capture video from default camera in OpenCV using C++?

Here, we will understand how to access the default camera and show the video stream from that camera. In a laptop, the fixed webcam is the default camera. In desktops, the default camera depends on the serial port's sequence where the camera is connected. When we want to capture the video stream from default webcam, we do not need to know anything about the camera and ensure that the camera is connected.
The following program takes video stream from default camera and shows it on the screen in real-time.
#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   Mat myImage;//Declaring a matrix to load the frames//
   namedWindow("Video Player");//Declaring the video to show the video//
   VideoCapture cap(0);//Declaring an object to capture stream of frames from default camera//
   if (!cap.isOpened()){ //This section prompt an error message if no video stream is found//
      cout << "No video stream detected" << endl;
      system("pause");
      return-1;
   }
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
         break;
      }
      imshow("Video Player", myImage);//Showing the video//
      char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//
      if (c == 27){ //If 'Esc' is entered break the loop//
         break;
      }
   }
   cap.release();//Releasing the buffer memory//
   return 0;
}
This program will show the real-time default camera's video stream on the monitor.
Concatenated string with uncommon characters in Python - GeeksforGeeks

19 Nov, 2020
Two strings are given and you have to modify 1st string such that all the common characters of the 2nd string have to be removed and the uncommon characters of the 2nd string have to be concatenated with uncommon characters of the 1st string.
Examples:
Input : S1 = "aacdb"
        S2 = "gafd"
Output : "cbgf"

Input : S1 = "abcs";
        S2 = "cxzca";
Output : "bsxz"

This problem has existing solution please refer Concatenated string with uncommon characters of two strings link. We can solve this problem quickly in Python using Set and List Comprehension. Approach is simple,
Convert both strings into set so that they could have only unique characters. Now take intersection of two sets to get common character both strings have.Now separate out those characters in each string which are not common in both of them and concatenate the characters.
Convert both strings into set so that they could have only unique characters. Now take intersection of two sets to get common character both strings have.
Now separate out those characters in each string which are not common in both of them and concatenate the characters.
# Function to concatenated string with uncommon # characters of two strings   def uncommonConcat(str1, str2):       # convert both strings into set     set1 = set(str1)     set2 = set(str2)       # take intersection of two sets to get list of     # common characters     common = list(set1 & set2)       # separate out characters in each string     # which are not common in both strings     result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common]       # join each character without space to get     # final string     print( ''.join(result) )  # Driver program if __name__ == "__main__":     str1 = 'aacdb'    str2 = 'gafd'    uncommonConcat(str1,str2) 
Output:
cbgf

Code_Mech
Python list-programs
Python set-programs
Python string-programs
python-list
python-set
python-string
Python
Strings
python-list
python-set
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
Build tree array from JSON in JavaScript

Suppose, we have the following array in JavaScript −
const arr = [{
   "code": "2",
   "name": "PENDING"
},
{
   "code": "2.2",
   "name": "PENDING CHILDREN"
},
{
   "code": "2.2.01.01",
   "name": "PENDING CHILDREN CHILDREN"
},
{
   "code": "2.2.01.02",
   "name": "PENDING CHILDREN CHILDREN02"
},
{
   "code": "1",
   "name": "ACTIVE"
},
{
   "code": "1.1",
   "name": "ACTIVE CHILDREN"
},
{
   "code": "1.1.01",
   "name": "ACTIVE CHILDREN CHILDREN"
}];
We are required to write a JavaScript function that takes in one such array. The function should build a tree structure from this array based on the "name" property of objects.
Therefore, for the above array, the output should look something like this −
const output = [{
   "code": "2",
   "name": "PENDING",
   "children": [{
      "code": "2.2",
      "name": "PENDING CHILDREN",
      "children": [{
         "code": "2.2.01.01",
         "name": "PENDING CHILDREN CHILDREN"
      },
      {
         "code": "2.2.01.02",
         "name": "PENDING CHILDREN CHILDREN02"
      }]
   }]
},
{
   "code": "1",
   "name": "ACTIVE",
   "children": [{
      "code": "1.1",
      "name": "ACTIVE CHILDREN",
      "children": [{
         "code": "1.1.01",
         "name": "ACTIVE CHILDREN CHILDREN"
      }]
   }]
}];
The code for this will be −
const arr = [{
   "code": "2",
   "name": "PENDING"
},
{
   "code": "2.2",
   "name": "PENDING CHILDREN"
},
{
   "code": "2.2.01.01",
   "name": "PENDING CHILDREN CHILDREN"
},
{
   "code": "2.2.01.02",
   "name": "PENDING CHILDREN CHILDREN02"
},
{
   "code": "1",
   "name": "ACTIVE"
},
{
   "code": "1.1",
   "name": "ACTIVE CHILDREN"
},
{
   "code": "1.1.01",
   "name": "ACTIVE CHILDREN CHILDREN"
}];
const transformToTree = (arr, root = '') => {
   let map = {}, last = [root], level = 0;
   map[root] = {};
   arr.forEach(el => {
      let parent = root;
      while (level && last[level].length >= el.code.length) {
         level--;
      };
      parent = last[level];
      level++;
      last.length = level;
      last.push(el.code);
      map[el.code] = el;
      map[parent].children = map[parent].children || [];
      map[parent].children.push(el);
   });
   return map[root].children;
};
console.log(JSON.stringify(transformToTree(arr), undefined, 4));
And the output in the console will be −
[
   {
      "code": "2",
      "name": "PENDING",
      "children": [
         {
            "code": "2.2",
            "name": "PENDING CHILDREN",
            "children": [
               {
                  "code": "2.2.01.01",
                  "name": "PENDING CHILDREN CHILDREN"
               },
               {
                  "code": "2.2.01.02",
                  "name": "PENDING CHILDREN CHILDREN02"
               }
            ]
         }
      ]
   },
   {
      "code": "1",
      "name": "ACTIVE",
      "children": [
         {
            "code": "1.1",
            "name": "ACTIVE CHILDREN",
            "children": [
               {
                  "code": "1.1.01",
                  "name": "ACTIVE CHILDREN CHILDREN"
               }
            ]
         }
      ]
   }
]
C# Fixed-Point (“F”) Format Specifier

The ("F") format specifier converts a number to a string of the following form −
"-ddd.ddd..."
Above, "d" indicates a digit (0-9).
Let us see an example.
Here, if we will set (“F3”) format specifier to add three values after decimal places, for let’s say, 212.
212.000
The following is another example −
 Live Demo
using System;
using System.Globalization;
class Demo {
   static void Main() {
      int val;
      val = 38788;
      Console.WriteLine(val.ToString("F",CultureInfo.InvariantCulture));
      val = -344;
      Console.WriteLine(val.ToString("F3",CultureInfo.InvariantCulture));
      val = 5656;
      Console.WriteLine(val.ToString("F5",CultureInfo.InvariantCulture));
   }
}
38788.00
-344.000
5656.00000
Find max in struct array using C++.

Here we will see how to get max in the struct array. Suppose there is a struct like below is given. We have to find the max element of an array of that struct type.
struct Height{
   int feet, inch;
};
The idea is straight forward. We will traverse the array, and keep track of the max value of array element in inches. Where value is 12*feet + inch
#include<iostream>
#include<algorithm>
using namespace std;
struct Height{
   int feet, inch;
};
int maxHeight(Height h_arr[], int n){
   int index = 0;
   int height = INT_MIN;
   for(int i = 0; i < n; i++){
      int temp = 12 * (h_arr[i].feet) + h_arr[i].inch;
      if(temp > height){
         height = temp;
         index = i;
      }
   }
   return index;
}
int main() {
   Height h_arr[] = {{1,3},{10,5},{6,8},{3,7},{5,9}};
   int n = sizeof(h_arr)/sizeof(h_arr[0]);
   int max_index = maxHeight(h_arr, n);
   cout << "Max Height: " << h_arr[max_index].feet << " feet and " << h_arr[max_index].inch << " inches";
}
Max Height: 10 feet and 5 inches
Removing a specific substring from a string in JavaScript

We are given a main string and a substring, our job is to create a function, let’s say
removeString() that takes in these two arguments and returns a version of the main string which
is free of the substring.
Here, we need to remove the separator from a string, for example −
this-is-a-sting
Let’s now write the code for this function −
const removeString = (string, separator) => {
   //we split the string and make it free of separator
   const separatedArray = string.split(separator);
   //we join the separatedArray with empty string
   const separatedString = separatedArray.join("");
   return separatedString;
}
const str = removeString('this-is-a-sting', '-');
console.log(str);
The output of this code in the console will be −
thisisastring
Change image resolution using Pillow in Python - GeeksforGeeks

02 Dec, 2020
Prerequisites: Python pillow
PIL is the Python Imaging Library which provides the python interpreter with an in-depth file format support, an efficient internal representation, and fairly powerful image processing capabilities. Changing the resolution of an image simply means reducing or increasing the number of pixels in an image, without changing its dimensions or any other factor. In this article, we are going to learn the methods how to change the quality/Resolution of an image with the help of python PIL(pillow) Library.
Using quality Parameter:
The image quality is a scale to measure and store the resolution of an image. It lies in the range of 0 to 100 where 95 is considered as best because 100 disables some portions of jpeg compression algorithm that results very large files. While on the other hand the gain in image quality or resolution is also insignificant from 95 to 100. The functionality can be achieved by the following steps:
Import the Images module from pillow.Open the image using .open( ) method by specifying the image path.The image_file.save() method have a parameter named quality, that specifies the resolution of an image in a 1-100 scale, where 95 is considered as the optimal quality.
Import the Images module from pillow.
Open the image using .open( ) method by specifying the image path.
The image_file.save() method have a parameter named quality, that specifies the resolution of an image in a 1-100 scale, where 95 is considered as the optimal quality.
Program:
Python3
# Import the Images module from pillowfrom PIL import Image  # Open the image by specifying the image path.image_path = "image_name.jpeg"image_file = Image.open(image_path)  # the defaultimage_file.save("image_name.jpg", quality=95)  # Changing the image resolution using quality parameter# Example-1image_file.save("image_name2.jpg", quality=25)  # Example-2image_file.save("image_name3.jpg", quality=1)
Original Image:
Output:
Default/High resolution (Quality=95):
Medium Resolution (Quality=25):
Low Resolution (Quality=1):
Python-pil
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions