code-rag-bench/online-tutorials huggingface dataset:
Print 2D matrix in different lines and without curly braces in C/C++? - GeeksforGeeks

09 May, 2022
Following is a general way of printing 2D matrix such that every row is printed in separate lines. 
C
for (int i = 0; i < m; i++){   for (int j = 0; j < n; j++)   {      cout << arr[i][j] << " ";   }       // Newline for new row   cout << endl;}
How to print without using any curly braces in for loops?   We strongly recommend you to minimize your browser and try this yourself first.   We can simply removed inner curly bracket as there is single line inner for loop. How to remove outer curly braces? Below is solution. 
C
// C++ program to print a matrix line by line without// using curly braces.#include<iostream>using namespace std; int main(){    int m = 2, n = 3;    int mat[][3] = { {1, 2, 3},                    {4, 5, 6},                  };    for (int i = 0; i < m; i++)       for (int j = 0; j < n; j++)           // Prints ' ' if j != n-1 else prints '\n'                   cout << mat[i][j] << " \n"[j == n-1];     return 0;}
Output:
1 2 3
4 5 6
The actual trick is in following statement “\n”[j == n-1], explanation is as follows: ” \n” is a 2 character string where 1st character is space and 2nd character is newline, so we want space after each value except last for which we want a newline. In C, string literals are treated character arrays [See this for more details]. j == n-1 statement evaluates to 0 for internal elements (because for them j < n-1) and for last value(of each row) it becomes 1. So for internal elements, statement evaluate to ” \n”[0] i.e. ” ” and for last element of each row ” \n”[1] i.e. “\n” Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sweetyty
cpp-array
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
useradd command in Linux with Examples - GeeksforGeeks

26 May, 2020
useradd is a command in Linux that is used to add user accounts to your system. It is just a symbolic link to adduser command in Linux and the difference between both of them is that useradd is a native binary compiled with system whereas adduser is a Perl script which uses useradd binary in the background. It make changes to the following files:
/etc/passwd
/etc/shadow
/etc/group
/etc/gshadow
creates a directory for new user in /home
Syntax:
useradd [options] name_of_the_user
1. To add a simple user
sudo useraddtest_user
This command will add the user named “test_user”.
2. To give a home directory path for new user
sudo useradd -d /home/test_user test_user
This will set the home directory of the us”/home/test_user”.
3. To create a user with specific user id
sudo useradd -u 1234 test_user
This will create a new user with the user-id “1234” and the name “test_user”.
4. To create a user with specific group id
sudo useradd -g 1000 test_user
This will create a new user with the group id “1000” and the name “test_user”.
5. To create a user without home directory
sudo useradd -M test_user
This will create the user with the name “test_user” and that too without a home directory.
6. To create a user with expiry date
sudo useradd -e 2020-05-30 test_user
This will create the user named “test_user” with the expiry date of 30th May 2020.
7. To create a user with a comment
sudo useradd -c "This is a test user" test_user
This will create a user with a short comment or description of the user.
8. To create a user with changed login shell
sudo useradd -s /bin/sh test_user
This will create a user named “test_user” with the default shell /bin/sh.
9 To set an unencrypted password for the user
sudo useradd -p test_password test_user
This will create a new user with the name “test_user” and an unencrypted password “test_password”.
10. To display help
sudo useradd --help
This command will display the help section of the useradd command.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
scp command in Linux with Examples
Compiling with g++
GATE | GATE CS 2020 | Question 45 - GeeksforGeeks

26 May, 2021
Consider the following five disk five disk access requests of the form (request id, cylinder number) that are present in the disk scheduler queue at a given time.
(P, 155), (Q, 85), (R, 110), (S, 30), (T, 115) 
Assume the head is positioned at cylinder 100. The scheduler follows Shortest Seek Time First scheduling to service the requests.
Which one of the following statements is FALSE ?(A) T is serviced before P(B) Q is serviced after S, but before T(C) The head reverses its direction of movement between servicing of Q and P(D) R is serviced before PAnswer: (B)Explanation: According to Shortest Seek Time First (SSTF) is a disk scheduling algorithm:
Therefore, option (B) is False.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
Find if two rectangles overlap using C++.

We know that a rectangle can be represented using two coordinates, the top left corner, and the bottom right corner. Suppose there are two rectangles, we have to check whether these two overlap or not. There are four coordinate points (l1, r1) and (l2, r2).
l1 is the top-left corner of first rectangle
r1 is the bottom-right corner of the first rectangle
l2 is the top-left corner of second rectangle
r2 is the bottom-right corner of the second rectangle
We have assumed that the rectangles are parallel to the coordinate axes. To solve this, we have to check a few conditions.
One rectangle is above the top edge of another rectangle
One rectangle is on the left side of the left edge of another rectangle.
 Live Demo
#include<iostream>
using namespace std;
class Point {
   public:
   int x, y;
};
bool isOverlapping(Point l1, Point r1, Point l2, Point r2) {
   if (l1.x > r2.x || l2.x > r1.x)
      return false;
   if (l1.y < r2.y || l2.y < r1.y)
      return false;
   return true;
}
int main() {
   Point l1 = {0, 10}, r1 = {10, 0};
   Point l2 = {5, 5}, r2 = {15, 0};
   if (isOverlapping(l1, r1, l2, r2))
      cout << "Rectangles are Overlapping";
   else
      cout << "Rectangles are not Overlapping";
}
Rectangles are Overlapping
VBScript StrComp Function

The StrComp Function returns an integer value after comparing the two given strings. It can return any of the three values -1, 0 or 1 based on the input strings to be compared.
If String 1 < String 2 then StrComp returns -1
If String 1 < String 2 then StrComp returns -1
If String 1 = String 2 then StrComp returns 0
If String 1 = String 2 then StrComp returns 0
If String 1 > String 2 then StrComp returns 1
If String 1 > String 2 then StrComp returns 1
StrComp(string1,string2[,compare]) 

String1, a Required Parameter. The first String expression.
String1, a Required Parameter. The first String expression.
String2, a Required Parameter. The second String expression.
String2, a Required Parameter. The second String expression.
Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below-mentioned values −

0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison


Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below-mentioned values −
0 = vbBinaryCompare - Performs Binary Comparison(Default)
0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison
1 = vbTextCompare - Performs Text Comparison
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         document.write("Line 1 :" & StrComp("Microsoft","Microsoft") & "<br />")
         document.write("Line 2 :" &StrComp("Microsoft","MICROSOFT") & "<br />")
         document.write("Line 3 :" &StrComp("Microsoft","MiCrOsOfT") & "<br />")
         document.write("Line 4 :" &StrComp("Microsoft","MiCrOsOfT",1) & "<br />")
         document.write("Line 5 :" &StrComp("Microsoft","MiCrOsOfT",0) & "<br />")

      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 :0
Line 2 :1
Line 3 :1
Line 4 :0
Line 5 :1 


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Python | Insert the string at the beginning of all items in a list - GeeksforGeeks

20 Nov, 2019
Given a list, write a Python program to insert some string at the beginning of all items in that list.
Examples:
Input : list = [1, 2, 3, 4], str = 'Geek'
Output : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']

Input : list = ['A', 'B', 'C'], str = 'Team'
Output : list = ['TeamA', 'TeamB', 'TeamC']

There are multiple ways to insert the string at the beginning of all items in a list.
Approach #1 : Using list comprehensionList comprehension is an elegant way to define and create list. It can also be used to apply an expression to each element in a sequence. We can use format() function which allows multiple substitutions and value formatting.
# Python3 program to insert the string # at the beginning of all items in a listdef prepend(list, str):          # Using format()    str += '{0}'    list = [str.format(i) for i in list]    return(list)  # Driver functionlist = [1, 2, 3, 4]str = 'Geek'print(prepend(list, str))
Output:
['Geek1', 'Geek2', 'Geek3', 'Geek4']
Another method in list comprehension is to use ‘%’ instead of format() function
# Using '% s'str += '% s'list =  [str % i for i in list]
 Approach #2 : Using in-built map() functionAnother approach is to use map() function. The function maps the beginning of all items in the list to the string.
# Python3 program to insert the string # at the beginning of all items in a listdef prepend(List, str):           # Using format()    str += '{0}'    List = ((map(str.format, List)))    return List   # Driver functionlist = [1, 2, 3, 4]str = 'Geek'print(prepend(list, str))
Output:
['Geek1', 'Geek2', 'Geek3', 'Geek4']
ManasChhabra2
Python list-programs
python-list
python-string
Python
python-list
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Add a custom border to certain cells in a Matplotlib / Seaborn plot

To add a custom border to certain cells in a Matplotlib/Seaborn plot.
Set the figure size and adjust the padding between and around the subplots.
Create a dataframe with some columns.
Plot a matrix dataset as a hierarchically-clustered heatmap.
Get heatmap axis as a subplot arrangement.
To add a custom border to certain cells in Matplotlib, we can intialize a variable, border_color.
Using custom bordder color, add a rectangle patch on the heatmap axes.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({"col1": [1, 4, 2, 3, 5], "col2": [3, 4, 1, 5, 2]})
g = sns.clustermap(df, figsize=(7.50, 3.50))
ax = g.ax_heatmap
border_color = "yellow"
ax.add_patch(plt.Rectangle((1, 2), 2, 1, fill=False,
edgecolor=border_color, lw=5))
plt.show()
How can we use SET statement to assign a SELECT result to a MySQL user variable?

For using the SET statement to assign a SELECT result to a user variable we need to write the SELECT statement as a subquery within parentheses. The condition is that the SELECT statement must have to return a single value. To make it understand we are using the data from ‘Tender’ table which is as follows −
mysql> select * from Tender;
+----+---------------+--------------+
| Sr | CompanyName   | Tender_value |
+----+---------------+--------------+
| 1  | Abc Corp.     | 250.369003   |
| 2  | Khaitan Corp. | 265.588989   |
| 3  | Singla group. | 220.255997   |
| 4  | Hero group.   | 221.253006   |
| 5  | Honda group   | 225.292266   |
+----+---------------+--------------+
5 rows in set (0.04 sec)
Now, in the following query, we are setting the maximum value, after rounding it up to 2 decimal point, of tender_value to the variable @Val_Max.
mysql> SET @Val_Max = (SELECT ROUND(MAX(tender_value),2) from tender);
Query OK, 0 rows affected (0.00 sec)

mysql> Select @Val_Max;
+----------+
| @Val_Max |
+----------+
| 265.59   |
+----------+
1 row in set (0.00 sec)
Python String | rpartition() - GeeksforGeeks

17 Jun, 2021
rpartition() function in Python split the given string into three parts. rpartition() start looking for separator from right side, till the separator is found and return a tuple which contains part of the string before separator, argument of the string and the part after the separator.
Syntax : 
string.rpartition(separator)
Parameters :  
separator -  separates the string at the first occurrence of it.
Return Value :  
It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string.It returns two empty strings, followed by the given string if the separator is not found in the string.
It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string.
It returns two empty strings, followed by the given string if the separator is not found in the string.
Exception :  
If separator argument is not supplied, it will throw TypeError.
Code #1 :  
Python3
# Python3 code explaining rpartition() # String need to splitstring1 = "Geeks@for@Geeks@is@for@geeks" string2 = "Ram is not eating but Mohan is eating" # Here '@' is a separatorprint(string1.rpartition('@')) # Here 'is' is separatorprint(string2.rpartition('is'))
Output : 
('Geeks@for@Geeks@is@for', '@', 'geeks')
('Ram is not eating but Mohan ', 'is', ' eating')
Code #2 :  
Python3
# Python3 code explaining rpartition() # String need to splitstring = "Sita is going to school" # Here 'not' is a separator which is not# present in the given stringprint(string.rpartition('not'))
Output : 
('', '', 'Sita is going to school')
Code #3 : TypeError  
Python3
# Python3 code explaining TypeError# in rpartition() str = "Bruce Waine is Batman" # Nothing is passed as separatorprint(str.rpartition())
Output : 
Traceback (most recent call last):
  File "/home/e207c003f42055cf9697001645999d69.py", line 7, in 
    print(str.rpartition())
TypeError: rpartition() takes exactly one argument (0 given)
Code #4 : ValueError  
Python3
# Python3 code explaining ValueError# in rpartition() str = "Bruce Waine is Batman" # Nothing is passed as separatorprint(str.rpartition(""))
Output : 
Traceback (most recent call last):
  File "/home/c8d9719625793f2c8948542159719007.py", line 7, in 
    print(str.rpartition(""))
ValueError: empty separator
 
anikakapoor
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
AngularJS | ng-init Directive - GeeksforGeeks

28 Mar, 2019
The ng-init directive is used to initialize an AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables.The ng-init directive defines initial values and variables for an AngularJS application.
Syntax:
<element ng-init = "expression">
   ...
</element>

Example: In this example, we initialize an array of string.
<html>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/    angular.min.js"></script>    <head>        <title>AngularJS ng-init Directive</title>    </head>    <body>            <h1 style = "color:green">GeeksforGeeks            <h2>ng-init directive</h2>            <div ng-app="" ng-init="sort=['quick sort', 'merge sort',             'bubble sort']">             Sorting techniques:            <ul>            <li>{{ sort[0] }} </li>            <li>{{ sort[1] }} </li>            <li>{{ sort[2] }} </li>            </ul>         </div>    </body></html>
Output:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to clear the memory completely of all Matplotlib plots?

Using the following methods, we can clear the memory occupied by Matplotlib plots.
plt.figure() - Create a new figure or activate an existing figure.
plt.figure() - Create a new figure or activate an existing figure.
plt.figure().close() -  Close a figure window.close() by itself closes the current figureclose(h), where h is a Figure instance, closes that figureclose(num) closes the figure number, numclose(name), where name is a string, closes figure with that labelclose('all') closes all the figure windows
plt.figure().close() -  Close a figure window.
close() by itself closes the current figure
close() by itself closes the current figure
close(h), where h is a Figure instance, closes that figure
close(h), where h is a Figure instance, closes that figure
close(num) closes the figure number, num
close(num) closes the figure number, num
close(name), where name is a string, closes figure with that label
close(name), where name is a string, closes figure with that label
close('all') closes all the figure windows
close('all') closes all the figure windows
plt.figure().clear() - It is the same as clf.
plt.figure().clear() - It is the same as clf.
plt.cla() - Clear the current axes.
plt.cla() - Clear the current axes.
plt.clf() - Clear the current figure.
plt.clf() - Clear the current figure.
from matplotlib import pyplot as plt
fig = plt.figure()
plt.figure().clear()
plt.close()
plt.cla()
plt.clf()
When we execute the code, it will clear all the plots from the memory.
How to create a modal dialog in tkinter?

Dialog Boxes are a very essential component of any application. It is generally used to interact with the user and the application interface. We can create dialog boxes for any tkinter application using the Toplevel window and other widgets. The toplevel window pops up the stuff above all the other windows. Thus, we can add more stuff on the toplevel window for building dialog boxes.
In this example, we have created a modal dialog which has two parts,
Initialization of the Toplevel window.
Function Definition for Popup Dialog Event.
Adding widgets in the Toplevel window.
Function Definition for Dialog options.
# Import required libraries
from tkinter import *
from tkinter import ttk

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

# Set the window size
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')

# Define a function to implement choice function
def choice(option):
   pop.destroy()
   if option == "yes":
      label.config(text="Hello, How are You?")
   else:
      label.config(text="You have selected No")
      win.destroy()
def click_fun():
   global pop
   pop = Toplevel(win)
   pop.title("Confirmation")
   pop.geometry("300x150")
   pop.config(bg="white")
   # Create a Label Text
   label = Label(pop, text="Would You like to Proceed?",
   font=('Aerial', 12))
   label.pack(pady=20)
   # Add a Frame
   frame = Frame(pop, bg="gray71")
   frame.pack(pady=10)
   # Add Button for making selection
   button1 = Button(frame, text="Yes", command=lambda: choice("yes"), bg="blue", fg="white")
   button1.grid(row=0, column=1)
   button2 = Button(frame, text="No", command=lambda: choice("no"), bg="blue", fg="white")
   button2.grid(row=0, column=2)
# Create a Label widget
label = Label(win, text="", font=('Aerial', 14))
label.pack(pady=40)

# Create a Tkinter button
ttk.Button(win, text="Click Here", command=click_fun).pack()

win.mainloop()
When we run the above code, it will display a window with a Button to open the modal dialog box.
Clicking the Button will open the Modal Dialog Box.
C++ Array Library - get() Function

The C++ function std::array::get(std::array) Returns reference to the Ith element of the array container.
Following is the declaration for std::array::get(std::array) function form std::array header.
template <size_t I, class T, size_t N> T& get (array<T,N>& arr) noexcept;
template <size_t I, class T, size_t N> T&& get (array<T,N>&& arr) noexcept;
template <size_t I, class T, size_t N> const T& get (const array<T,N>& arr) noexcept;
I − position of an element in the array, with 0 as the position of the first element.
I − position of an element in the array, with 0 as the position of the first element.
T − type of elements contained in the array.
T − type of elements contained in the array.
arr − an array container.
arr − an array container.
A reference to the element at the specified position in the array.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::array::get(std::array) function.
#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 3> arr = {10, 20, 30};

   cout << "arr[0] = " << get<0>(arr) << "\n";
   cout << "arr[1] = " << get<1>(arr) << "\n";
   cout << "arr[2] = " << get<2>(arr) << "\n";

   return 0;
}
Let us compile and run the above program, this will produce the following result −
arr[0] = 10
arr[1] = 20
arr[2] = 30

 Print
 Add Notes
 Bookmark this page
