code-rag-bench/online-tutorials huggingface dataset:
Calculate total time duration (add time) in MySQL?

To calculate the total time duration in MySQL, you need to use SEC_TO_TIME(). Let us see an example by creating a table
mysql> create table AddTotalTimeDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > LoginTime time
   - > );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into AddTotalTimeDemo(LoginTime) values('05:05:00');
Query OK, 1 row affected (0.10 sec)
mysql> insert into AddTotalTimeDemo(LoginTime) values('07:20:00');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AddTotalTimeDemo(LoginTime) values('02:05:00');
Query OK, 1 row affected (0.17 sec)
mysql> insert into AddTotalTimeDemo(LoginTime) values('03:03:00');
Query OK, 1 row affected (0.25 sec)
mysql> insert into AddTotalTimeDemo(LoginTime) values('05:07:00');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from AddTotalTimeDemo;
The following is the output
+----+-----------+
| Id | LoginTime |
+----+-----------+
|  1 | 05:05:00  |
|  2 | 07:20:00  |
|  3 | 02:05:00  |
|  4 | 03:03:00  |
|  5 | 05:07:00  |
+----+-----------+
5 rows in set (0.00 sec)
The following is the query to calculate the total time duration in MySQL
mysql> SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(LoginTime))) AS TotalTime from AddTotalTimeDemo;
The following is the output
+-----------+
| TotalTime |
+-----------+
| 22:40:00  |
+-----------+
1 row in set (0.00 sec)
How to get radiobutton output in Tkinter?

The radiobutton widget in Tkinter allows the user to make a selection for only one option from a set of given choices. The radiobutton has only two values, either True or False.
If we want to get the output to check which option the user has selected, then we can use the get() method. It returns the object that is defined as the variable. We can display the selection in a label widget by casting the integer value in a string object and pass it in the text attributes.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the window
win.geometry("700x350")

# Define a function to get the output for selected option
def selection():
   selected = "You selected the option " + str(radio.get())
   label.config(text=selected)

radio = IntVar()
Label(text="Your Favourite programming language:", font=('Aerial 11')).pack()

# Define radiobutton for each options
r1 = Radiobutton(win, text="C++", variable=radio, value=1, command=selection)

r1.pack(anchor=N)
r2 = Radiobutton(win, text="Python", variable=radio, value=2, command=selection)

r2.pack(anchor=N)
r3 = Radiobutton(win, text="Java", variable=radio, value=3, command=selection)

r3.pack(anchor=N)

# Define a label widget
label = Label(win)
label.pack()

win.mainloop()
Executing the above code will display a window with a set of radiobuttons in it. Click any option and it will show the option that you have selected.
How to Show All Tables in MySQL using Python? - GeeksforGeeks

29 Sep, 2021
A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server.
In order to make python interact with the MySQL database, we use Python-MySQL-Connector. Here we will try implementing SQL queries which will show the names of all the tables present in the database or server.
Syntax:
To show the name of tables present inside a database:
SHOW Tables;
To show the name of tables present inside a server:
SELECT table_name
FROM information_schema.tables;
Database in use:
Schema of the database used
The following programs implement the same.
Example 1: Display table names present inside a database:
Python3
import mysql.connector mydb = mysql.connector.connect(    host="localhost",    user="root",    password="",    database="gfg") mycursor = mydb.cursor() mycursor.execute("Show tables;") myresult = mycursor.fetchall() for x in myresult:    print(x)
Output:
Table names in gfg  database
Example 2: Display table names present inside a server:
Python3
import mysql.connector mydb = mysql.connector.connect(  host="localhost",  user="root",  password="",) mycursor = mydb.cursor() mycursor.execute("SELECT table_name FROM information_schema.tables;") myresult = mycursor.fetchall() for x in myresult:  print(x)
Output:
Table names in server
surindertarika1234
Picked
Python-mySQL
Python
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
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Convert a Number to Hexadecimal in C++

Suppose we have an integer; we have to devise an algorithm to convert it to hexadecimal. For negative numbers we will use the two’s complement method.
So, if the input is like 254 and -12, then the output will be fe and fffffff4 respectively.
To solve this, we will follow these steps −
if num1 is same as 0, then −return "0"
if num1 is same as 0, then −
return "0"
return "0"
num := num1
num := num1
s := blank string
s := blank string
while num is non-zero, do −temp := num mod 16if temp <= 9, then −s := s + temp as numeric characterOtherwises := s + temp as alphabetnum := num / 16
while num is non-zero, do −
temp := num mod 16
temp := num mod 16
if temp <= 9, then −s := s + temp as numeric character
if temp <= 9, then −
s := s + temp as numeric character
s := s + temp as numeric character
Otherwises := s + temp as alphabet
Otherwise
s := s + temp as alphabet
s := s + temp as alphabet
num := num / 16
num := num / 16
reverse the array s
reverse the array s
return s
return s
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string toHex(int num1){
      if (num1 == 0)
         return "0";
      u_int num = num1;
      string s = "";
      while (num) {
         int temp = num % 16;
         if (temp <= 9)
            s += (48 + temp);
         else
            s += (87 + temp);
         num = num / 16;
      }
      reverse(s.begin(), s.end());
      return s;
   }
};
main(){
   Solution ob;
   cout << (ob.toHex(254)) << endl;
   cout << (ob.toHex(-12));
}
254
-12
fe
fffffff4
Scrolling to element using Webdriver.

