code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE CS 2013 | Question 44 - GeeksforGeeks

28 Jun, 2021
Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a global parameter.
MultiDequeue(Q){
   m = k
   while (Q is not empty and m  > 0) {
      Dequeue(Q)
      m = m - 1
   }
}
What is the worst case time complexity of a sequence of n MultiDequeue() operations on an initially empty queue? (GATE CS 2013)
(A) 
(B) 
(C) 
(D) 

(A) A(B) B(C) C(D) DAnswer: (A)Explanation: See https://www.geeksforgeeks.org/data-structures-queue-question-10-2/Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
SQL - RIGHT JOINS

The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table. This means that if the ON clause matches 0 (zero) records in the left table; the join will still return a row in the result, but with NULL in each column from the left table.
This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no matching join predicate.
The basic syntax of a RIGHT JOIN is as follow.
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;

Consider the following two tables,
Table 1 − CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − ORDERS Table is as follows.
+-----+---------------------+-------------+--------+
|OID  | DATE                | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 |           3 |   3000 |
| 100 | 2009-10-08 00:00:00 |           3 |   1500 |
| 101 | 2009-11-20 00:00:00 |           2 |   1560 |
| 103 | 2008-05-20 00:00:00 |           4 |   2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using the RIGHT JOIN as follows.
SQL> SELECT  ID, NAME, AMOUNT, DATE
   FROM CUSTOMERS
   RIGHT JOIN ORDERS
   ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result −
+------+----------+--------+---------------------+
| ID   | NAME     | AMOUNT | DATE                |
+------+----------+--------+---------------------+
|    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
|    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
|    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
|    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
Python | Alternate character addition

26 Oct, 2021
Sometimes, while working with Python, we can have a problem in which we need to add a character after every character in String. This kind of problem can have its application in many day-day programming domains. Lets discuss certain ways in which this task can be performed.Method #1 : Using loop This is brute force way in which this task can be performed. In this, we iterate for each element and insert the character required. We erase the last stray character. 
Python3
# Python3 code to demonstrate working of# Alternate character addition# Using loop # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + test_str) # initializing KK = '*' # Alternate character addition# Using loopres = ''for ele in test_str:    res += ele + Kres = res[:-1] # printing resultprint("String after character addition : " + str(res))
The original string is : geeksforgeeks
String after character addition : g*e*e*k*s*f*o*r*g*e*e*k*s
 
 Method #2 : Using join() This is easiest, elegant and recommended way to perform this task. In this, we just use one line to perform this task. The join() is used to perform it. 
Python3
# Python3 code to demonstrate working of# Alternate character addition# Using join() # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + test_str) # initializing KK = '*' # Alternate character addition# Using join()res = K.join(test_str) # printing resultprint("String after character addition : " + str(res))
The original string is : geeksforgeeks
String after character addition : g*e*e*k*s*f*o*r*g*e*e*k*s
 
saurabh1990aror
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shell Script to Concatenate Two Strings

28 Mar, 2021
String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other. The examples below show some shell scripts that can be used to concatenate strings.
Example 1:
In this example, we will concatenate two strings using += operator. The input strings will be stored in two variables, a and b.
Code:
#Read inputs a and b and store string variables in them.
read a b

#append b to the string a
a+=$b

#Output the resulting string
echo $a
Example 2:
In this example.  We will concatenate multiple variables using the += operator in a for loop, where every two strings are separated by a space.
Code:
#create an empty string c
c=""

#read input strings and store them in a and b
read a b

#for loop to append a group of strings to the variable c.  
for val in $a 'ipsum' $b 'sit amet' 10
do
 c+="$val "
done

#The result is a string that consists of all the elements concatenated into a single string
echo "$c"
Notice that the integer 10 inside the array was treated the same as the strings. This is because in shell scripts, variables are treated depending on context and not segregated by type.
Example 3:
In this example, we have two variables a and b, and we stored a string in each variable. We want to concatenate them one after the other. The result of concatenation will be stored in the variable c.
Code:
#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by writing one after the other. Store the result in c
c=$a$b