Removing whitespaces using C# Regex

Let’s say we want to remove whitespace from the following string str1.
string str1 = "Brad Pitt";
Now, use Regex Replace to replace whitespace with empty. Here, we have used System.Text.RegularExpressions.
string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
Let us see the complete example.
 Live Demo
using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string str1 = "Brad Pitt";
         Console.WriteLine(str1);
         string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
         Console.WriteLine(str2);
      }
   }
}
Brad Pitt
BradPitt
How to get row index based on a value of an R data frame column?

A row of an R data frame can have multiple ways in columns and these values can be numerical, logical, string etc. It is easy to find the values based on row numbers but finding the row numbers based on a value is different. If we want to find the row number for a particular value in a specific column then we can extract the whole row which seems to be a better way and it can be done by using single square brackets to take the subset of the row.
Consider the below data frame −
 Live Demo
x1<-rnorm(20,0.5)
x2<-rpois(20,2)
x3<-rpois(20,5)
x4<-rpois(20,10)
x5<-rnorm(20,2)
df<-data.frame(x1,x2,x3,x4,x5)
df
      x1       x2 x3  x4      x5
1 1.33780769    1 5    1    3.3322153
2 2.22651263    3 5    14   3.4969403
3 0.53231950    4 9    8    3.7816594
4 0.99704756    1 6    13    2.7308284
5 0.37735760    2 5    7     2.3210021
6 0.96967898    3 7    8     1.9086576
7 0.06543569    2 4    9    1.4005479
8 1.59064892    1 8    14    1.1250329
9 0.48771130    1 4    11    2.2479028
10 0.64134261   0 9    5    2.4194513
11 0.43355439   3 2    18    -0.7633724
12 1.31803573   3 4    10    2.6201427
13 0.25367683   3 6    9    1.5728880
14 1.07884550   5 4    9    0.8045540
15 0.78574641   6 6    8    1.3538888
16 -0.27873444  2 6    12    3.5431787
17 0.28112519   2 3    8    4.1865617
18 1.24416762   4 4    11    2.3626763
19 -0.04745463  2 5    13    3.4203297
20 1.33358241   1 9    14    2.8205837
Finding the rows that will also return row indexes for a value −
df[df$x4==14,]
      x1   x2 x3 x4 x5
