code-rag-bench/online-tutorials huggingface dataset:
How to return multiple values from function in PHP? - GeeksforGeeks

10 Feb, 2022
PHP doesn’t support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed. However, there are ways to work around this limitation. The multiple values can be returned from a function by using an array.Example 1: This example shows how to return multiple values from a function in PHP. First, create an empty array end push the element to the array and then return the array. 
php
<?php // Function to return the array// of factors of nfunction factors( $n ) {         // Declare an empty array    $fact = array();         // Loop to find the    for ( $i = 1; $i < $n; $i++) {             // Check if i is the factor of        // n then push it into array        if( $n % $i == 0 )            array_push( $fact, $i );    }         // Return the array    return $fact;} // Declare a variable and initialize it$num = 24; // Function call$nFactors = factors($num); // Display the resultecho 'Factors of ' . $num . ' are: <br>'; foreach( $nFactors as $x ) {    echo $x . "<br>";} ?>
Factors of 24 are: 
1
2
3
4
6
8
12
 
Example 2: This example uses list function to store the swapped value of variable. It is used to assign array values to multiple variables at the same time. The multiple values returned in array from the function can be assigned to corresponding variables using list(). 
php
<?php // Function to swap two numbersfunction swap( $x, $y ) {    return array( $y, $x );} // Declare variable and initialize it$a = 10;$b = 20; echo 'Before swapping the elements <br>'; // Display the value of a and becho 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>'; // Function call to swap the value of a and blist($a, $b) = swap($a, $b); echo 'After swapping the elements <br>'; // Display the value of a and becho 'a = ' . $a . '<br>' . 'b = ' . $b . '<br>'; ?>
Before swapping the elements 
a = 10
b = 20
After swapping the elements 
a = 20
b = 10
 
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
shubham_singh
sagar0719kumar
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
How to get parameters from a URL string in PHP?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
How to get parameters from a URL string in PHP?
How to fire jQuery events with setTimeout?

The jQuery setTimeout() method is used to set an interval for events to fire.
Here, we will set an interval of 3 seconds for an alert box to load using jQuery events:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button1").click(function(){
       setTimeout("alert('Hello World!');", 3000);
    });
});
</script>
</head>
<body>

<button id="button1">Click</button>
<p>Click the above button and wait for 3 seconds. An alert box will generate after 3 seconds.</p>

<p></p>
</body>
</html>
Priority Queues with C#

A priority queue is held information with a priority value. It is an extension of queue.
The item with the highest property is removed first when you try to eliminate an item from a priority queue.
Let us see how to set priority queue −
public class MyPriorityQueue <T> where T : IComparable <T> {

}
Now let us add an item. In the below example the items get stored in info, which is a generic list.
public class MyPriorityQueue <T> where T : IComparable <T> {
   private List <T> info;

   public MyPriorityQueue() {
      this.info = new List <T>();
   }
}
How to embed tables in New Google Sites ? - GeeksforGeeks

10 Sep, 2020
Sometimes, we have to display some data in a systematic manner, to do so we use tables. To embed the table in Google sites follow the steps:
Select embed option from the insert panel and then go to embed code division of the dialogue box appeared.
Write your iframe code in the space provided.
To insert a border-less table use the following code:
HTML
<body>    <h2>Test Scores</h2>    <table style="width:100%">        <tr>            <th>Geek Name</th>            <th>Score</th>        </tr>        <tr>            <td>Geek 1</td>            <td>50</td>        </tr>        <tr>            <td>Geek 2</td>              <td>94</td>        </tr>      </table></body>
To add a bordered table just use the following code:
HTML
<head>    <style>        table,        th,        td {            border: 1px solid black;        }    </style></head>  <body>    <h2>Test Scores</h2>    <table style="width:100%">        <tr>            <th>Geek Name</th>            <th>Score</th>        </tr>        <tr>            <td>Geek 1</td>            <td>50</td>        </tr>        <tr>            <td>Geek 2</td>            <td>94</td>        </tr>    </table></body>
To add a table with some background color use the following code:
HTML
<head>    <style>        table,        th,        td {            border: 1px solid black;            border-collapse: collapse;        }          th,        td {            padding: 15px;            text-align: left;            background-color: lightGreen;        }    </style></head>  <body>    <h2>Test Scores</h2>    <table style="width:100%">        <tr>            <th>Geek Name</th>            <th>Score</th>        </tr>        <tr>            <td>Geek 1</td>            <td>50</td>        </tr>        <tr>            <td>Geek 2</td>            <td>94</td>        </tr>    </table></body>
You can change the style and content of the table as per your requirement.
Google Sites
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
File uploading in React.js
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ?
Python | Column deletion from list of lists - GeeksforGeeks