#output c
echo $c
We can also add extra text elements by simply inserting the text surrounded by double quotations “”.  In this case we added a space between the two strings, a hyphen before them, and an exclamation point after. An alternative method would be to surround the entire text with double quotations ” ” and surround variable names by curly brackets {} so that the other elements in the string do not interfere with them.
Code:
#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by putting one after the other. Store the result in c
c="-"$a" "$b"!"

#alternative solution:
#c="-${a} {b}!"

#output c
echo $c
Example 4:
This is another example that shows how to concatenate strings by writing them one after the other. In this case we have 4 strings, two of them are stored in variables a and b.
Code:
#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by putting one after the other
echo $a" ipsum "$b" sit amet"
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
diff command in Linux with examples
touch command in Linux with Examples
Python – Random Sample Training and Test Data from dictionary

22 Apr, 2020
Sometimes, while working with Machine Learning Algorithm, we can have problem in which we need to differentiate the training and testing data randomly. This is very common problem and solution to it is desirable for Machine Learning domains. This article discusses approach to solve this without using external libraries.
Method : Using keys() + random.randint() + computationsThis problem can be solved by using combination of above functions. In this, we perform the task of extraction of random keys using randint(), from the keys extracted using keys(). The logical computations are performed for getting the separated test and training data.
# Python3 code to demonstrate working of # Random Sample Training and Test Data# Using keys() + randint() + computationsimport random  # initializing dictionarytest_dict = {'gfg' : 4, 'is' : 12, 'best' : 6, 'for' : 7, 'geeks' : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing ratiotest = 40training = 60  # Random Sample Training and Test Data# Using keys() + randint() + computationskey_list = list(test_dict.keys())  test_key_count = int((len(key_list) / 100) * test)test_keys = [random.choice(key_list) for ele in range(test_key_count)]train_keys = [ele for ele in key_list if ele not in test_keys]  testing_dict = dict((key, test_dict[key]) for key in test_keys                                         if key in test_dict) training_dict = dict((key, test_dict[key]) for key in train_keys                                         if key in test_dict)   # printing result print("The testing dictionary is : " + str(testing_dict)) print("The training dictionary is : " + str(training_dict)) 
The original dictionary is : {‘is’: 12, ‘gfg’: 4, ‘best’: 6, ‘for’: 7, ‘geeks’: 10}The testing dictionary is : {‘is’: 12, ‘for’: 7}The training dictionary is : {‘gfg’: 4, ‘best’: 6, ‘geeks’: 10}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
Defaultdict in Python
Python program to convert a list to string
Python Program for Fibonacci numbers
Python program to add two numbers
Python Program for factorial of a number
Java Examples - Calculating Factorial

How to use  method for calculating Factorial of a number?
This example shows the way of using method for calculating Factorial of 9(nine) numbers.
public class MainClass {
   public static void main(String args[]) {
      for (int counter = 0; counter <= 10; counter++) {
         System.out.printf("%d! = %d\n", counter, factorial(counter));
      }
   }
   public static long factorial(long number) {
      if (number <= 1) return 1;
      else return number * factorial(number - 1);
   }
}
The above code sample will produce the following result.
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

The following is an another example of factorial
public class NumberFactorial {
   public static void main(String[] args) {
      int number = 5;
      int factorial = number;
      
      for(int i = (number - 1); i > 1; i--) {
         factorial = factorial * i;
      } 
      System.out.println("Factorial of 5 is " + factorial);
   }
}
The above code sample will produce the following result.
Factorial of 5 is 120
The Threading Module in Python

The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.
The threading module exposes all the methods of the thread module and provides some additional methods −
threading.activeCount() − Returns the number of thread objects that are active.
threading.currentThread() − Returns the number of thread objects in the caller's thread control.
threading.enumerate() − Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows −
run()  − The run() method is the entry point for a thread.
start()  − The start() method starts a thread by calling the run method.
join([time])  − The join() waits for threads to terminate.
isAlive()  − The isAlive() method checks whether a thread is still executing.
getName()  − The getName() method returns the name of a thread.
setName()  − The setName() method sets the name of a thread.
To implement a new thread using the threading module, you have to do the following −
Define a new subclass of the Thread class.
Override the __init__(self [,args]) method to add additional arguments.
Then, override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method.
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print "Starting " + self.name
      print_time(self.name, 5, self.counter)
      print "Exiting " + self.name