2 2.226513  3 5  14 3.496940
8 1.590649  1 8  14 1.125033
20 1.333582 1 9  14 2.820584
df[df$x4==12,]
      x1     x2  x3  x4   x5
16 -0.2787344 2  6   12 3.543179
df[df$x4==7,]
      x1    x2  x3 x4    x5
5 0.3773576 2   5   7 2.321002
df[df$x4==9,]
      x1       x2 x3 x4    x5
7 0.06543569    2 4   9    1.400548
13 0.25367683   3 6   9    1.572888
14 1.07884550   5 4   9    0.804554
df[df$x2==2,]
      x1       x2 x3 x4    x5
5 0.37735760    2 5   7    2.321002
7 0.06543569    2 4   9    1.400548
16 -0.27873444  2 6   12   3.543179
17 0.28112519   2 3   8    4.186562
19 -0.04745463  2 5   13    3.420330
df[df$x2==5,]
      x1    x2 x3 x4   x5
14 1.078845 5   4  9  0.804554
df[df$x2==4,]
      x1    x2 x3 x4   x5
3 0.5323195 4   9 8  3.781659
18 1.2441676 4  4 11 2.362676
df[df$x3==4,]
      x1    x2 x3  x4    x5
7 0.06543569 2 4   9    1.400548
9 0.48771130 1 4  11   2.247903
12 1.31803573 3 4 10   2.620143
14 1.07884550 5 4  9    0.804554
18 1.24416762 4 4 11   2.362676
df[df$x3==6,]
      x1    x2 x3 x4    x5