We can perform scrolling to an element using Selenium webdriver. This can be achieved in multiple ways. Selenium cannot handle scrolling directly. It takes the help of the Javascript Executor and Actions class to do scrolling action.
First of all we have to identify the element up to which we have to scroll to with the help of any of the locators like class, id, name and so on. Next we shall take the help of the Javascript Executor to run the Javascript commands. The method executeScript is used to execute Javascript commands in Selenium. We have to use the scrollIntoView method in Javascript and pass true as an argument to the method.
WebElement e = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", e);
Code Implementation with Javascript Executor.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollToElementJs{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView (true);", m);
      Thread.sleep(200);
      driver.close();
   }
}
With the Actions class, we shall use the moveToElement method and pass the webelement locator as an argument to the method.
Code Implementation with Actions.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ScrollToElementActions{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
      // moveToElement method with Actions class
      Actions act = new Actions(driver);
      act.moveToElement(m);
      act.perform();
      driver.close();
   }
}
What is the difference between class and typeof function in R?

The class function in R helps us to understand the type of object, for example the output of class for a data frame is integer and the typeof of the same object is list because data frames are stored as list in the memory but they are represented as a data frame. Check out the below examples with multiple type of objects to understand the differences.
 Live Demo
x1<-rpois(20,2)
typeof(x1)
[1] "integer"
class(x1)
[1] "integer"
df1<-data.frame(x1)
df1
   x1
1  1
2  4
3  1
4  0
5  2
6  2
7  4
8  2
9  3
10 4
11 1
12 4
13 0
14 5
15 2
16 2
17 0
18 4
19 3
20 3
typeof(df1)
[1] "list"
class(x1)
[1] "integer"
 Live Demo
M<-matrix(rnorm(40),ncol=2)
M
        [,1]          [,2]
[1,]   2.02437789  -0.9161853
[2,]  -0.60108978  -0.8972007
[3,]   1.27916953   0.1017923
[4,]   1.06998017   1.4839931
[5,]   0.22298522   0.6160919
[6,]  -0.29346341  -0.3975116
[7,]   2.07012097  -0.7900820
[8,]   0.36719470  -0.1100298
[9,]  -0.69522122  -1.9198172
[10,]  2.07822428   0.2517532
[11,] -1.56267422   1.8295022
[12,] -1.07488221   1.2666054
[13,] -0.79381494  -1.0993693
[14,] -0.16027224  -1.1814177
[15,]  0.67561791   0.7309281
[16,] -1.40912018  -0.3307749
[17,] -0.77769513   0.5527600
[18,]  0.47050704   0.1075593
[19,] -0.46616151  -0.5079660
[20,] -0.01944371   0.1553333
typeof(M)
[1] "double"
class(M)
[1] "matrix" "array"
How to delete all the documents from a collection in MongoDB?

If you want to delete all documents from the collection, you can use deleteMany(). Let us first create a collection and insert some documents to it:
> db.deleteDocumentsDemo.insert({"Name":"Larry","Age":23});
WriteResult({ "nInserted" : 1 })
> db.deleteDocumentsDemo.insert({"Name":"Mike","Age":21});
WriteResult({ "nInserted" : 1 })
> db.deleteDocumentsDemo.insert({"Name":"Sam","Age":24});
WriteResult({ "nInserted" : 1 })
Now display all the documents from the collection. The query is as follows:
> db.deleteDocumentsDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ab0e064f3d70fcc914805"),
   "Name" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"),
   "Name" : "Mike",
   "Age" : 21
}
{
   "_id" : ObjectId("5c6ab0f864f3d70fcc914807"),
   "Name" : "Sam",
   "Age" : 24
}
The query is as follows:
> db.deleteDocumentsDemo.deleteMany({});
The following is the output:
{ "acknowledged" : true, "deletedCount" : 3 }
Look at the above sample output. Right now, we do not have any documents in the collection ‘deleteDocumentsDemo’ i.e. we have successfully deleted all the documents using the deleteMany() method.
How to print characters from a string starting from 3rd to 5th in Python?