26 Feb, 2019
The problem of removing a row from a list is quite simple and we just need to pop a list out of list of lists. But there can be a utility where we need to delete a column i.e particular index element of each of the list. This is problem that can occur if we store any database data into containers. Let’s discuss certain ways in which this can be performed.
Method #1 : Using del + loopIn this strategy, we just delete the column element one by one using a loop to iterate the row number at each of the iteration.
# Python3 code to demonstrate # deleting columns of list of lists# using del + loop  # initializing list test_list = [[4, 5, 6, 8],             [2, 7, 10, 9],             [12, 16, 18, 20]]  # printing original listprint ("The original list is : " + str(test_list))  # using del + loop# deleting column element of rowfor j in test_list:    del j[1]  # printing result print ("The modified mesh after column deletion : " +  str(test_list))
Output :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
 
Method #2 : Using pop() + list comprehensionWe can do this particular task in an easier and shorter way using the list comprehension technique and using the pop function which can be used to remove the list element.
# Python3 code to demonstrate # deleting columns of list of lists# using pop() + list comprehension  # initializing list test_list = [[4, 5, 6, 8],             [2, 7, 10, 9],             [12, 16, 18, 20]]  # printing original listprint ("The original list is : " + str(test_list))  # using pop() + list comprehension# deleting column element of row[j.pop(1) for j in test_list]  # printing result print ("The modified mesh after column deletion : " +  str(test_list))
Output :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
Python list-programs
Python
Python Programs
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
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
X of a Kind in a Deck of Cards in C++

Suppose we have a deck of cards, each card has an integer written on it. We have to check whether we can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where the following condition satisfies: Each group has exactly X number of cards. All of the cards in each group have the same number.
So, if the input is like deck = [1,2,3,4,4,3,2,1], then the output will be True, as possible partitions are [1,1],[2,2],[3,3],[4,4].
To solve this, we will follow these steps −
Define one map mp
for all x in deck(increase mp[x] by 1)
(increase mp[x] by 1)
for all key-value pair x in mpans := gcd of (ans and value of x)
ans := gcd of (ans and value of x)
return true when ans > 1, otherwise false
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool hasGroupsSizeX(vector<int>& deck) {
      unordered_map<int, int> mp;
      int ans;
      for (auto x : deck)
         mp[x]++;
      for (auto x : mp)
         ans = __gcd(ans, x.second);
      return (ans > 1);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,4,3,2,1};
   cout << (ob.hasGroupsSizeX(v));
}
{1,2,3,4,4,3,2,1}
1
Python – Add Custom Column to Tuple list