4 0.9970476 1   6 13  2.730828
13 0.2536768 3  6 9   1.572888
15 0.7857464 6  6 8   1.353889
16 -0.2787344 2 6 12  3.543179
df[df$x3==5,]
      x1    x2 x3 x4 x5
1 1.33780769 1 5  1 3.332215
2 2.22651263 3 5 14 3.496940
5 0.37735760 2 5  7 2.321002
19 -0.04745463 2 5 13 3.420330
df[df$x3==8,]
      x1   x2 x3 x4 x5
8 1.590649 1  8 14 1.125033
df[df$x2==1,]
      x1    x2 x3  x4   x5
1 1.3378077 1   5  1  3.332215
4 0.9970476 1   6  13  2.730828
8 1.5906489 1   8  14  1.125033
9 0.4877113 1   4  11  2.247903
20 1.3335824 1  9  14  2.820584
AWK - String Concatenation Operator

Space is a string concatenation operator that merges two strings. The following example demonstrates this −
[jerry]$ awk 'BEGIN { str1 = "Hello, "; str2 = "World"; str3 = str1 str2; print str3 }'
On executing this code, you get the following result −
Hello, World

 Print
 Add Notes
 Bookmark this page
Same Tree in C++

Suppose we have two binary trees; we have to define a function to check whether they are the same or not. We know that the binary trees are considered the same when they are structurally identical and the nodes have the same value.
So, if the input is like [1,2,3],[1,2,3], then the output will be True
To solve this, we will follow these steps −
Define a function called isSameTree, this will take two tree nodes p and q
Define a function called isSameTree, this will take two tree nodes p and q
if p is the same as NULL and q is same as NULL, then −return true
if p is the same as NULL and q is same as NULL, then −
return true
return true
if p is the same as NULL or q is same as NULL, then −return false
if p is the same as NULL or q is same as NULL, then −
return false
return false
if val of p is the same as val of p and isSameTree(left of p, left of q) is true and
isSameTree(right of p, right of q) is true, thenreturn true
if val of p is the same as val of p and isSameTree(left of p, left of q) is true and
isSameTree(right of p, right of q) is true, then
return true
return true
return false
return false
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
      int val;
      TreeNode *left, *right;
      TreeNode(int data){
         val = data;
         left = NULL;
         right = NULL;
      }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
      }
      else{
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
         return;
      }
      else{
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class Solution {
public:
   bool isSameTree(TreeNode *p, TreeNode* q){
      if (p == NULL && q == NULL)
         return true;
      if (p == NULL || q == NULL)
         return false;
      if (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
         return true;
      return false;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3}, v1 = {1,2,3};
   TreeNode *root1 = make_tree(v);
   TreeNode *root2 = make_tree(v1);
   cout << (ob.isSameTree(root1, root2));
}
{1,2,3}, {1,2,3}
1
How can we change the data type of the column in MySQL table?

It can be done with the help of ALTER TABLE command of MySQL. Consider the table ‘Student’ in which the data type of ‘RollNo’ column is declared as Integer, can be seen from the following query −
mysql> DESCRIBE Student;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Name   | varchar(20) | YES  |     | NULL    |       |
| RollNo | int(11)     | YES  |     | NULL    |       |
| Grade  | varchar(50) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.06 sec)
Now suppose we want to change the data type of RollNo from Int(11) to Varchar(10) the following query will do it −
mysql> Alter Table student Modify column RollNo Varchar(10);
Query OK, 3 rows affected (0.25 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> Desc Student;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Name   | varchar(20) | YES  |     | NULL    |       |
| RollNo | varchar(10) | YES  |     | NULL    |       |
| Grade  | varchar(10) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.06 sec)
From the query above it can be observed that the data type of RollNo has been changed from integer to varchar.
Ant - Environment Setup

Apache Ant is distributed under the Apache Software License which is a fully-fledged open source license certified by the open source initiative.
The latest Apache Ant version, including its full-source code, class files, and documentation can be found at https://ant.apache.org.
It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions available at file:///C:/java/java_environment_setup.htm
Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed.
Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed.
Download the binaries from https://ant.apache.org
Download the binaries from https://ant.apache.org
Unzip the zip file to a convenient location c:\folder by using Winzip, winRAR, 7-zip or similar tools.
Unzip the zip file to a convenient location c:\folder by using Winzip, winRAR, 7-zip or similar tools.
Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\apache-ant-1.10.12-bin folder.
Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\apache-ant-1.10.12-bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\apache-ant-1.10.12-bin\bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\apache-ant-1.10.12-bin\bin folder.
To verify the successful installation of Apache Ant on your computer, type ant on your command prompt.
You should see an output as given below −
C:\>ant -version
Apache Ant(TM) version 1.10.12 compiled on October 13 2021

If you do not see the above output, then please verify that you have followed the installation steps properly.
This tutorial also covers integration of Ant with Eclipse integrated development environment (IDE). Hence, if you have not installed Eclipse, please download and install Eclipse.
Download the latest Eclipse binaries from www.eclipse.org
Download the latest Eclipse binaries from www.eclipse.org
Unzip the Eclipse binaries to a convenient location, say c:\folder.
Unzip the Eclipse binaries to a convenient location, say c:\folder.
Run Eclipse from c:\eclipse\eclipse.exe.
Run Eclipse from c:\eclipse\eclipse.exe.

    20 Lectures 
     2 hours 

 Deepti Trivedi

    19 Lectures 
     2.5 hours 

 Deepti Trivedi

    139 Lectures 
     14 hours 

 Er. Himanshu Vasishta

    30 Lectures 
     1.5 hours 

 Pushpendu Mondal

    65 Lectures 
     6.5 hours 

 Ridhi Arora

    10 Lectures 
     2 hours 

 Manish Gupta
 Print
 Add Notes
 Bookmark this page
C# Program to get the smallest and largest element from a list

Set a list.
List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };
To get the smallest element, use the Min() method.
list.AsQueryable().Min();
To get the largest element, use the Max() method.
list.AsQueryable().Max();
Let us see the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };
      foreach(long ele in list){
         Console.WriteLine(ele);
      }

      // getting largest element
      long max_num = list.AsQueryable().Max();

      // getting smallest element
      long min_num = list.AsQueryable().Min();

      Console.WriteLine("Smallest number = {0}", min_num);
      Console.WriteLine("Largest number = {0}", max_num);
   }
}
150
300
400
350
450
550
600
Smallest number = 150
Largest number = 600
Retrieving array values from a find query in MongoDB?