Slicing feature in Python helps fetch a substring from original string. Slice operator [:] needs two operands. First operand is an integer representing index of starting character of slice. Second operand is index of character next to slice. Recalling that index of sequence starts from 0,
>>> string = 'abcdefghij'
>>> string[2:5]
 'cde'
Here 3rd character of slice ‘cde’ starts at index 2 and ends at 4, so second operand is given as 5
How to capture divide by zero exception in C#?

System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.
Let us see an example −
using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}
The values entered here is num1/ num2 −
result = num1 / num2;
Above, if num2 is set to 0, then the DivideByZeroException is caught since we have handled exception above.
How can we change the JButton text dynamically in Java?


A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate the MouseListener and KeyListener interfaces. By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.getText()) method of a JButton class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonTextChangeTest extends JFrame {
   private JTextField textField;
   private JButton button;
   public JButtonTextChangeTest() {
      setTitle("JButtonTextChange Test");
      setLayout(new FlowLayout());
      textField = new JTextField(20);
      button = new JButton("Initial Button");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            if (!textField.getText().equals(""))
               button.setText(textField.getText());
         }
      });
      add(textField);
      add(button);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JButtonTextChangeTest();
   }
}
How to create a dictionary with list comprehension in Python?

The zip() function which is an in-built function, provides a list  of tuples containing elements at same indices from two lists. If two lists are keys and values respectively,  this zip object can be used to constructed dictionary object using another built-in function dict()
>>> L1=['a','b','c','d']
>>> L2=[1,2,3,4]
>>> d1=dict(zip(L1,L2))
>>> d1
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
In Python 3.x a dictionary comprehension syntax is also available to construct dictionary from zip object
>>> L2=[1,2,3,4]
>>> L1=['a','b','c','d']
>>> d={k:v for (k,v) in zip(L1,L2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Java String startsWith() method example.

The startsWith(String prefix, int toffset) method of the String class tests if the substring of this string beginning at the specified index starts with the specified prefix.
import java.lang.*;

public class StringDemo {
   public static void main(String[] args) {
      String str = "www.tutorialspoint.com";
      System.out.println(str);

      //The start string to be checked
      String startstr1 = "tutorialspoint";
      String startstr2 = "tutorialspoint";

      //Checks that string starts with given substring and starting index
      boolean retval1 = str.startsWith(startstr1);
      boolean retval2 = str.startsWith(startstr2, 4);

      //Prints true if the string starts with given substring
      System.out.println("starts with " + startstr1 + " ? " + retval1);
      System.out.println("string " + startstr2 + " starting from index 4 ? " + retval2);
   }
}
www.tutorialspoint.com
starts with tutorialspoint ? false
string tutorialspoint starting from index 4 ? true
How to update a MySQL date type column?

Let us first create a table −
mysql> create table DemoTable1451
   -> (
   -> JoiningDate date
   -> );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1451 values('2019-07-21');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable1451 values('2018-01-31');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1451 values('2017-06-01');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1451;
This will produce the following output −
+-------------+
| JoiningDate |
+-------------+
| 2019-07-21  |
| 2018-01-31  |
| 2017-06-01  |
+-------------+
3 rows in set (0.00 sec)
Here is the query to update a date type column. We are incrementing the date records with an year −
mysql> update DemoTable1451 set JoiningDate=date_add(JoiningDate, interval 1 year);
Query OK, 3 rows affected (0.15 sec)
Rows matched: 3  Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1451;
This will produce the following output −
+-------------+
| JoiningDate |
+-------------+
| 2020-07-21  |
| 2019-01-31  |
| 2018-06-01  |
+-------------+
3 rows in set (0.00 sec)
How to remove duplicates from MongoDB Collection?

For this, set “unique:true” i.e. the unique constraint and avoid inserting duplicates as in the below syntax −
db.yourCollectionName.ensureIndex({yourFieldName: 1}, {unique: true, dropDups: true})
To understand the above syntax, let us create a collection with documents. Here, duplicate insertion won’t be allowed −
> db.demo604.ensureIndex({FirstName: 1}, {unique: true, dropDups: true});{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo604.insertOne({FirstName:"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e960887ed011c280a0905d8")
}
> db.demo604.insertOne({FirstName:"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e96088aed011c280a0905d9")
}
> db.demo604.insertOne({FirstName:"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e96088ded011c280a0905da")
}
> db.demo604.insertOne({FirstName:"Chris"});
2020-04-15T00:31:35.978+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo604 index: FirstName_1 dup key: { : "Chris" } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: test.demo604 index: FirstName_1 dup key: { : \"Chris\" }",
   "op" : {
      "_id" : ObjectId("5e96088fed011c280a0905db"),
      "FirstName" : "Chris"
   }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
Display all documents from a collection with the help of find() method −
> db.demo604.find();
This will produce the following output −
{ "_id" : ObjectId("5e960887ed011c280a0905d8"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e96088aed011c280a0905d9"), "FirstName" : "Bob" }
{ "_id" : ObjectId("5e96088ded011c280a0905da"), "FirstName" : "David" }
Python | Find missing and additional values in two lists - GeeksforGeeks

21 Nov, 2018
Given two lists, find the missing and additional values in both the lists.
Examples:
Input : list1 = [1, 2, 3, 4, 5, 6] 
        list2 = [4, 5, 6, 7, 8] 
Output : Missing values in list1 = [8, 7] 
         Additional values in list1 = [1, 2, 3] 
         Missing values in list2 = [1, 2, 3] 
         Additional values in list2 = [7, 8] 

Explanation: 


Approach: To find the missing elements of list2 we need to get the difference of list1 from list2. To find the additional elements of list2, calculate the difference of list2 from list1.Similarly while finding missing elements of list1, calculate the difference of list2 from list1. To find the additional elements in list1, calculate the difference of list1 from list2.
Insert the list1 and list2 to set and then use difference function in sets to get the required answer.
Prerequisite : Python Set Difference
# Python program to find the missing # and additional elements   # examples of listslist1 = [1, 2, 3, 4, 5, 6]list2 = [4, 5, 6, 7, 8]  # prints the missing and additional elements in list2 print("Missing values in second list:", (set(list1).difference(list2)))print("Additional values in second list:", (set(list2).difference(list1)))  # prints the missing and additional elements in list1print("Missing values in first list:", (set(list2).difference(list1)))print("Additional values in first list:", (set(list1).difference(list2)))
Output:
Missing values in second list: {1, 2, 3}
Additional values in second list: {7, 8}
Missing values in first list: {7, 8}
Additional values in first list: {1, 2, 3}

Python list-programs
Python set-programs
python-list
python-set
Python
python-list
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Area of Largest rectangle that can be inscribed in an Ellipse?

Here we will see the area of largest rectangle that can be inscribed in an ellipse. The rectangle in ellipse will be like below −
The a and b are the half of major and minor axis of the ellipse. The upper right corner of the rectangle is (x, y). So the area is
Now, after making this equation as f(x) and maximizing the area, we will get the area as
#include <iostream>
#include <cmath>
using namespace std;
float area(float a, float b) {
   if (a < 0 || b < 0 ) //if the valuse are negative it is invalid
      return -1;
   float area = 2*a*b;
   return area;
}
int main() {
   float a = 10, b = 8;
   cout << "Area : " << area(a, b);
}
Area : 160
Explain switch statement in C language

It is used to select one among multiple decisions. ‘switch’ successively tests a value against a list of integers (or) character constant. When a match is found, the statement (or) statements associated with that value are executed.
The syntax is given below −
switch (expression){
   case value1 : stmt1;
      break;
   case value2 : stmt2;
      break;
   - - - - - -
   default : stmt – x;
}
Refer the algorithm given below −
Step 1: Declare variables.
Step 2: Read expression variable.
Step 3: Switch(expression)
   If value 1 is select : stmt 1 executes break (exists from switch)
   If value 2 is select : stmt 2 executes ;break
   If value 3 is select : stmt 3 executes; break
   ...................................................
Default : stmt-x executes;
The following C program demonstrates the usage of switch statement −
 Live Demo
#include<stdio.h>
main ( ){
   int n;
   printf ("enter a number");
   scanf ("%d", &n);
   switch (n){
      case 0 : printf ("zero");
         break;
      case 1 : printf ("one");
         break;
      default : printf ("wrong choice");
   }
}
You will see the following output −
enter a number
1
One
Consider another program on switch case as mentioned below −
 Live Demo
#include<stdio.h>
int main(){
   char grade;
   printf("Enter the grade of a student:\n");
   scanf("%c",&grade);
   switch(grade){
      case 'A': printf("Distiction\n");
         break;
      case 'B': printf("First class\n");
         break;
      case 'C': printf("second class \n");
         break;
      case 'D': printf("third class\n");
         break;
      default : printf("Fail");
   }
   printf("Student grade=%c",grade);
   return 0;
}
You will see the following output −
Run 1:Enter the grade of a student:A
Distiction
Student grade=A
Run 2: Enter the grade of a student:C
Second class
Student grade=C
TimeSpan.Compare() Method in C#

The TimeSpan.Compare() method in C# is used to compare two TimeSpan values
and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value.
The return value is -1 if span1 is shorter than span2, 0 if span1=span2, whereas 1 if span1 is longer than span2.
The syntax is as follows −
public static int Compare (TimeSpan span1, TimeSpan span2);
Above, the parameter span1 is the 1st time interval to compare, whereas span2 is the 2nd interval to compare.
Let us now see an example −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = new TimeSpan(-6, 25, 0);
      TimeSpan span2 = new TimeSpan(1, 11, 25, 20);
      TimeSpan span3 = TimeSpan.MinValue;
      TimeSpan res1 = span1.Add(span2);
      TimeSpan res2 = span2.Add(span3);
      Console.WriteLine("Final Timespan (TimeSpan1 + TimeSpan2) = "+res1);
      Console.WriteLine("Final Timespan (TimeSpan2 + TimeSpan3) = "+res2);
      Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
   }
}
This will produce the following output −
Final Timespan (TimeSpan1 + TimeSpan2) = 1.05:50:20
Final Timespan (TimeSpan2 + TimeSpan3) = -10675197.15:22:45.4775808
Result (Comparison of span1 and span2) = -1
Let us now see another example −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = new TimeSpan(-6, 25, 0);
      TimeSpan span2 = new TimeSpan(1, 10, 0);
      Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
   }
}
This will produce the following output −
Result (Comparison of span1 and span2) = -1
Matrix Chain Multiplication

If a chain of matrices is given, we have to find the minimum number of the correct sequence of matrices to multiply.
We know that the matrix multiplication is associative, so four matrices ABCD, we can multiply A(BCD), (AB)(CD), (ABC)D, A(BC)D, in these sequences. Like these sequences, our task is to find which ordering is efficient to multiply.
In the given input there is an array say arr, which contains arr[] = {1, 2, 3, 4}. It means the matrices are of the order (1 x 2), (2 x 3), (3 x 4).
Input:
The orders of the input matrices. {1, 2, 3, 4}. It means the matrices are
{(1 x 2), (2 x 3), (3 x 4)}.
Output:
Minimum number of operations need multiply these three matrices. Here the result is 18.
matOrder(array, n)
Input − List of matrices, the number of matrices in the list.
Output − Minimum number of matrix multiplication.
Begin
   define table minMul of size n x n, initially fill with all 0s
   for length := 2 to n, do
      fir i:=1 to n-length, do
         j := i + length – 1
         minMul[i, j] := ∞
         for k := i to j-1, do
            q := minMul[i, k] + minMul[k+1, j] + array[i-1]*array[k]*array[j]
            if q < minMul[i, j], then minMul[i, j] := q
         done
      done
   done
   return minMul[1, n-1]
End
#include<iostream>
using namespace std;

int matOrder(int array[], int n) {
   int minMul[n][n];          //holds the number of scalar multiplication needed

   for (int i=1; i<n; i++)
      minMul[i][i] = 0;           //for multiplication with 1 matrix, cost is 0

   for (int length=2; length<n; length++) {        //find the chain length starting from 2
      for (int i=1; i<n-length+1; i++) {
         int j = i+length-1;
         minMul[i][j] = INT_MAX;     //set to infinity
         for (int k=i; k<=j-1; k++) {
            //store cost per multiplications
            int q = minMul[i][k] + minMul[k+1][j] + array[i- 1]*array[k]*array[j];
            if (q < minMul[i][j])
               minMul[i][j] = q;
         }
      }
   }
   return minMul[1][n-1];
}

int main() {
   int arr[] = {1, 2, 3, 4};
   int size = 4;
   cout << "Minimum number of matrix multiplications: " << matOrder(arr, size);
}
Minimum number of matrix multiplications: 18
How to convert a string to snake case using JavaScript ? - GeeksforGeeks

25 Dec, 2020
Given a string in and the task is to write a JavaScript code to convert the given string into snake case and print the modified string. 
Examples:
Input: GeeksForGeeks
Output: geeks_for_geeks
Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case
We use match(), map(), join, and toLowerCase() method to convert a given string into snake case string. The match() method is used to match the given string with the pattern and then use map() and toLowerCase() method to convert given string into lower case and then use join() method to join the string using underscore (_). 
Example:
HTML
<!DOCTYPE html><html>  <head>    <title>        How to convert a string to        snake case using JavaScript?    </title></head>  <body style="text-align: center;">    <h1 style="color: green;">        GeeksforGeeks    </h1>      <h3>        How to convert a string to        snake case using JavaScript?    </h3>      <script>        function snake_case_string(str) {            return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)                .map(s => s.toLowerCase())                .join('_');        }          console.log(snake_case_string('GeeksForGeeks'));        console.log(snake_case_string('Welcome to GeeksForGeeks'));        console.log(snake_case_string('Welcome-to-GeeksForGeeks'));        console.log(snake_case_string('Welcome_to_GeeksForGeeks'));    </script></body>  </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
C++ Program to Search Sorted Sequence Using Divide and Conquer with the Aid of Fibonacci Numbers

In this C++ program we implement a Divide and Conquer approach using Fibonacci numbers. Using Fibonacci numbers, we calculate mid of data array to search the data item. The time complexity of this approach is O(log(n)).
Begin
   Assign the data to the array in a sorted manner.
   Take input of the element to be searched.
   Call FibonacciSearch() function.
   Calculate the mid value using ‘start+fib[index-2]’ expression.
   If the chosen item is equal to the value at mid index, print result and return to main.
   If it is lesser than the value at mid index, proceed with the left sub-array.
   If it is more than the value at mid index, proceed with the right sub-array.
   If the calculated mid value is equal to either start or end then the item is not found in the array.
End
#include<iostream>
using namespace std;
void FibonacciSearch(int *a, int start, int end, int *fib, int index, int item) {
   int i, mid;
   mid = start+fib[index-2];
   if(item == a[mid]) {
      cout<<"\n item found at "<<mid<<" index.";
      return;
   } else if(item == a[start]) {
      cout<<"\n item found at "<<start<<" index.";
      return;
   } else if(item == a[end]) {
      cout<<"\n item found at "<<end<<" index.";
      return;
   } else if(mid == start || mid == end) {
      cout<<"\nElement not found";
      return;
   } else if(item > a[mid])
         FibonacciSearch(a, mid, end, fib, index-1, item);
      else
         FibonacciSearch(a, start, mid, fib, index-2, item);
   }
   main() {
      int n, i, fib[20], a[10]={3, 7, 55, 86, 7, 15, 26, 30, 46, 95};
      char ch;
      fib[0] = 0;
      fib[1] = 1;
      i = 1;
      while(fib[i] < 10) {
         i++;
         fib[i] = fib[i-1] + fib[i-2];
      }
      up:
         cout<<"\nEnter the Element to be searched: ";
         cin>>n;
         FibonacciSearch(a, 0, 9, fib, i, n);
         cout<<"\n\n\tDo you want to search more...enter choice(y/n)?";
         cin>>ch;
         if(ch == 'y' || ch == 'Y')
            goto up;
         return 0;
   }
}
Enter the Element to be searched: 26
item found at 6 index.
Do you want to search more...enter choice(y/n)?y
Enter the Element to be searched: 45
item not found
Do you want to search more...enter choice(y/n)?n
What is a register storage class in C language?