10 Jun, 2020
Sometimes, while working with Python records, we can have a problem in which we need to add custom column to tuples list. This kind of problem can have application in data domains such as web development. Lets discuss certain ways in which this task can be performed.
Input :test_list = [(3, ), (7, ), (2, )]cus_eles = [7, 8, 2]Output : [(3, 7), (7, 8), (2, 2)]
Input :test_list = [(3, 9, 6, 10)]cus_eles = [7]Output : [(3, 9, 6, 10, 7)]
Method #1 : Using list comprehension + zip()The combination of above functionalities can be used to solve this problem. In this, we perform the pairing of custom elements and tuples with the help of zip().
# Python3 code to demonstrate working of # Add Custom Column to Tuple list# Using list comprehension + zip()  # initializing listtest_list = [(3, 4), (78, 76), (2, 3)]  # printing original listprint("The original list is : " + str(test_list))  # initializing add listcus_eles = [17, 23, 12]  # Add Custom Column to Tuple list# Using list comprehension + zip()res = [sub + (val, ) for sub, val in zip(test_list, cus_eles)]  # printing result print("The tuples after adding elements : " + str(res)) 
The original list is : [(3, 4), (78, 76), (2, 3)]
The tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]

 
Method #2 : Using map() + lambdaThe combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to each tuple using map() and lambda is used to perform task of addition.
# Python3 code to demonstrate working of # Add Custom Column to Tuple list# Using map() + lambda  # initializing listtest_list = [(3, 4), (78, 76), (2, 3)]  # printing original listprint("The original list is : " + str(test_list))  # initializing add listcus_eles = [17, 23, 12]  # Add Custom Column to Tuple list# Using map() + lambdares = list(map(lambda a, b: a +(b, ), test_list, cur_eles))  # printing result print("The tuples after adding elements : " + str(res)) 
The original list is : [(3, 4), (78, 76), (2, 3)]
The tuples after adding elements : [(3, 4, 17), (78, 76, 23), (2, 3, 12)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
String Class stripTrailing() Method in Java with Examples

02 Feb, 2021
This method is used to strip trailing whitespaces from the string i.e stripTrailing() method removes all the whitespaces only at the ending of the string. 
Example:
Input:

String name = "   kapil   ";
System.out.println("#" + name + "#);
System.out.println("#" + name.stripLeading());


Output:

#   kapil   #
#   kapil# // trailing whitespaces are removed 
Syntax:
public String stripTrailing()
Parameter: It accepts no parameters.
Returns: The string after removing all the whitespaces at the end of the string.
Note: Like the stripTrailing() method in java, we have strip() (removes leading and trailing whitespace) and stripLeading() (removes the only leading whitespace). 
Java
// Java program to demonstrate the usage of// stripTrailing() method in comparison to // other methods  class GFG {    public static void main(String[] args)    {          // creating a string        String str = "  Hello,  World ";          // print the string without any function        System.out.println("String is");        System.out.println("#" + str + "#");        System.out.println();          // using strip() method        System.out.println("Using strip()");        System.out.println("#" + str.strip() + "#");        System.out.println();          // using stripLeading() method        System.out.println("Using stripLeading()");        System.out.println("#" + str.stripLeading() + "#");        System.out.println();          // using stripTrailing() method        System.out.println("Using stripTrailing()");        System.out.println("#" + str.stripTrailing() + "#");    }}
String is
#  Hello,  World #

Using strip()
#Hello,  World#

Using stripLeading()
#Hello,  World #

Using stripTrailing()
#  Hello,  World#

Java-Strings
Picked
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
GATE | GATE CS 2019 | Question 28

07 Sep, 2021
Consider the following given grammar:
S → Aa
A → BD
B → b|ε
D → d|ε 
Let a, b, d and $ be indexed as follows:Compute the FOLLOW set of the non-terminal B and write the index values for the symbols in the FOLLOW set in the descending order. (For example, if the FOLLOW set is {a, b, d, $}, then the answer should be 3210).
Note: This was Numerical Type question.(A) 31(B) 310(C) 230(D) 23Answer: (A)Explanation: Follow (B) to be the set of terminals that can appear immediately to the right of Non-Terminal B in some sentential form.
Therefore,
Follow (B) = {d, a} 
Hence their index in descending order is 31.
PYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0031:30 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" 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
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-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49
Python | Pandas Series.to_dict()

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_dict() function is used to convert the given Series object to {label -> value} dict or dict-like object.
Syntax: Series.to_dict(into=)
Parameter :into : The collections.Mapping subclass to use as the return object.
Returns : value_dict : collections.Mapping
Example #1: Use Series.to_dict() function to convert the given series object to a dictionary.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.to_dict() function to convert the given series object to a dictionary.
# convert to dictionarysr.to_dict()
Output :
As we can see in the output, the Series.to_dict() function has successfully converted the given series object to a dictionary. Example #2: Use Series.to_dict() function to convert the given series object to a dictionary.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])  # Print the seriesprint(sr)
Output :
Now we will use Series.to_dict() function to convert the given series object to a dictionary.
# convert to dictionarysr.to_dict()
Output :
As we can see in the output, the Series.to_dict() function has successfully converted the given series object to a dictionary.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Convert integer to string in Python
Javascript Number() Function

06 Jul, 2020
Below is the example of the Number() function.
Example:<script>    // JavaScript to illustrate    // Number() function    function func() {          // Original string        var a = true;          var value = Number(a);        document.write(value);    }// Driver codefunc();</script> 
<script>    // JavaScript to illustrate    // Number() function    function func() {          // Original string        var a = true;          var value = Number(a);        document.write(value);    }// Driver codefunc();</script> 
Output:1
1
The Number() function is used to convert data type to number.
Syntax:
Number(object)
Parameters: This function accept a single parameter as mentioned above and described below:
object: This parameter holds the objects that will be converted any type of javascript variable to number type.
Return Values: Number() function returns the number format for any type of javascript variable.
Below examples illustrate the Number() function in JavaScript:
Example 1:Input : Number(true);
             Number(false);
Output : 1
         0
Input : Number(true);
             Number(false);
Output : 1
         0
Example 2: Not a number is returned by the compiler.Input : Number("10 20");
Output: NaN
Input : Number("10 20");
Output: NaN
Example 3: The Number() method above returns the number of milliseconds since 1.1.1970.Input : Number(new Date("2017-09-30"));
Output : 1506729600000
Input : Number(new Date("2017-09-30"));
Output : 1506729600000
Example 4:Input : Number("John");
Output : NaN

Input : Number("John");
Output : NaN

More example codes for the above function are as follows:
Program 1:
<script>    // JavaScript to illustrate Number() function    function func() {          // Original string        var a = "10 20";          var value = Number(a);        document.write(value);    }// Driver codefunc();</script>
Output:
NaN
Program 2:
<script>    // JavaScript to illustrate Number() function    function func() {        var value = Number(new Date("2017-09-30"));        document.write(value);    }// Driver codefunc();</script>
Output:
1506729600000
Program 4:
<script>    // JavaScript to illustrate Number() function    function func() {        var value = Number("John");        document.write(value);    }// Driver codefunc();</script>
Output:
NaN
Supported Browsers:
Google Chrome
Firefox
Internet Explorer
Safari
Opera
javascript-functions
JavaScript-Numbers
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python – time.ctime() Method

16 Jul, 2021
Python time.ctime() method converts a time in seconds since the epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). Current time is returned by localtime() is used when the time tuple is not present.
Syntax: time.ctime([ sec ])
Parameter:
sec: number of seconds to be converted into string representation.
Example 1:
Let’s move to the code with an explanation :
Python3
# import moduleimport time # here no parameter is passedprint(time.ctime())
Output:
Thu Mar 18 11:00:19 2021
It prints the standard time equivalent to asctime() method. 
Example 2:
Let’s Have a look at asctime() method:
Python3
# import timeimport time # gives local timea = time.localtime() c = time.asctime(a)print(c)
Output:
Thu Mar 18 11:01:02 2021
Example 3:
Let’s move to another example where we will pass seconds as a parameter to ctime() method.
Python3
# import time moduleimport time # passing number of seconds as# parameter to ctime() methodprint(time.ctime(1615799665.584516))
Output:
Mon Mar 15 14:44:25 2021
Example 4:
Here is another example where we pass a parameter to ctime() method.
Python3
# import time moduleimport time # passing number of seconds as# parameter to ctime() methodprint(time.ctime(1000))
Output:
Thu Jan  1 05:46:40 1970
surindertarika1234
Picked
Python time-module
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Java Program for Tower of Hanoi

16 Jun, 2022
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. 
Java
// Java recursive program to solve tower of hanoi puzzle class GFG{    // Java recursive function to solve tower of hanoi puzzle    static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)    {        if (n == 1)        {            System.out.println("Move disk 1 from rod " +  from_rod + " to rod " + to_rod);            return;        }        towerOfHanoi(n-1, from_rod, aux_rod, to_rod);        System.out.println("Move disk " + n + " from rod " +  from_rod + " to rod " + to_rod);        towerOfHanoi(n-1, aux_rod, to_rod, from_rod);    }         //  Driver method    public static void main(String args[])    {        int n = 4; // Number of disks        towerOfHanoi(n, \'A\', \'C\', \'B\');  // A, B and C are names of rods    }}
Output:
 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 3 from rod A to rod B
 Move disk 1 from rod C to rod A
 Move disk 2 from rod C to rod B
 Move disk 1 from rod A to rod B
 Move disk 4 from rod A to rod C
 Move disk 1 from rod B to rod C
 Move disk 2 from rod B to rod A
 Move disk 1 from rod C to rod A
 Move disk 3 from rod B to rod C
 Move disk 1 from rod A to rod B
 Move disk 2 from rod A to rod C
 Move disk 1 from rod B to rod C
Time Complexity: O(2n)
Auxiliary Space: O(n)
Please refer complete article on Program for Tower of Hanoi for more details!
chandramauliguptach
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65

10 Apr, 2018
The minimum number of comparisons required to find the minimum and the maximum of 100 numbers is ______________.(A) 148(B) 147(C) 146(D) 140Answer: (A)Explanation: Steps to find minimum and maximum element out of n numbers:
1. Pick 2 elements(a, b), compare them. (say a > b)
2. Update min by comparing (min, b)
3. Update max by comparing (max, a)
Therefore, we need 3 comparisons for each 2 elements, so total number of required comparisons will be (3n)/2 – 2, because we do not need to update min or max in the very first step.
Recurrence relation will be:
T(n) = T(⌈n/2⌉)+T(⌊n/2⌋)+2 = 2T(n/2)+2 = ⌈3n/2⌉-2
By putting the value n=100, (3*100/2)-2 = 148 which is answer.
 Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modifying existing data in SQL

10 Sep, 2021
In this article, we are going to cover how we can modify the existing data in SQL. There are lots of situations where we need to alter and need to update existing data. Let’s discuss one by one. 
1. ALTER Command : ALTER is an SQL command used in Relational DBMS and is a Data Definition Language (DDL) statement. ALTER can be used to update the table’s structure in the database (like add, delete, drop indexes, columns, and constraints, modify the attributes of the tables in the database). 
ALTER command is most commonly used to improve SQL SELECT queries by adding and removing indexes. 
SYNTAX : Adding a column to the existing table – 
ALTER TABLE tableName 
ADD columnName columnDefinition;
Example –  
ALTER TABLE Student 
ADD marks_obtained Number (3);
Before : Student Table 
After : Student Table 
marks_obtained 
SYNTAX : Removing column from existing table –  
ALTER TABLE tableName 
DROP COLUMN columnName;
Example –  
ALTER TABLE Student 
DROP COLUMN city;
Before : Student table  
After: Student table 
SYNTAX : 
Changing column name in the existing table –  
ALTER TABLE tableName 
RENAME COLUMN olderName TO newName;
Example –  
ALTER TABLE student 
RENAME COLUMN contactTO contact_no;
Before : Student table  
After : Student table  
2. UPDATE Command : 
UPDATE is an SQL command used in Relational DBMS and is a Data Manipulation Language (DML) statement. It is used to manipulate the data of any existing column. But can’t change the table’s definition. 
SYNTAX : Updating data in existing table –  
UPDATE table_name 
SET column1 = value1, 
column2 = value2, ... WHERE condition;
Example –  
UPDATE student 
SET contact = 91111. WHERE name =ashu;
Before : Student table  
Without the WHERE clause, all records in the table will be updated. 
Difference Between ALTER and UPDATE Command in SQL :  
 
arorakashish0911
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
How to change the Background Color of Text in C# Console

To change the background color of text in Console, use the Console.BackgroundColor
Property in C#.
Let us now see an example −
using System;
class Demo {
   public static void Main (string[] args) {
      Console.BackgroundColor = ConsoleColor.Blue;
      Console.WriteLine("Background color changed = "+Console.BackgroundColor);
   }
}
This will produce the following output −
Valid Palindrome III in C++

Suppose we have a string s and another number k; we have to check whether the given string is a K-Palindrome or not.
A string is said to be K-Palindrome if it can be transformed into a palindrome by removing at most k characters from it.
So, if the input is like s = "abcdeca", k = 2, then the output will be true as by removing 'b' and 'e' characters, it will be palindrome.
To solve this, we will follow these steps −
Define a function lcs(), this will take s, t,
Define a function lcs(), this will take s, t,
n := size of s
n := size of s
add one blank space before s
add one blank space before s
add one blank space before t
add one blank space before t
Define one 2D array dp of size (n + 1) x (n + 1)
Define one 2D array dp of size (n + 1) x (n + 1)
for initialize i := 1, when i <= n, update (increase i by 1), do −for initialize j := 1, when j <= n, update (increase j by 1), do −dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
for initialize i := 1, when i <= n, update (increase i by 1), do −
for initialize j := 1, when j <= n, update (increase j by 1), do −dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
for initialize j := 1, when j <= n, update (increase j by 1), do −
dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]
dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]
if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
if s[i] is same as t[j], then −
dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
return dp[n, n]
return dp[n, n]
From the main method do the following −
From the main method do the following −
if not size of s, then −return true
if not size of s, then −
return true
return true
x := blank space
x := blank space
for initialize i := size of s, when i >= 0, update (decrease i by 1), do −x := x + s[i]
for initialize i := size of s, when i >= 0, update (decrease i by 1), do −
x := x + s[i]
x := x + s[i]
return size of s
return size of s
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int lcs(string s, string t){
      int n = s.size();
      s = " " + s;
      t = " " + t;
      vector<vector<int> > dp(n + 1, vector<int>(n + 1));
      for (int i = 1; i <= n; i++) {
         for (int j = 1; j <= n; j++) {
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            if (s[i] == t[j])
            dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
         }
      }
      return dp[n][n];
   }
   bool isValidPalindrome(string s, int k) {
      if (!s.size())
      return true;
      string x = "";
      for (int i = s.size() - 1; i >= 0; i--)
         x += s[i];
      return s.size() - lcs(s, x) <= k;
   }
};
main(){
   Solution ob;
   cout << (ob.isValidPalindrome("abcdeca", 2));
}
"abcdeca", 2
1
Longest Repeating Substring in C++