To retrieve array values, use dot(.) notation. Let us first create a collection with documents −
> db.retrievingArrayDemo.insertOne(
   { "UserDetails" : [
      { "UserName" : "John", "UserAge" : 23 } ],
      "UserCountryName" : "AUS",
      "UserLoginDate" : new ISODate(),
      "UserMessage" : "Hello"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9718478f00858fb12e920")
}
> db.retrievingArrayDemo.insertOne(
   { "UserDetails" : [
      { "UserName" : "Sam", "UserAge" : 24 } ],
      "UserCountryName" : "UK",
      "UserLoginDate" : new ISODate(),
      "UserMessage" : "Bye"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9718478f00858fb12e921")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.retrievingArrayDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ce9718478f00858fb12e920"),
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserAge" : 23
      }
   ],
   "UserCountryName" : "AUS",
   "UserLoginDate" : ISODate("2019-05-25T16:47:00.211Z"),
   "UserMessage" : "Hello"
}
{
   "_id" : ObjectId("5ce9718478f00858fb12e921"),
   "UserDetails" : [
      {
         "UserName" : "Sam",
         "UserAge" : 24
      }
   ],
   "UserCountryName" : "UK",
   "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
   "UserMessage" : "Bye"
}
Following is the query to retrieve array values from a find query −
> db.retrievingArrayDemo.find({"UserCountryName" : "UK", "UserDetails.UserName":"Sam"}).pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ce9718478f00858fb12e921"),
   "UserDetails" : [
      {
         "UserName" : "Sam",
         "UserAge" : 24
      }
   ],
   "UserCountryName" : "UK",
   "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
   "UserMessage" : "Bye"
}
Introduction to URLSearchParams API in Node.js