def print_time(threadName, counter, delay):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
When the above code is executed, it produces the following result −
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
How to Normalize a Histogram in MATLAB?

08 Dec, 2021
Histogram normalization is a technique to distribute the frequencies of the histogram over a wider range than the current range. This technique is used in image processing too. There we do histogram normalization for enhancing the contrast of poor contrasted images. 
Formula:
  
Here ./ and .* means operation has to be performed element-wise.
Steps:
Read the image.
Convert color image into grayscale.
Display histogram.
Observe maximum and minimum intensities from the histogram.
Change image type from uint8 to double.
Apply a formula for histogram normalization.
Convert back into unit format.
Display image and modified histogram.
Example: 
Matlab
% MATLAB code for% Histogram normalisation.% Read the image.k=imread("lincoln.jfif"); % Convert into grayscalek1=rgb2gray(k); % Display the image and histogram.imtool(k1,[]);imhist(k1); % Set the minimum and maximum% Values from histogram.min=45;max=180; % Convert image into double.k2=double(k1); % Apply the formula.k3=(k2-min)./(max-min); % Multiply with maximum possible value.k4=k3.*255; % Convert the final result into uint8.k5=uint8(k4); % Display the enhanced image and histogram.imtool(k5,[]);imhist(k5);
Output:
Figure: Original histogram
Figure: Normalized histogram
Figure: Images before and after normalization
Code Explanation: 
First, we read the image using imread( ) function.
After reading the image, we convert it into the grayscale format.
After converting it into grayscale, we displayed the image and its histogram.
Maximum and minimum intensity is noted from the histogram.
The image data type is changed from uint8 to double, to facilitate the calculation steps.
Apply the formula of normalization.
The image data type is changed back to uint8.
sweetyty
MATLAB image-processing
MATLAB-graphs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | putalpha() Method

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.putalpha() Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it’s converted to “LA” or “RGBA”. The new layer must be either “L” or “1”.
Syntax: Image.putalpha(alpha)
Parameters:alpha – The new alpha layer. This can either be an “L” or “1” image having the same size as this image, or an integer or other color value.
Returns: An Image object.
Image Used:
     # importing Image class from PIL package from PIL import Image   # creating a object im = Image.open(r"C:\Users\System-Pc\Desktop\lion.png")  # using putalpha methodim.putalpha(1)  # show image objectim.show()
Output:
Another Example: another image used.
Image Used:
     # importing Image class from PIL package from PIL import Image   # creating a object im = Image.open(r"C:\Users\System-Pc\Desktop\butter.png")  # using putalpha methodim.putalpha(1)  # show image objectim.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to make a connection with MySQL server using PHP ?