Suppose we have a string S, we have to find the length of the longest repeating substring(s). We will return 0 if no repeating substring is present. So if the string is like “abbaba”, then the output will be 2. As the longest repeating substring is “ab” or “ba”.
Return all words that can be formed in this manner, in lexicographical order.
To solve this, we will follow these steps −
n := size of S
n := size of S
set S := one blank space concatenated with S
set S := one blank space concatenated with S
set ret := 0
set ret := 0
create one matrix dp of size (n + 1) x (n + 1)
create one matrix dp of size (n + 1) x (n + 1)
for i in range 1 to nfor j in range i + 1 to nif S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]
for i in range 1 to n
for j in range i + 1 to nif S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]
for j in range i + 1 to n
if S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]
if S[i] = S[j]
dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]
dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]
ret := max of ret and dp[i, j]
ret := max of ret and dp[i, j]
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int longestRepeatingSubstring(string S) {
      int n = S.size();
      S = " " + S;
      int ret = 0;
      vector < vector <int> > dp(n + 1, vector <int> (n + 1));
      for(int i = 1; i <= n; i++){
         for(int j = i + 1; j <= n; j++){
            if(S[i] == S[j]){
               dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
               ret = max(ret, dp[i][j]);
            }
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.longestRepeatingSubstring("abbaba"));
}
"abbaba"
2
MySQL add “prefix” to every column?

To create a view only if it does not already exist, you can use the following syntax −
CREATE OR REPLACE VIEW yourViewName AS SELECT *FROM yourTableName;
To understand the above syntax, let us create a table. 
The query to create a table is as follows −
mysql> create table createViewDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command. 
The query is as follows −
mysql> insert into createViewDemo(Name) values('John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into createViewDemo(Name) values('Carol');
Query OK, 1 row affected (0.15 sec)
mysql> insert into createViewDemo(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)
mysql> insert into createViewDemo(Name) values('Sam');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. 
The query is as follows −
mysql> select *from createViewDemo;
Here is the output −
+----+-------+
| Id | Name  |
+----+-------+
| 1  | John  |
| 2  | Carol |
| 3  | Bob   |
| 4  | Sam   |
+----+-------+
4 rows in set (0.00 sec)
Here is the query to create a view only if it does not already exist −
mysql> CREATE OR REPLACE VIEW New_ViewDemo AS select *from createViewDemo;
Query OK, 0 rows affected (0.13 sec)
Let us check the records of view. 
The query is as follows −
mysql> select *from New_ViewDemo;
The following is The output −
+----+-------+
| Id | Name  |
+----+-------+
| 1  | John  |
| 2  | Carol |
| 3  | Bob   |
| 4  | Sam   |
+----+-------+
4 rows in set (0.02 sec)
turtle.up() method in Python - GeeksforGeeks

16 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.up() method is used to pull the pen up from the screen. It gives no drawing on moving to another position or direction. 
turtle.up() or turtle.pu() or turtle.penup()

Here, this method can be called with three names as written above i.e; it has Aliases: penup | pu | up. There is no argument required for this method.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle    # forward the turtle (drawing)turtle.forward(50)  # up the turtleturtle.up()  # forward the turtle (no drawing)turtle.forward(50)  # down the turtleturtle.down()  # forward the turtle (drawing)turtle.forward(50)
Output:
Example 2 :
Python3
# import packageimport turtle    # forward the turtle (drawing)turtle.forward(50)  # turn right 90 degreesturtle.right(90)  # up the turtleturtle.up()  # forward the turtle (no drawing)turtle.forward(50)  # down the turtleturtle.down()  # turn right 90 degreesturtle.right(90)  # forward the turtle (drawing)turtle.forward(50)
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How can we extract the Year and Month from a date in MySQL?

It can be done with the following three ways in MySQL
 For extracting YEAR and MONTH collectively then we can use the EXTRACT function. We need to provide the YEAR_MONTH as an argument for this function. To understand it, consider the following function using the data from table ‘Collegedetail’ −
mysql> Select EXTRACT(YEAR_MONTH From estb) from collegedetail;
+-------------------------------+
| EXTRACT(YEAR_MONTH From estb) |
+-------------------------------+
|                        201005 |
|                        199510 |
|                        199409 |
|                        200107 |
|                        201007 |
+-------------------------------+
5 rows in set (0.00 sec)
 It can extract the year and the month collectively as well as separately. As the name suggests we can also format its output. To understand it, consider the following example which uses the data from table ‘Collegedetail’ −
mysql> Select DATE_FORMAT(estb, '%Y %m') from collegedetail;
+----------------------------+
| DATE_FORMAT(estb, '%Y %m') |
+----------------------------+
| 2010 05                    |
| 1995 10                    |
| 1994 09                    |
| 2001 07                    |
| 2010 07                    |
+----------------------------+
5 rows in set (0.00 sec)

mysql> Select DATE_FORMAT(estb, '%Y') from Collegedetail;
+-------------------------+
| DATE_FORMAT(estb, '%Y') |
+-------------------------+
| 2010                    |
| 1995                    |
| 1994                    |
| 2001                    |
| 2010                    |
+-------------------------+
5 rows in set (0.00 sec)

mysql> Select DATE_FORMAT(estb, '%m') from Collegedetail;
+-------------------------+
| DATE_FORMAT(estb, '%m') |
+-------------------------+
| 05                      |
| 10                      |
| 09                      |
| 07                      |
| 07                      |
+-------------------------+
5 rows in set (0.00 sec)

mysql> Select DATE_FORMAT(estb, '%M') from Collegedetail;
+-------------------------+
| DATE_FORMAT(estb, '%M') |
+-------------------------+
| May                     |
| October                 |
| September               |
| July                    |
| July                    |
+-------------------------+
5 rows in set (0.10 sec)
 it will extract the Year and month separately by using two different functions. To understand it, consider the following example which uses the data from table ‘Collegedetail’ −
mysql> Select YEAR(estb) AS 'Year', MONTH(estb) As 'MONTH' From collegedetail;
+------+-------+
| Year | MONTH |
+------+-------+
| 2010 |     5 |
| 1995 |    10 |
| 1994 |     9 |
| 2001 |     7 |
| 2010 |     7 |
+------+-------+
5 rows in set (0.00 sec)
How to find Square root of complex numbers in Python?

You can find the Square root of complex numbers in Python using the cmath library. The cmath library in python is a library for dealing with complex numbers. You can use it as follows to find the square root −
from cmath import sqrt
a = 0.2 + 0.5j
print(sqrt(a))
This will give the output 
(0.6076662244659689+0.4114100635092987j)
Convert a JSON String to Java Object using the json-simple library in Java?


The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to encode or decode a JSON text. 
In the below program, we can convert a JSON String to Java object using the json.simple library.
import org.json.simple.*;
import org.json.simple.parser.*;
public class ConvertJSONStringToObjectTest {
   public static void main(String[] args) {
      String jsonString = "{\"Name\":\"Raja\",\"EmployeeId\":\"115\",\"Age\":\"30\"}";
      JSONParser parser = new JSONParser();
      JSONObject obj;
      try {
         obj = (JSONObject)parser.parse(jsonString);
         System.out.println(obj.get("Name"));
         System.out.println(obj.get("EmployeeId"));
         System.out.println(obj.get("Age"));
      } catch(ParseException e) {
         e.printStackTrace();
      }
   }
}
Raja
115
30
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

const myElement = (
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Cherries</li>
  </ul>
);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
Column Sort of a Matrix in Python

Suppose we have a matrix, we have to sort each of the columns in ascending order.
So, if the input is like
then the output will be
To solve this, we will follow these steps −
R := row count of matrix, C := column count of matrix
res := matrix of same size as given matrix and fill with 0
for col in range 0 to C, dovalues := take the elements as a vector of matrix[col]for row in range 0 to R, dores[row, col] := delete last element from values
values := take the elements as a vector of matrix[col]
for row in range 0 to R, dores[row, col] := delete last element from values
res[row, col] := delete last element from values
return res
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, matrix):
      R = len(matrix)
      C = len(matrix[0])
      res = [[0] * C for _ in range(R)]
      for col in range(C):
         values = [r[col] for r in matrix]
         values.sort(reverse=True)
         for row in range(R):
            res[row][col] = values.pop()
      return res
ob = Solution()
matrix = [[11, 21, 31],[6, 6, 4],[1, 11, 8]]
print(ob.solve(matrix))
[[11, 21, 31],
[6, 6, 4],
[1, 11, 8]]
[[1, 6, 4],[6, 11, 8],[11, 21, 31]]
rand() and srand() in C

The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.
Here is the syntax of rand() in C language,
int rand(void);
Here is an example of rand() in C language,
 Live Demo
#include <stdio.h>
#include<stdlib.h>
int main() {
   printf("%d\n", rand());
   printf("%d", rand());
   return 0;
}
1804289383
846930886
The function srand() is used to initialize the generated pseudo random number by rand() function. It does not return anything.
Here is the syntax of srand() in C language,
void srand(unsigned int number);
Here is an example of srand() in C language,
 Live Demo
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
   srand(time(NULL));
   printf("%d\n", rand());
   srand(12);
   printf("%d", rand());
   return 0;
}
1432462941
1687063760
HTML <textarea> disabled Attribute - GeeksforGeeks

04 Jan, 2019
The disabled attribute for <textarea> element in HTML is used to specify that the text area element is disabled. A disabled text area is un-clickable and unusable. It is a boolean attribute.
Syntax:
<textarea disabled>text content...</textarea>

Example:
<!DOCTYPE html> <html>     <head>         <title>HTML textarea disabled Attribute</title>     </head>     <body style = "text-align:center">            <h1 style = "color: green;">GeeksforGeeks</h1>        <h2>HTML textarea disabled Attribute</h2>          <p>This text area is non editable.</p>          <!--A disabled textarea-->        <textarea disabled>            This textarea field is disabled.        </textarea>    </body> </html>    
Output:
Supported Browsers: The browser supported by <textarea> disabled attribute are listed below:
Apple Safari
Google Chrome
Firefox
Opera
Internet Explorer
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
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?