Node is an open source project that is used to create dynamic web applications. The URLSearchParams API is an interface. It defines different utility that is required to work with the query string of the URL.
In this article, we will discuss the four different constructors of URLSearchParams that can be used as per the requirement.
This is a no argument constructor and therefore only used to initialize a new Empty URLSearchParams() object.
var params = new URLSearchParams();
This constructor can accept a string as an input parameter along with instantiating a new URLSearchParams object.
const params = new URLSearchParams('firstName=pqr & lastName=xyz');
   console.log(params.get('firstName'));
   console.log(params.get('lastName'));
pqr
xyz
This contructor accepts an object as an input parameter with a collection of key-value pairs to initialize a new URL. The key-value pair are always converted to string type. Duplicate keys are not allowed.
const params = new URLSearchParams({
   user: 'John',
   subjects: ['Physics', 'Chemistry', 'Maths']
});
console.log(params.toString());
user=John&subjects=Physics%2CChemistry%2CMaths
This contructor accepts an iterable object that contains a collection of key-value pairs to initialize a new URLSearchParams object. Since URLSearchParams is itself an iterable an object, therefore we can have another iterable URLSearchParams inside new URLSearchParams(). Duplicate keys are allowed inside this.
const map = new Map();
   map.set('Taj Mahal', 'Agra');
   map.set('Qutub Minar', 'Delhi');
   map.set('Gateway of India', 'Mumbai');
   params = new URLSearchParams(map);
   console.log(params.toString());