There are four storage classes in C programming language, which are as follows −
auto
extern
static
register
The keyword is register.
The keyword is register.
Register variable values are stored in CPU registers, rather than in memory where, normal variables are stored.
Register variable values are stored in CPU registers, rather than in memory where, normal variables are stored.
Registers are temporary storage units in CPU.
Registers are temporary storage units in CPU.
They allow faster access time for register variables than normal variables.
They allow faster access time for register variables than normal variables.
Following is the C program for register storage class −
 Live Demo
#include<stdio.h>
main ( ){
   register int i;
   for (i=1; i<=5; i++)
      printf ("%d ",i);
}
The output is stated below −
1 2 3 4 5
Consider another C program for register storage class −
 Live Demo
#include<stdio.h>
int main(){
   register int a;
   printf("%d",a); //prints default value of a =0
}
The output is stated below −
0
Following is the third C program for static storage class −
#include<stdio.h>
int main(){
   register int i = 10;
   int *p;
   //int *p = &i; //error occurred ,here we are trying to request address of register    variable
   printf("Value of i: %d", *p);
   printf("Address of i: %u", p);
}
The output is stated below −
Error:add of reg var?
How to make an image responsive in HTML?

To make an image responsive, you need to set two properties. Add image using the <img> tag and add CSS style for height and max-width to make it responsive. For example, style="height:auto;max-width:100%;"
You can try to run the following code to make an image responsive in HTML −Note − To check the responsiveness of an image, resize the browser tab. If the image resizes correctly, then it means it is responsive.
<!DOCTYPE html>
<html>
   <head></head>
   <body>
      <img src="https://www.tutorialspoint.com/images/video_tutorial_intro.jpg" alt="Video Tutorials" style="height:auto;max-width:100%;">
   </body>