27 Oct, 2021
MySQL is a widely used database management system that may be used to power a wide range of projects. One of its main selling features is its capacity to manage large amounts of data without breaking a sweat. There are two approaches that can be used to connect MySQL and PHP code, which are mentioned below.
PDO (PHP Data Objects)
MySQLi extension
Let’s get to know both of these options a bit more.
A Database Abstraction Layer is the PHP Data Objects (PDO) extension. It functions as a user interface for the backend to interact with the MySQL database and make changes without altering the PHP code. It also allows you to deal with numerous databases at the same time. The main benefit of using PDO is that it keeps your code simple and portable.
MySQLi is a connector function that connects the PHP app’s backend to the MySQL database. It performs in the same way as the previous version, but it is safer and faster, with a more comprehensive collection of functions and extensions. With PHP 5.0.0, MySQLi was launched, and the drivers were installed with PHP 5.3.0. The API was created to work with MySQL versions 4.1.13 and higher.
Connect with MySQL: Before one can access data in the MySQL database, one needs to be able to connect to the server. Use the mysqli_connect() function according to your connecting way to establish a database connection. This function returns a database connection pointer also known as a database handle. This handle will be utilized later in the code. Remember to add your database credentials after you get the handle.
1. Connection via PDO – A database is also supplied in the PDO example below (“geeksDatabase”). To connect to a database, PDO requires a valid database else an exception is thrown.
PHP
<?php  $servername = "localhost";$username = "user";$password = "123456";$dbName = "geeksDatabase";  try {      // Creating the connection    $conn = new PDO("mysql:host=$servername;dbname=$dbName",                     $username, $password);        // Setting the PDO error mode to exception    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    echo "Connection established successfully...";        // To close the connection    $conn = null;}   // If connection fails catch(PDOException $e) {        // Throws the error message     echo "Connection failed: " . $e->getMessage();}  ?>
Output:
Connection established successfully...
2. Connection via MySQLi – 
PHP
<?php  $servername = "localhost";$username = "user";$password = "123456";$dbName = "geeksDatabase";  // Creating connection$conn = mysqli_connect($servername,          $username, $password, $dbName);  // Checking connectionif (!$conn) {        // If connecting fails    die("Connection failed: " . mysqli_connect_error());}  echo "Connection established successfully...";  // Close the connection  mysqli_close($conn);  ?>
Output:
Connection established successfully...
mysql
PHP-MySQL
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Performing Binomial Test in R programming – binom.test() Method

10 May, 2020
With the help of binom.test() method, we can get the binomial test for some hypothesis of binomial distribution in R Programming.
Syntax: binom.test(x, n, p-value)
Return: Returns the value of binomial test.
Example 1:
# Using binom.test() method  gfg <- binom.test(58, 100)  print(gfg)
Output:
Exact binomial test

data:  58 and 100
number of successes = 58, number of trials = 100, p-value = 0.1332
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
 0.4771192 0.6780145
sample estimates:
probability of success 
                  0.58 


Example 2:
# Using binom.test() method  gfg <- binom.test(1, 36, 0.6)  print(gfg)
Output:
Exact binomial test

data:  1 and 36
number of successes = 1, number of trials = 36, p-value = 2.597e-13
alternative hypothesis: true probability of success is not equal to 0.6
95 percent confidence interval:
 0.0007030252 0.1452892647
sample estimates:
probability of success 
            0.02777778 


R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS - background-attachment

background-attachment determines the tiling context and scroll state of a background image.
scroll − A background image set to scroll will scroll along with the rest of the document.
scroll − A background image set to scroll will scroll along with the rest of the document.
fixed − A background image set to fixed will remain locked in place while the rest of the document scrolls.
fixed − A background image set to fixed will remain locked in place while the rest of the document scrolls.
All the HTML elements.
object.style.backgroundAttachment = scroll | fixed;

<html>
   <head>
   </head>
   
   <body>
      <p style = "background-image:url(/images/logo.png);  
         background-attachment:scroll;
         background-attachment:scroll;
         background-repeat: no-repeat;
         background-attachment: fixed;">
         
         This parapgraph has scrolling background image.
         This parapgraph has fixed repeated background image.
         This parapgraph has fixed repeated background image.
         This parapgraph has fixed repeated background image. 
         This parapgraph has fixed repeated background image.
         This parapgraph has fixed repeated background image.
      </p>
   
   </body>
</html> 
It will produce the following result −

   This parapgraph has scrolling background image.
     This parapgraph has scrolling background image.
	   This parapgraph has scrolling background image.
	     This parapgraph has scrolling background image.
		   This parapgraph has scrolling background image.  
		   This parapgraph has scrolling background image.
		   This parapgraph has scrolling background image.
		   


    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Design and Analysis Max-Min Problem

Let us consider a simple problem that can be solved by divide and conquer technique.
The Max-Min Problem in algorithm analysis is finding the maximum and minimum value in an array.
To find the maximum and minimum numbers in a given array numbers[] of size n, the following algorithm can be used. First we are representing the naive method and then we will present divide and conquer approach.
Naïve method is a basic method to solve any problem. In this method, the maximum and minimum number can be found separately. To find the maximum and minimum numbers, the following straightforward algorithm can be used.
Algorithm: Max-Min-Element (numbers[]) 
max := numbers[1] 
min := numbers[1] 

for i = 2 to n do 
   if numbers[i] > max then  
      max := numbers[i] 
   if numbers[i] < min then  
      min := numbers[i] 
return (max, min) 

The number of comparison in Naive method is 2n - 2.
The number of comparisons can be reduced using the divide and conquer approach. Following is the technique.
In this approach, the array is divided into two halves. Then using recursive approach maximum and minimum numbers in each halves are found. Later, return the maximum of two maxima of each half and the minimum of two minima of each half.
In this given problem, the number of elements in an array is y−x+1, where y is greater than or equal to x.
Max−Min(x,y) will return the maximum and minimum values of an array numbers[x...y].
Algorithm: Max - Min(x, y) 
if y – x ≤ 1 then  
   return (max(numbers[x], numbers[y]), min((numbers[x], numbers[y])) 
else 
   (max1, min1):= maxmin(x, ⌊((x + y)/2)⌋) 
   (max2, min2):= maxmin(⌊((x + y)/2) + 1)⌋,y) 
return (max(max1, max2), min(min1, min2)) 

Let T(n) be the number of comparisons made by Max−Min(x,y), where the number of elements n=y−x+1.
If T(n) represents the numbers, then the recurrence relation can be represented as
T(n)={T(⌊n2⌋)+T(⌈n2⌉)+2forn>21forn=20forn=1
Let us assume that n is in the form of power of 2. Hence, n = 2k where k is height of the recursion tree.
So,
T(n)=2.T(n2)+2=2.(2.T(n4)+2)+2.....=3n2−2
Compared to Naïve method, in divide and conquer approach, the number of comparisons is less. However, using the asymptotic notation both of the approaches are represented by O(n).

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Catching base and derived classes exceptions in C++

To catch an exception for both base and derive class then we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.
Begin
   Declare a class B.
   Declare another class D which inherits class B.
   Declare an object of class D.
   Try: throw derived.
   Catch (D derived)
      Print “Caught Derived Exception”.
   Catch (B b)
      Print “Caught Base Exception”.
End.
Here is a simple example where catch of derived class has been placed before the catch of base class, now check the Output
#include<iostream>
using namespace std;
class B {};
class D: public B {}; //class D inherit the class B
int main() {
   D derived;
   try {
      throw derived;
   }
   catch(D derived){
      cout<<"Caught Derived Exception"; //catch block of derived class
   }
   catch(B b) {
      cout<<"Caught Base Exception"; //catch block of base class
   }
   return 0;
}
Caught Derived Exception
Here is a simple example where catch of base class has been placed before the catch of derived class, now check the Output
#include<iostream>
using namespace std;

class B {};
class D: public B {}; //class D inherit the class B
int main() {
   D derived;
   try {
      throw derived;
   }
   catch(B b) {
      cout<<"Caught Base Exception"; //catch block of base class
   }
   catch(D derived){
      cout<<"Caught Derived Exception"; //catch block of derived class
   }
   return 0;
}
Caught Base Exception
Thus it is proved that we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.
CodeIgniter - Page Caching

Caching a page will improve the page load speed. If the page is cached, then it will be stored in its fully rendered state. Next time, when the server gets a request for the cached page, it will be directly sent to the requested browser.
Cached files are stored in application/cache folder. Caching can be enabled on per page basis. While enabling the cache, we need to set the time, until which it needs to remain in cached folder and after that period, it will be deleted automatically.
Caching can be enabled by executing the following line in any of the controller’s method.
$this->output->cache($n);

Where $n is the number of minutes, you wish the page to remain cached between refreshes.
Cache file gets deleted when it expires but when you want to delete it manually, then you have to disable it. You can disable the caching by executing the following line.
// Deletes cache for the currently requested URI 
$this->output->delete_cache();
  
// Deletes cache for /foo/bar 
$this->output->delete_cache('/foo/bar');
Create a controller called Cache_controller.php and save it in application/controller/Cache_controller.php
<?php 
   class Cache_controller extends CI_Controller { 
	
      public function index() { 
         $this->output->cache(1); 
         $this->load->view('test'); 
      }
		
      public function delete_file_cache() { 
         $this->output->delete_cache('cachecontroller'); 
      } 
   } 
?>
Create a view file called test.php and save it  in application/views/test.php
<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>CodeIgniter View Example</title> 
   </head>
	
   <body> 
      CodeIgniter View Example 
   </body>
	
</html>
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['cachecontroller'] = 'Cache_controller'; 
$route['cachecontroller/delete'] = 'Cache_controller/delete_file_cache';
Type the following URL in the browser to execute the example.
http://yoursite.com/index.php/cachecontroller

After visiting the above URL, you will see that a cache file for this will be created in application/cache folder. To delete the file, visit the following URL.
http://yoursite.com/index.php/cachecontroller/delete

 Print
 Add Notes
 Bookmark this page
Java String toLowerCase() Method

❮ String Methods

Convert a string to upper case and lower case letters:
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());

Try it Yourself »

The toLowerCase() method converts a string to lower case letters.
Note: The toUpperCase() method converts a string to upper case letters.
public String toLowerCase()

None.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Output of C Program | Set 18 - GeeksforGeeks

28 Mar, 2022
Predict the output of following C programs.Question 1  
C
#include<stdio.h>int fun(){  static int num = 40;  return num--;}  int main(){  for(fun(); fun(); fun())  {    printf("%d ", fun());  }  getchar();  return 0;}
Output: 38 35 32 29 26 23 20 17 14 11 8 5 2Since num is static in fun(), the old value of num is preserved for subsequent functions calls. Also, since the statement return num– is postfix, it returns the old value of num, and updates the value for next function call.Question 2  
C
#include<stdio.h>int main(){  char *s[] = { "knowledge","is","power"};  char **p;  p = s;  printf("%s ", ++*p);  printf("%s ", *p++);  printf("%s ", ++*p);    getchar();  return 0;}
Output: nowledge nowledge sLet us consider the expression ++*p in first printf(). Since precedence of prefix ++ and * is same, associativity comes into picture. *p is evaluated first because both prefix ++ and * are right to left associative. When we increment *p by 1, it starts pointing to second character of “knowledge”. Therefore, the first printf statement prints “knowledge”.Let us consider the expression *p++ in second printf() . Since precedence of postfix ++ is higher than *, p++ is evaluated first. And since it’s a postfix ++, old value of p is used in this expression. Therefore, second printf statement prints “knowledge”. In third printf statement, the new value of p (updated by second printf) is used, and third printf() prints “s”.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above 
rs1686740
as5853535
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Runtime Errors
Output of Java Program | Set 3
unsigned specifier (%u) in C with Examples
Output of Java program | Set 5
Output of Java Program | Set 7
How to show full column content in a PySpark Dataframe ?
Output of Java Programs | Set 12
Output of Java Programs | Set 14 (Constructors)
Output of Java program | Set 26
How to clear all the input in HTML forms?

Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.
The <input> tag, helps you to take user input using the type attribute. To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.
You can try to run the following code to clear all the input in HTML forms −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <form>
         Student Name:<br>
         <input type="text" name="sname">
         <br>
         Student Subject:<br>
         <input type="text" name="ssubject">
         <br>
         <input type="reset" value="reset">
      </form>
   </body>
</html>
Python Get the real time currency exchange rate?

Python is very good at handling API calls. In this article we will see how we can handle the API calls for currency exchange rates in real time as well as historical.
This module provides the most direct way of getting the currency conversion rates. It has functions and parameters which can take inputs for the required currency codes and then give the result for the conversion. The below example gives the live conversion rate.
from forex_python.converter import CurrencyRates

c = CurrencyRates()

print(c.get_rate('USD', 'GBP'))
Running the above code gives us the following result −
0.7357387755
We add a datetime object form the datetime module to the above example and that gives us the currency exchange rate at specific time and date.
from forex_python.converter import CurrencyRates
import datetime

c = CurrencyRates()

dt = datetime.datetime(2020, 3, 27, 11, 21, 13, 114505)

print(c.get_rate('USD', 'INR', dt))

Running the above code gives us the following result −
75.4937596793
There are many APIs available which provide us the currency rates by making calls using a API key and getting back the result as JSON. We can further extend the code to convert the JSON to a list and format the data if needed.
import requests

# Where USD is the base currency you want to use
url = 'https://v6.exchangerate-api.com/v6/336ccxxxxxxxxx8e74eac/latest/USD'

# Making our request
response = requests.get(url)
data = response.json()

# Your JSON object
print(data)
Running the above code gives us the following result −
{'result': 'success', 'documentation': 'https://www.exchangerate-api.com/docs', 'terms_of_use': 'https://www.exchangerate-api.com/terms', 'time_last_update_unix': 1610323201, 'time_last_update_utc': 'Mon, 11 Jan 2021 00:00:01 +0000', 'time_next_update_unix': 1610409616, 'time_next_update_utc': 'Tue, 12 Jan 2021 00:00:16 +0000', 'base_code': 'USD', 'conversion_rates': {'USD': 1, 'AED': 3.6725, .........., 'XOF': 536.3826, 'XPF': 97.579, 'YER': 250.1264, 'ZAR': 15.2899, 'ZMW': 21.1561}}
Change the file extension in the text column in MySQL?

To change the file extension in the text column, you can use UPDATE command along with REPLACE() function. Let’s say we have some columns with extensions and we need to replace all of them. For that, let us first create a table with the extension columns set as text type:
mysql create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ProgramExtension1 text,
   ProgramExtension2 text,
   ImageExtension text
);
Query OK, 0 rows affected (0.52 sec)
Following is the query to insert records in the table using insert command:
mysql> insert into
DemoTable(ProgramExtension1,ProgramExtension2,ImageExtension)values('.java','.c','.jpeg');
Query OK, 1 row affected (0.18 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+----+-------------------+-------------------+----------------+
| Id | ProgramExtension1 | ProgramExtension2 | ImageExtension |
+----+-------------------+-------------------+----------------+
|  1 | .java             |                .c |          .jpeg |
+----+-------------------+-------------------+----------------+
1 row in set (0.00 sec)
Following is the query to change the file extension in the text column:
mysql> update DemoTable
   set ProgramExtension1=replace(ProgramExtension1,'.java','.py'),
   ProgramExtension2=replace(ProgramExtension2,'.c','.cpp'),
   ImageExtension=replace(ImageExtension,'.jpeg','.png');
Query OK, 1 row affected (0.13 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the file extensions have been changed or not:
mysql> select *from DemoTable;
This will produce the following output
+----+-------------------+-------------------+----------------+
| Id | ProgramExtension1 | ProgramExtension2 | ImageExtension |
+----+-------------------+-------------------+----------------+
|  1 |               .py |              .cpp |           .png |
+----+-------------------+-------------------+----------------+
1 row in set (0.00 sec)
Mixins in JavaScript

JavaScript doesn't support multiple inheritence. But sometimes there is a need to add functionality of 2 classes to a single object. Mixin is a way properties are added to objects without using inheritance.
For example, let's say we have a Person class. And we want people to be able to say Hi. We can create a sayHiMixin and use it to make People say hi −
let sayHiMixin = {
   sayHi() {
      console.log(`Hello ${this.name}`);
   },
   sayBye() {
      console.log(`Bye ${this.name}`);
   }
};
class Person {
   constructor(name) {
      this.name = name;
   }
}
// copy the methods
Object.assign(Person.prototype, sayHiMixin);
new Person("John").sayHi();
Hello John
There is no inheritence involved here. We're just copying properties from one object to another. The person class can also inherit from another class while using this mixin.
PostgreSQL - Schema

A schema is a named collection of tables. A schema can also contain views, indexes, sequences, data types, operators, and functions. Schemas are analogous to directories at the operating system level, except that schemas cannot be nested. PostgreSQL statement CREATE SCHEMA creates a schema.
The basic syntax of CREATE SCHEMA is as follows −
CREATE SCHEMA name;

Where name is the name of the schema.
The basic syntax to create table in schema is as follows −
CREATE TABLE myschema.mytable (
...
);
Let us see an example for creating a schema. Connect to the database testdb and create a schema  myschema as follows −
testdb=# create schema myschema;
CREATE SCHEMA
The message "CREATE SCHEMA" signifies that the schema is created successfully.
Now, let us create a table in the above schema as follows −
testdb=# create table myschema.company(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25),
   SALARY   DECIMAL (18, 2),
   PRIMARY KEY (ID)
);
This will create an empty table. You can verify the table created with the command given below −
testdb=# select * from myschema.company;
This would produce the following result −
 id | name | age | address | salary
----+------+-----+---------+--------
(0 rows)

To drop a schema if it is empty (all objects in it have been dropped), use the command −
DROP SCHEMA myschema;
To drop a schema including all contained objects, use the command −
DROP SCHEMA myschema CASCADE;
It allows many users to use one database without interfering with each other.
It allows many users to use one database without interfering with each other.
It organizes database objects into logical groups to make them more manageable.
It organizes database objects into logical groups to make them more manageable.
Third-party applications can be put into separate schemas so they do not collide with the names of other objects.
Third-party applications can be put into separate schemas so they do not collide with the names of other objects.

    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Python | os.path.ismount() method

12 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.ismount() method in Python is used to check whether the given path is a mount point or not.A mount point is a point in a file system where different file system has been mounted.
Syntax: os.path.ismount(path)
Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a Boolean value of class bool. This method returns True if the given path is a mount point, otherwise returns False.
On Linux system, the partitions and their mount points information can be displayed using the df command.
For example:
Code #1: Use of os.path.ismount() method to check if the given path is a mount point (On Unix)
# Python program to explain os.path.islink() method     # importing os.path module import os.path  # Path path = "/run"   # Check whether the # given path is a# mount point or notismount = os.path.ismount(path)    # Path path = "/dev"   # Check whether the # given path is a# mount point or notismount = os.path.ismount(path)print(ismount)
True
True

Code #2: Use of os.path.ismount() method to check if the given path is a mount point (On Windows)
# Python program to explain os.path.islink() method     # importing os.path module import os.path    # On Windows, a drive letter root# and a share UNC are always# mount points Path path = "C:"   # Check whether the # given path is a# mount point or notismount = os.path.ismount(path)print(ismount)
True

Reference: https://docs.python.org/3/library/os.path.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
Python | Extract key-value of dictionary in variables

26 Jul, 2019
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let’s discuss certain ways in which this can be done.
Method #1 : Using items()This problem can be solved using the items function which does the task of extracting a key-value pair and using the 0th index gives us the first key-value pair. Works only in Python2.
# Python code to demonstrate working of# Extracting key-value of dictionary in variables# Using items()  # Initialize dictionarytest_dict = {'gfg' : 1}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using items()# Extracting key-value of dictionary in variableskey, val = test_dict.items()[0]  # printing result print("The 1st key of dictionary is : " + str(key))print("The 1st value of dictionary is : " + str(val))
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1

 
Method #2 : Using iter() + next()The combination of above functions can be used to perform this particular task. It uses iterators to perform this task. The next() is used to fetch the pairs till dictionary is exhausted. It works with Python3.
# Python3 code to demonstrate working of# Extracting key-value of dictionary in variables# Using iter() + next()  # Initialize dictionarytest_dict = {'gfg' : 1}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using iter() + next()# Extracting key-value of dictionary in variableskey, val = next(iter(test_dict.items()))  # printing result print("The 1st key of dictionary is : " + str(key))print("The 1st value of dictionary is : " + str(val))
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python | Split string into list of characters