Taj+Mahal=Agra&Qutub+Minar=Delhi&Gateway+of+India=Mumbai
What does 'show processlist' command do in MySQL?

The ‘SHOW processlist’ command can be used to display the running thread related to only your MySQL account. We can see almost all running threads if we have process privileges. It shows which threads are running.
The following is the query.
mysql> SHOW processlist;
Here is the output.
+----+-----------------+-----------------+------+---------+------+------------------------+------------------+
| Id | User            | Host            | db   | Command | Time | State                  | Info             |
+----+-----------------+-----------------+------+---------+------+------------------------+------------------+
|  4 | event_scheduler | localhost       | NULL | Daemon  |  968 | Waiting on empty queue | NULL             |
|  9 | root            | localhost:50255 | NULL | Query   |    0 | starting               | show processlist |
+----+-----------------+-----------------+------+---------+------+------------------------+------------------+
2 rows in set (0.00 sec)

If we change the database, then the output will be different, but there will always be the following two users: ‘event_scheduler’ and ‘root’.
Let us try the query again.
mysql> SHOW processlist;
The following is the output.
+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+
| Id | User            | Host            | db       | Command | Time | State                  | Info             |
+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+
|  4 | event_scheduler | localhost       | NULL     | Daemon  | 1148 | Waiting on empty queue | NULL             |
|  9 | root            | localhost:50255 | business | Query   |    0 | starting               | show processlist |
+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+
2 rows in set (0.00 sec)
How to add a list elements within an unordered list element using jQuery ? - GeeksforGeeks