</html>
Convert list of numerical string to list of Integers in Python

For data manipulation using python, we may come across scenario where we have strings containing numbers in a list. To be able to make calculations, we will need to change the strings into numbers. In this article we will see the ways to change the strings into numbers inside a list.
The int function can be applied to the string elements of a list converting them to integers . We have to carefully design the for loops to go through each element and get the result even if there are multiple strings inside a single element.
 Live Demo
listA = [['29','12'], ['25'], ['70']]
# Given lists
print("Given list A: ", listA)
# Use int
res = [[int(n) for n in element] for i in listA for element in i]
# Result
print("The numeric lists: ",res)
Running the above code gives us the following result −
Given list A: [['29', '12'], ['25'], ['70']]
The numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]]
We can also use the map function which will apply a given function again and again to each parameter that is supplied to this function. We create a for loop which fetches the elements form each of the inner lists. This approach does not work if the inner lists have multiple elements inside them.
 Live Demo
listA = [['29'], ['25'], ['70']]
# Given lists
print("Given list A: ", listA)
# Use map
res = [list(map(int, list(elem[0]))) for elem in listA if elem ]
# Result
print("The numeric lists: ",res)
Running the above code gives us the following result −
Given list A: [['29'], ['25'], ['70']]
The numeric lists: [[2, 9], [2, 5], [7, 0]]
How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar?