14 Apr, 2021
Here in this article, we will see that how we can add a list to the Unordered List using jQuery. So the function which we had used to append the items in the list are –
<script>
    $(document).ready(function() {
        $('.btn').click(function(){
            var content = $('#addList').val();
            var fixingContent='<li>'+content+'</li>';
            $('.List').append(fixingContent);
        })
    }) 
</script>
Approach: First, we create a button that provides the functionality to add the items to the list.
When the button is clicked then through the button ID we will be first store the input from the textBox to the variable content having it’s value then simply put the content in the var fixingContent='<li><span>’+content+'</span></li>’ 
After that, we just append the content to the list having a class named list.
Code Implementation:
HTML
<!DOCTYPE html><html lang="en">  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">    </script>      <style>        .btn {            width: 66px;            height: 21px;            margin: 5px;            padding: 0px;            border-color: #b6b6bb;        }                  #addList {            border-color: rgb(183, 252, 252);        }    </style>          <script>        $(document).ready(function() {            $('.btn').click(function() {                var content = $('#addList').val();                var fixingContent =                     '<li>' + content + '</li>';                                      $('.List').append(fixingContent);            })        })    </script></head>    <body>    <h3 class="head"> Type List to Add</h3>    <input type="text" id="addList">    <input type="button" name="add"         class="btn" value="Add">    </button>      <div class="addTask">        <ul class="List">          </ul>    </div></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML-Questions
HTML-Tags
jQuery-Methods
jQuery-Questions
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
How to auto-resize an image to fit a div container using CSS?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to Dynamically Add/Remove Table Rows using jQuery ?
How to change the background color after clicking the button in JavaScript ?
Reading images using Python?

OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.
With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & recognization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.
In this I'll try to explain how we can use OpenCV library and python to read and display image. This is implemented using cv2 and Numpy modules.
You can download numpy module from the Python Package Index(PyPI).
$ pip install numpy
We use cv2.imread() function to read an image. The image should be placed in the current working directory or else we need to provide the absoluate path.
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('Top-bike-wallpaper.jpg',0)
To display an image in a window, use cv2.imshow() function.
#Display the image
cv2.imshow('image',img)
#key binding function
cv2.waitKey(0)
#Destroyed all window we created earlier.
cv2.destroyAllWindows()
On running above code, a screenshot of the window will look like this,
Use the function cv2.imwrite() to save an image.
First argument is the file name, second argument is the image you want to save.
cv2.imwrite('messigray.png',img)
Sum it up −
import numpy as np
import cv2

#Read the Image
# Load an color image in grayscale
img = cv2.imread('Top-bike-wallpaper.jpg',0)

#Display the image
cv2.imshow('image',img)

#key binding function
k = cv2.waitKey(0)

# wait for ESC key to exit
if k == 27:
   cv2.destroyAllWindows()
# wait for 's' key to save and exit
elif k == ord('s'):
   cv2.imwrite('myBike.jpg',img)
   cv2.destroyAllWindows()
Save the image by pressing 's' or press 'ESC' key to simply exit without saving.
The Python Imaging Library (PIL) is image manipulation library in python. Use pip to install PIL library,
$ pip install Pillow
from PIL import Image, ImageFilter
#Read image
im = Image.open( 'myBike.png' )

#Display image
im.show()

#Applying a filter to the image
im_sharp = im.filter( ImageFilter.SHARPEN )

#Saving the filtered image to a new file
im_sharp.save( 'another_Bike.jpg', 'JPEG' )
Image is saved in my default location .i.e. currently working directory and a screenshot of the window will display our images.