Let's take an example to see how to display a 3D plot of a 3D array isosurface in matplotlib −
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x, y)
h = x ** 2 + y ** 2
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, h, rstride=1, cstride=1, cmap=plt.cm.rainbow, linewidth=0, antialiased=False)
plt.show()
MySQL get hash value for each row?

Get hash value of each row using MD5() function from MySQL. The syntax is as follows −
SELECT MD5(CONCAT(yourColumnName1,yourColumnName2,yourColumnName3,.......N)) as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table getHashValueForEachRow
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> Marks int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.25 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Larry',24,89);
Query OK, 1 row affected (0.22 sec)

mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('David',26,98);
Query OK, 1 row affected (0.24 sec)

mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Bob',21,67);
Query OK, 1 row affected (0.20 sec)

mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Sam',22,56);
Query OK, 1 row affected (0.22 sec)

mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Mike',25,80);
Query OK, 1 row affected (0.72 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from getHashValueForEachRow;
The following is the output −
+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
|  1 | Larry |   24 | 89    |
|  2 | David |   26 | 98    |
|  3 | Bob   |   21 | 67    |
|  4 | Sam   |   22 | 56    |
|  5 | Mike 25 | 80 |       |
+----+-------+------+-------+
5 rows in set (0.00 sec)
The following is the query to get hash value of each row −
mysql> select md5(concat(Id,Name,Age,Marks)) as HashValueOfEachRow from getHashValueForEachRow;
Here is the output −
+----------------------------------+
| HashValueOfEachRow               |
+----------------------------------+
| a5f6b8e1a701d467cf1b4d141027ca27 |
| 6e649522c773b6a6672e625939eb4225 |
| 8bd419e9b7e9e014a4dc0596d70e93c8 |
| 504cf50194a2a6e3481dfa9b8568b9e6 |
| 08716a8dad7105a00c49ea30d278b315 |
+----------------------------------+
5 rows in set (0.00 sec)
Find elements of array using XOR of consecutive elements in C++

Consider we have to find a list of n elements. But we have the XOR value of two consecutive elements of the actual array. Also the first element of the actual is given. So if the array elements are a, b, c, d, e, f, then the given array will be a^b, b^c, c^d, d^e and e^f.
As the first number is given, named a, that can help us to find all numbers. If we want to find the second element of the actual array, then we have to perform b = a ^ arr[i], for second element c = b ^ arr[1] and so on.
#include<iostream>
using namespace std;
void findActualElements(int a, int arr[], int n) {
   int actual[n + 1];
   actual[0] = a;
   for (int i = 0; i < n; i++) {
      actual[i + 1] = arr[i] ^ actual[i];
   }
   for (int i = 0; i < n + 1; i++)
      cout << actual[i] << " ";
}
int main() {
   int arr[] = { 12, 5, 26, 7 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int a = 6;
   findActualElements(a, arr, n);
}
6 10 15 21 18
Program to calculate area and perimeter of equilateral triangle

Tringle is a closed figure with three sides. An equilateral triangle has all sides equal. Area and perimeter of an equilateral triangle can be found using the below formula,
Area of equilateral triangle = (√3)/4*a2
Perimeter of equilateral triangle = 3 * a
To find the area of an equilateral triangle program uses square-root and power functions. The math library has both these functions and can be used to do the calculation in the program.
The below code display program to calculate the area and perimeter of an equilateral triangle,
 Live Demo
#include <stdio.h>
#include <math.h>
int main(){
   int side = 5, perimeter;
   float area;
   perimeter = (3 * side);
   area = (sqrt(3)/4)*(side*side);
   printf("perimeter is %d\n", perimeter);
   printf("area is %f", area);
   return 0;
}
perimeter is 15
area is 10.825317
Roll In Animation Effect with CSS

To create a roll in animation effect with CSS, you can try to run the following code −
Live Demo
<html>
   <head>
      <style>
         .animated {
            background-image: url(/css/images/logo.png);
            background-repeat: no-repeat;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;
            animation-duration: 10s;
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
         }
         @-webkit-keyframes rollIn {
            0% {
               opacity: 0;
               -webkit-transform: translateX(-100%) rotate(-120deg);
            }
            100% {
               opacity: 1;
               -webkit-transform: translateX(0px) rotate(0deg);
            }
         }
         @keyframes rollIn {
            0% {
               opacity: 0;
               transform: translateX(-100%) rotate(-120deg);
            }
            100% {
               opacity: 1;
               transform: translateX(0px) rotate(0deg);
            }  
         }
         .rollIn {
            -webkit-animation-name: rollIn;
            animation-name: rollIn;
         }
      </style>
   </head>

   <body>
      <div id = "animated-example" class = "animated rollIn"></div>
      <button onclick = "myFunction()">Reload page</button>
      <script>
         function myFunction() {
            location.reload();
         }
      </script>
   </body>
</html>
How to delete element from an array in MongoDB?

To delete element from an array, use $pull. Let us create a collection with documents −
> db.demo279.insertOne({id:[101,103,105,110]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e490af7dd099650a5401a58")
}
> db.demo279.insertOne({id:[107,111,110]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e490b06dd099650a5401a59")
}
Display all documents from a collection with the help of find() method −
> db.demo279.find();
This will produce the following output −
{ "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105, 110 ] }
{ "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111, 110 ] }
Following is the query to delete element from an array &minus';
> db.demo279.update({},{$pull:{id:110}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Display all documents from a collection with the help of find() method −
> db.demo279.find();
This will produce the following output −
{ "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105 ] }
{ "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111 ] }
MongoDB – Multiply Operator ($mul)

10 May, 2020
MongoDB provides different types of field update operators to update the values of the fields of the documents and $mul operator is one of them. This operator is used to multiply the value of the field by a number.
$mul operator only updates those fields whose value are of numeric type like int, float, etc.
If the specified field is not present in the document, then this operator will add that field in the document and assign the value of that field to zero of the same numeric type as the multiplier.
This operator is an atomic operation within a single document.
In this operator, multiplication with values of mixed numeric types like 32-bit integer, 64-bit integer, float, etc., may result in conversion of numeric type. The following rules are applied in the multiplication with the values of mixed numeric types:32-bit Integer64-bit IntegerFloat32-bit Integer32-bit or 64-bit Integer64-bit IntegerFloat64-bit Integer64-bit Integer64-bit IntegerFloatFloatFloatFloatFloat
$mul operator can also work with embedded/nested documents or arrays. You can use this operator in methods like update(), findAndModify(), etc., according to your requirements.
Syntax:
{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }
Here, <field> can specify with dot notation in embedded/nested documents.
In the following examples, we are working with:
Database: FruitsCollection: DetailsDocument: two documents that contain the details of the fruits in the form of field-value pairs.
In this example, we are multiplying the value of price field by 2.10 in the document who matches the specified condition, i.e., name = mango.
db.Details.update({name: "mango"}, {$mul: {price: NumberDecimal("2.10")}})
In this example, we are multiplying the value of quantity.tQuantity field by 3 in the document who matches the specified condition, i.e., name = mango.
db.Details.update({name: "mango"}, {$mul: {"quantity.tQuantity": 3}})
In this example, we are applying $mul operator to a non- existing field in the document who matches the specified condition, i.e., name = apple.
db.Details.update({name: "apple"}, {$mul: {"batchNumber":NumberInt(230)}})
In this example, we are multiplying the value(float type) of price field in the document who matches the specified condition, i.e., name = apple.
db.Details.update({name: "apple"}, {$mul: {price: NumberDecimal(5)}})
MongoDB
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
How to connect MongoDB with ReactJS ?
Upsert in MongoDB
MongoDB - Check the existence of the fields in the specified collection
How to build a basic CRUD app with Node.js and ReactJS ?
MongoDB: An introduction
MongoDB - limit() Method
Python | Sort words of sentence in ascending order

22 Nov, 2019
Given a sentence, sort it alphabetically in ascending order.
Examples:
Input : to learn programming refer geeksforgeeks
Output : geeksforgeeks learn programming refer to

Input : geeks for geeks
Output : for geeks geeks

We will use built in library function to sort the words of the sentence in ascending order.Prerequisites:1. split()2. sort() in Python3. join()
Split the Sentence in words.
Sort the words alphabetically
Join the sorted words alphabetically to form a new Sentence.
Below is the implementation of above idea.
# Function to sort the words# in ascending orderdef sortedSentence(Sentence):          # Splitting the Sentence into words    words = Sentence.split(" ")          # Sorting the words    words.sort()          # Making new Sentence by     # joining the sorted words    newSentence = " ".join(words)          # Return newSentence    return newSentence  # Driver's Code  Sentence = "to learn programming refer geeksforgeeks"# Print the sortedSentenceprint(sortedSentence(Sentence))  Sentence = "geeks for geeks"# Print the sortedSentenceprint(sortedSentence(Sentence))
Output:
geeksforgeeks learn programming refer to
for geeks geeks

shubham_singh
python-string
Python
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.