code-rag-bench/online-tutorials huggingface dataset:
PyQt5 QSpinBox - Getting current value - GeeksforGeeks

03 May, 2020
In this article we will see how we can get the current value of the spin box. By default its value is 0 although user can change it any time and programmatically we use setValue method to change its value.
In order to get the value of spin box we use value method
Syntax : spin.value()
Argument : It takes no argument
Return : It returns integer i.e current value
Implementation steps –
1. Create a spin box widget2. Create a label to show current value3. Add action to the spin box4. Inside the action get the current value with the help of value method5. Show this value with the help of label.
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import *import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 100, 40)          # adding action to the spin box        self.spin.valueChanged.connect(self.show_result)          # creating label show result        self.label = QLabel(self)          # setting geometry        self.label.setGeometry(100, 200, 200, 40)      # method called by spin box    def show_result(self):          # getting current value        value = self.spin.value()          # setting value of spin box to the label        self.label.setText("Value : " + str(value))    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  window.show()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Write a program in Python Pandas to convert a dataframe Celsius data column into Fahrenheit

The result for converting celsius to Fahrenheit as,
 Id Celsius Fahrenheit
0 1  37.5    99.5
1 2  36.0    96.8
2 3  40.0    104.0
3 4  38.5    101.3
4 5  39.0    102.2
To solve this, we will follow below approaches −
Define a dataframe with ‘Id’ and ‘Celsius’ column values
Define a dataframe with ‘Id’ and ‘Celsius’ column values
Apply df.assign function inside write lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and assign it to Fahrenheit. It is defined below −
Apply df.assign function inside write lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and assign it to Fahrenheit. It is defined below −
df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32)
Let’s check the following code to get a better understanding −
import pandas as pd
df = pd.DataFrame({'Id':[1,2,3,4,5],
                     'Celsius':[37.5,36,40,38.5,39]
                  })
print("DataFrame is\n",df)
df = df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32)
print(df)
DataFrame is
 Id Celsius
0 1 37.5
1 2 36.0
2 3 40.0
3 4 38.5
4 5 39.0
 Id Celsius Fahrenheit
0 1  37.5    99.5
1 2  36.0    96.8
2 3  40.0    104.0
3 4  38.5    101.3
4 5  39.0    102.2
Define a dataframe with ‘Id’ and ‘Celsius’ column values
Define a dataframe with ‘Id’ and ‘Celsius’ column values
Set df.apply function inside writing lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and save it as inside df[Fahrenheit]. It is defined below,
Set df.apply function inside writing lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and save it as inside df[Fahrenheit]. It is defined below,
df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32,axis=1)
Let’s check the following code to get a better understanding −
import pandas as pd
df = pd.DataFrame({'Id':[1,2,3,4,5],
                     'Celsius':[37.5,36,40,38.5,39]
                  })
print("DataFrame is\n",df)
df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32,axis=1)
print(df)
DataFrame is
 Id Celsius
0 1 37.5
1 2 36.0
2 3 40.0
3 4 38.5
4 5 39.0
 Id Celsius Fahrenheit
0 1  37.5    99.5
1 2  36.0    96.8
2 3  40.0    104.0
3 4  38.5    101.3
4 5  39.0    102.2
W3.CSS Examples

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.
Python program to capitalize the first letter of every word in the file - GeeksforGeeks

26 Nov, 2020
The following article contains programs to read a file and capitalize the first letter of every word in the file and print it as output. To capitalize the first letter we will use the title() function in python. The title function in python is the Python String Method which is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the string and returns the new string.
Examples:
# Content of the file serves as input
Input: hello world
Output: Hello World

# Content of the file serves as input
Input: geeks for geeks
Output: Geeks For Geeks

Approach:
We will take the content of the file as input.
We will open the file and save its content by using the open() function in python.
Printing the content after altering it.
Input File:
Content of the gfg.txt file
Below is the Implementation.
Python3
# Python program to read a file and capitalize# the first letter of every word in the file.  # A file named "gfg", will be opened with the # reading mode. file_gfg = open('gfg.txt', 'r')  # This will traverse through every line one by one# in the filefor line in file_gfg:          # This will convert the content    # of that line with capitalized    # first letter of every word    output = line.title()          # This will print the output    print(output)
Output:
Geeksforgeeks Is A Computer Science  Portal For Geeks. It Contains Well Written, Well Thought And Well Explained Computer Science And Programming Articles, Quizzes Etc.
Python file-handling-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How can I shutdown MySQL Server?

With the help of ‘mysqladmin’ program we would be able to shutdown our MySQL server. It can be used as follows on command line −
C:\mysql\bin>mysqladmin -u root shutdown
We will see nothing after entering the above command because it will not print any message in command window. We should have to trust that MySQL server has been shutdown properly.
OpenCV - Canny Edge Detection

Canny Edge Detection is used to detect the edges in an image. It accepts a gray scale image as input and it uses a multistage algorithm.
You can perform this operation on an image using the Canny() method of the imgproc class, following is the syntax of this method.
Canny(image, edges, threshold1, threshold2)

This method accepts the following parameters −
image − A Mat object representing the source (input image) for this operation.
image − A Mat object representing the source (input image) for this operation.
edges − A Mat object representing the destination (edges) for this operation.
edges − A Mat object representing the destination (edges) for this operation.
threshold1 − A variable of the type double representing the first threshold for the hysteresis procedure.
threshold1 − A variable of the type double representing the first threshold for the hysteresis procedure.
threshold2 − A variable of the type double representing the second threshold for the hysteresis procedure.
threshold2 − A variable of the type double representing the second threshold for the hysteresis procedure.
Following program is an example demonstrating, how to perform Canny Edge Detection operation on a given image.
import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class CannyEdgeDetection {
   public static void main(String args[]) throws Exception {
      // Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

      // Reading the Image from the file and storing it in to a Matrix object
      String file = "E:/OpenCV/chap17/canny_input.jpg";

      // Reading the image
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat gray = new Mat();

      // Converting the image from color to Gray
      Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
      Mat edges = new Mat();

      // Detecting the edges
      Imgproc.Canny(gray, edges, 60, 60*3);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap17/canny_output.jpg", edges);
      System.out.println("Image Loaded");
   } 
}
Assume that following is the input image canny_input.jpg specified in the above program.
On executing the above program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows −

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
How can we set the background/foreground color for individual column of a JTable in Java?

A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableColumnColorTest extends JFrame {
   private JTable table;
   private TableColumn tColumn;
   public JTableColumnColorTest() {
      setTitle("JTableColumnColor Test");
      table = new JTable(10, 5);
      tColumn = table.getColumnModel().getColumn(2);
      tColumn.setCellRenderer(new ColumnColorRenderer(Color.lightGray, Color.red));
      add(new JScrollPane(table), BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String [] args) {
      new JTableColumnColorTest();
   }
}
// Customize the code to set the background and foreground color for each column of a JTable
class ColumnColorRenderer extends DefaultTableCellRenderer {
   Color backgroundColor, foregroundColor;
   public ColumnColorRenderer(Color backgroundColor, Color foregroundColor) {
      super();
      this.backgroundColor = backgroundColor;
      this.foregroundColor = foregroundColor;
   }
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,   boolean hasFocus, int row, int column) {
      Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      cell.setBackground(backgroundColor);
      cell.setForeground(foregroundColor);
      return cell;
   }
}
MySQL's DESCRIBE command?

The MySQL’s DESCRIBE or DESC both are equivalent. The DESC is the short form of DESCRIBE command and used to dipslay the information about a table like column names and constraints on column name.
The DESCRIBE command is equivalent to the following command −
SHOW columns from yourTableName command.
The following is the query that display information about a table with the help of DESCRIBE command. The query is as follows.
mysql> DESCRIBE Student;
Above, Student is the table name in my database.
The above query generates the following output.
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | YES  | MUL | NULL    |       |
| Name  | varchar(100) | YES  | MUL | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.13 sec)

Here is the equivalent query that gives the same result. The query is as follows.
mysql> show columns from student;
The following is the output.
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | YES  | MUL | NULL    |       |
| Name  | varchar(100) | YES  | MUL | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.03 sec)

As you see above, both of them gives the same output.
C Quiz - 101 | Question 1 - GeeksforGeeks

28 Jun, 2021
Suppose that in a C program snippet, followings statements are used.
i) sizeof(int);ii) sizeof(int*);iii) sizeof(int**);
Assuming size of pointer is 4 bytes and size of int is also 4 bytes, pick the most correct answer from the given options.(A) Only i) would compile successfully and it would return size as 4.(B) i), ii) and iii) would compile successfully and size of each would be same i.e. 4(C) i), ii) and iii) would compile successfully but the size of each would be different and would be decided at run time.(D) ii) and iii) would result in compile error but i) would compile and result in size as 4.Answer: (B)Explanation: Size of all pointer types is same.
And whether it is a ‘pointer to char’ or ‘pointer to int’ or ‘pointer to pointer to int’, the size always remain same.
That’s why all i), ii) and iii) would compile successfully and would result in same size value of 4.Quiz of this Question
C Quiz - 101
C-C Quiz - 101
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to dynamically allocate a 2D array in C?
fgets() and gets() in C language
Exception Handling in C++
void pointer in C / C++
sizeof operator in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Misc | Question 7
Output of C programs | Set 64 (Pointers)
GitLab - Create Backup

GitLab allows to take backup copy of your repository by using simple command. In this chapter, we will discuss about how to take backup copy in the GitLab −
Step 1 − First, login to your GitLab server using SSH (Secure Shell).
Step 2 − Create the backup of GitLab by using the below command −
sudo gitlab-rake gitlab:backup:create
Step 3 − You can exclude some directories from the backup by adding environment variable SKIP as shown below −
sudo gitlab-rake gitlab:backup:create SKIP = db,uploads
Step 4 − The backup tar file will get created in the default /var/opt/gitlab/backups directory. Navigate to this path and type ls -l to see the created backup file −
 Print
 Add Notes
 Bookmark this page
Select into in MySQL?

To do select into in MySQL, use CREATE TABLE SELECT command. The syntax is as follows −
CREATE TABLE yourTableName SELECT *FROM yourOriginalTableName;
To understand, let us first create a table −
mysql> create table SelectIntoDemo
-> (
-> Id int,
-> Name varchar(200)
-> );
Query OK, 0 rows affected (0.50 sec)
Let us insert some records into the table with the help of insert command. The query is as follows −
mysql> insert into SelectIntoDemo values(1,'Bob'),(2,'Carol'),(3,'David');
Query OK, 3 rows affected (0.15 sec)
Records: 3 Duplicates: 0 Warnings: 0
Displaying all records with the help of select statement. The query is as follows −
mysql> select *from SelectIntoDemo;
Here is the output −
+------+-------+
| Id   | Name |
+------+-------+
| 1    | Bob   |
| 2    | Carol |
| 3    | David |
+------+-------+
3 rows in set (0.00 sec)
Now you can apply the above syntax discussed in the beginning. The query is as follows −
mysql> create table yourTempTable select *from SelectIntoDemo;
Query OK, 3 rows affected (0.56 sec)
Records: 3 Duplicates: 0 Warnings: 0
Check all records with new table name “yourTempTable”. The query is as follows −
mysql> select *from yourTempTable;
The following is the output −
+------+-------+
| Id   | Name  |
+------+-------+
| 1    | Bob   |
| 2    | Carol |
| 3    | David |
+------+-------+
3 rows in set (0.00 sec)
PyQt5 QListWidget - Current Item Changed Signal - GeeksforGeeks

01 Aug, 2020
In this article we will see how we can get the current item changed signal of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item. Unless the selection mode is NoSelection, the item is also selected. It can be set with the help of setCurrentItem method. This signal is emitted when current item is changed.
In order to do this we will use currentItemChanged method with the list widget object.
Syntax : list_widget.currentItemChanged.connect(method)
Argument : It takes method as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting current item        list_widget.setCurrentItem(item2)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)          # getting item changed signal        list_widget.currentItemChanged.connect(lambda: label.setText("Item Changed Signal"))                   # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
CSS3 top to bottom Gradient

You can try to run the following code to implement top to the bottom gradient in CSS3 −
Live Demo
<html>
   <head>
      <style>
         #grad1 {
            height: 100px;
            background: -webkit-linear-gradient(pink,green);
            background: -o-linear-gradient(pink,green);
            background: -moz-linear-gradient(pink,green);
           background: linear-gradient(pink,green);
         }
      </style>
   </head>
   <body>
       <div id = "grad1"></div>
   </body>
</html>
How to overwrite a specific chunk in a byte array using java?

Java provides a ByteBuffer class which allows you to wrap an array into a byte buffer using its wrap() method. Once you did that you can replace the contents of the buffer using the position(): To select the starting position and, put(): To replace the data methods:
Live Demo
import java.nio.ByteBuffer;

public class OverwriteChunkOfByteArray {
   public static void main(String args[]) {
      String str = "Hello how are you what are you doing";
      byte[] byteArray = str.getBytes();
      System.out.println("Contents of the byet array :: ");
     
      for(int i = 0; i<byteArray.length; i++) {
         System.out.println((char)byteArray[i]);
      }
      ByteBuffer buffer = ByteBuffer.wrap(byteArray);
      byte[] newArray = "where do you live ".getBytes();
      buffer.position(18);
      buffer.put(newArray);
      System.out.println("Contents of the byte array after replacement::");
     
      for(int i = 0; i<byteArray.length; i++) {
         System.out.println((char)byteArray[i]);
      }
   }
}
of the byte array ::
H
e
l
l
o

h
o
w

a
r
e

y
o
u

w
h
a
t

a
r
e

y
o
u

d
o
i
n
g
Contents of the byet array after replacement ::
H
e
l
l
o

h
o
w

a
r
e

y
o
u

w
h
e
r
e

d
o

y
o
u

l
i
v
e
How do I get time of a Python program's execution?

To measure time time of a program's execution, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes. 
import time
t0= time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)
This will give the output −
Time elapsed:  0.0009403145040156798
You can also use the timeit module to get proper statistical analysis of a code snippet's execution time.  It runs the snippet multiple times and then it tells you how long the shortest run took. You can use it as follows −
def f(x):
  return x * x
 
import timeit
timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)
This will give the output −
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
How to write a JavaScript function to get the difference between two numbers?

Use Math.abs() inside a JavaScript function to get the difference between two numbers in JavaScript.
You can try to run the following code to get the difference of numbers
Live Demo
<html>
   <head>
      <script>
         var num1, num2;
         num1 = 50;
         num2 = 35;
         var difference = function (num1, num2){
            return Math.abs(num1 - num2);
         }
         document.write("Difference = "+difference(num1,num2));
      </script>
   </head>
   <body></body>
</html>
What is a fat arrow function in JavaScript?

Fat arrow function as the name suggests helps in decreasing line of code. The syntax => shows fat arrow. This also avoids you to write the keyword “function” repeatedly.
Here’s the syntax:
argument => expression
Use the following for more than one argument:
(argument1 [, argument2]) => expression
Let’s compare a function with and without fat arrow:
Function in JavaScript
var rank = [7,8,9];
var display = rank.map(function(num) {
   return num * num;
});
Fat Arrow function in JavaScript
var rank= [7,8,9];
var display = rank.map((num) => num*num);
document.write(arr)
Arrow function definitely reduces the code lines.
How to handle errors in HTML5 Web Workers?

The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console.
<!DOCTYPE HTML>
<html>
   <head>
      <title>Big for loop</title>
      <script>
         var worker = new Worker('bigLoop.js');
         worker.onmessage = function (event) {
            alert("Completed " + event.data + "iterations" );
         };
         worker.onerror = function (event) {
            console.log(event.message, event);
         };
         function sayHello(){
            alert("Hello sir...." );
         }
      </script>
   </head>
   <body>
      <input type = "button" onclick = "sayHello();" value = "Say Hello"/>
   </body>
</html>
DATE() and DATE_ADD() Function in MariaDB - GeeksforGeeks

27 Nov, 2020
1. DATE() Function :
In MariaDB, the DATE() function is used to return extracts the date value from a date or datetime expression. In this function, the first parameter will be a date or DateTime. This function will return extracts the date value from the expression. If the expression is not date or DateTime then this function will return the NULL Value.
Syntax :
DATE(expression)
Parameter :
Expression – date or DateTime value.
Returns : The date value from datetime.
Example-1 :
SELECT DATE('2020-09-11 11:13:19');
Output :
'2020-09-11'
Example-2 :
SELECT DATE('2020-04-12 11:13:01.000001');
Output :
'2020-04-12'
Example-3 :
SELECT DATE('Today is 2020-10-17');
Output :
NULL
2. DATE_ADD() Function :
 In MariaDB, the DATE_ADD() Function is used to return the time/DateTime value after which a certain date /timeinterval has been added. In this function, the first parameter will be a start_value and the second parameter will be the interval value. This function will return DateTime with the adding given interval. This function works similar to the DATE_SUB function. If the given interval is negative.If the interval value that is too short for the unit then DATE_ADD function will assume that the left-most portion of the interval value was not provided.
Syntax :
DATE_ADD(date, INTERVAL value unit)
Parameters :
Date – Date to which the interval should be added.
Days – Number of days to add to date.
value – The time/date interval that you wish to add.
unit – The unit type of the interval such as DAY, MONTH, MINUTE, HOUR, etc.
Returns : Time/DateTime value after which a certain date interval has been added.
Example-1 :
SELECT DATE_ADD('2020-01-10 08:44:21', INTERVAL 25 MINUTE);
Output :
'2020-01-10 09:09:21'
Example-2 :
SELECT DATE_ADD('2014-05-17 08:44:21.000001', INTERVAL '7 1:03:12.000001' DAY_MICROSECOND);
Output :
'2014-05-24 09:47:33.000002'
Example-3 :
SELECT DATE_ADD('2019-07-10', INTERVAL '1-2' YEAR_MONTH);
Output :
'2020-09-10'
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | DROP, TRUNCATE
How to Select Data Between Two Dates and Times in SQL Server?
SQL vs NoSQL: Which one is better to use?
Advanced SQL Interview Questions
SQL | OFFSET-FETCH Clause
Insert multiple values into multiple tables using a single statement in SQL Server
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Comments
SQL | CREATE
Adding multiple constraints in a single table
Accessing variables of a data frame in R Programming - attach() and detach() function - GeeksforGeeks

23 Dec, 2021
In this article, we will see how to Access variables of a data frame in R Programming Language.
attach() function in R Language is used to access the variables present in the data framework without calling the data frame.
Syntax: attach(data, pos)
Parameters: 
data: data frame
pos: position of database
Example: Accessing variables of a data frame in R using attach() function
R
# R program to illustrate# attach function # Create example datadata <- data.frame(x1 = c(1, 2, 3, 4, 5),                       x2 = c(6, 7, 8, 9, 0),                x3 = c(1, 2, 5, 4, 5)) # Try to print x1# Error: object 'x1' not found # attach dataattach(data, pos = x1)                                           
Output: 
1 2 3 4 5
Here in the above code, we have created a data framework and assigned a value to it, when we tried to return value an error occurred. Then we use the attach function and returned value of x1.
detach() function is used to remove the attachment in data framework that was made by attach() function.
Syntax: detach(data, unload)
Parameters: 
data: data frame
unload: boolean value
Example: Accessing variables of a data frame in R using detach() Function 
R
# R program to illustrate# detach function # Install dplyr packageinstall.packages("dplyr") # attach dplyrlibrary("dplyr")                                # Apply as.tbl function of dplyr packagedata_tbl <- as.tbl(data)                        detach("package:dplyr", unload = FALSE) # Apply as.tbl after detaching dplyr packagedata_tbl <- as.tbl(data)
Output: 
Error in as.tbl(data) : could not find function “as.tbl”
Here in the above code, we have installed a dplyr package and used its function as.tbl. Then we detach the package and try to use the function again, and an error occurred. detach functions are used to unpack the libraries which were added to the library.
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Remove rows with NA in one column of R DataFrame
K-Means Clustering in R Programming
Angular 10 NgTemplateOutlet Directive - GeeksforGeeks

03 Jun, 2021
In this article, we are going to see what is NgTemplateOutlet in Angular 10 and how to use it.
The NgTemplateOutlet in Angular10 is used to insert an embedded view from a prepared TemplateRef. NgTemplateOutlet adds the reference element which is displayed on the page.
Syntax:
<li *NgTemplateOutlet='condition'></li>
NgModule: Module used by NgTemplateOutlet is:
CommonModule
 
Selectors:
[NgTemplateOutlet]
Approach: 
Create an angular app to be used.
There is no need for any import for the NgIf to be used.
in app.component.html add NgTemplateOutlet Directive to the element with its reference.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.html
<ng-container *ngTemplateOutlet="gfg"></ng-container>  <ng-template #gfg>    <h1>GeeksforGeeks</h1>      <div>        ngTemplateOutlet Directive    </div></ng-template>
Output:
Example 2:
app.component.html
<div *ngTemplateOutlet="gfg"></div>  <ng-template #gfg>    <h1>        GeeksforGeeks    </h1>    <div>        We can also use ngTemplateOutlet Directive with a div     </div></ng-template>
Output:
Reference: https://angular.io/api/common/NgTemplateOutlet
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to download images using Invoke-Webrequest in PowerShell?

To download the images from the webpage using the Invoke-WebRequest command, we can use the images property from the result to retrieve the images URL, and later we can use the method to download them at the specific location. Consider we have the URI: https://theautomationcode.com to retrieve the images.
Once you run the below command, you can see the Images property there.
Invoke-WebRequest -Uri "https://theautomationcode.com/feed/"
To retrieves the images URL,
$req = Invoke-WebRequest -Uri "https://theautomationcode.com/feed/"
$req.Images | Select -ExpandProperty src
https://i1.wp.com/theautomationcode.com/wp-content/uploads/2020/11/image-9.png?resize=178%2C60&ssl=1 https://i0.wp.com/theautomationcode.com/wp-content/uploads/2020/11/image-10.png?resize=640%2C68&ssl=1
All the above URLs point to the images, so we can download that.
$wc = New-Object System.Net.WebClient
$req = Invoke-WebRequest -Uri "https://theautomationcode.com/feed/"
$images = $req.Images | Select -ExpandProperty src
$count = 0
foreach($img in $images){    
   $wc.DownloadFile($img,"C:\Temp\WebImages\img$count.jpg")
}
The output images will be stored in the C:\temp\WebImages folder.
How to get Time in Milliseconds for the Given date and time in Java?

The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string.
One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. 
To parse/convert a string as a Date object Instantiate this class by passing desired format string.
Parse the date string using the parse() method.
You can get the epoch time using the getTime() method.
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
   public static void main(String args[]) throws ParseException {  
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");      
      //Parsing the given String to Date object
      String str = "25-08-2009 11:20:45";
      Date date = dateformatter.parse(str);  
      long msec = date.getTime();
      System.out.println("Epoch of the given date: "+msec);
   }
}
Epoch of the given date: 1251179445000
Epoch of the given date: 1251179445000
You can set date and time values to a calendar object using the set() method. The getTimeInMillis() of this class returns the epoch time of the date value.
Live Demo
import java.util.Calendar;
public class Sample {
   public static void main(String args[]) {  
      Calendar cal = Calendar.getInstance();
      cal.set(2014, 9, 11, 10, 25, 30);
      long msec = cal.getTimeInMillis();
      System.out.print(msec);      
   }
}
1413003330758
1413003330758
You can set date and time values to a ZonedDateTime object using the of() method. The toEpochMilli() of the Instant class returns the epoch time of the date value.
Live Demo
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Sample {
   public static void main(String args[]){  
      //Creating the ZonedDateTime object
      ZoneId id = ZoneId.of("Asia/Kolkata");
      ZonedDateTime obj = ZonedDateTime.of(2014, 9, 11, 10, 25, 30, 22, id);
      Instant instant = obj.toInstant();      
      long msec = instant.toEpochMilli();
      System.out.println("Milli Seconds: "+msec);
   }
}
Milli Seconds: 1410411330000
Milli Seconds: 1410411330000
Image button with HTML5

To add image button with HTML5, use the <button> element and set the image inside it before it is closed </button> −
<button type = "submit" name = "learn" value = "myimage">
   <p>Tutorials for all</p>
   <img src="https://www.tutorialspoint.com/latest/inter-process-communication.png " />
</button>
How to use union and order by clause in MySQL?

Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set.
Let us see an example.
Creating first table
mysql> create table UnionDemo1
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.59 sec)
Inserting records into first table.
mysql> insert into UnionDemo1 values(1),(4),(10);
Query OK, 3 rows affected (0.21 sec)
Records: 3  Duplicates: 0  Warnings: 0
To display all records.
mysql> select *from UnionDemo1;
The following is the output that displays all the records.
+------+
| id   |
+------+
|    1 |
|    4 |
|   10 |
+------+
3 rows in set (0.00 sec)

Let us create second table.
mysql> create table UnionDemo2
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.54 sec)
Inserting records into second table.
mysql> insert into UnionDemo2 values(2),(3),(5),(6),(7),(8),(9);
Query OK, 7 rows affected (0.21 sec)
Records: 7  Duplicates: 0  Warnings: 0
To display all the records.
mysql> select *from UnionDemo2;
Here is the output.
+------+
| id   |
+------+
|    2 |
|    3 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
+------+
7 rows in set (0.00 sec)

Let us now see the query to apply UNION with Order by.
mysql> select id from UnionDemo1
   -> union
   -> select id from UnionDemo2
   -> order by id desc;
The following is the output.
+------+
| id   |
+------+
|   10 |
|    9 |
|    8 |
|    7 |
|    6 |
|    5 |
|    4 |
|    3 |
|    2 |
|    1 |
+------+
10 rows in set (0.05 sec)
C library function - strcpy()

The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.
Following is the declaration for strcpy() function.
char *strcpy(char *dest, const char *src)
dest − This is the pointer to the destination array where the content is to be copied.
dest − This is the pointer to the destination array where the content is to be copied.
src − This is the string to be copied.
src − This is the string to be copied.
This returns a pointer to the destination string dest.
The following example shows the usage of strcpy() function.
#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[100];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strcpy(dest, src);

   printf("Final copied string : %s\n", dest);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Final copied string : This is tutorialspoint.com


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How can I get a stack trace for a JavaScript exception?

To get a JavaScript stack trace, simply add the following in your code. It will display the stack trace −
 Live Demo
<html>
   <head>
      <script>
         function stackTrace() {
            var err = new Error();
            return err.stack;
         }

         console.log(stackTrace());
         document.write(stackTrace());
      </script>
   </head>
   <body>
      <p>Stacktrace prints above.</p>
   </body>
</html>
Char.IsUpper() Method in C#

The Char.IsUpper() method in C# indicates whether the specified Unicode character is categorized as an uppercase letter.
public static bool IsUpper (char ch);
Above, the parameter ch is the Unicode character to evaluate.
Let us now see an example to implement the Char.IsUpper() method −
using System;
public class Demo {
   public static void Main(){
      bool res;
      char val = 'H';
      Console.WriteLine("Value = "+val);
      res = Char.IsUpper(val);
      Console.WriteLine("Is the value an uppercae letter? = "+res);
   }
}
This will produce the following output −
Value = H
Is the value an uppercae letter? = True
Let us now see another example to implement IsUpper() method −
using System;
public class Demo {
   public static void Main(){
      bool res;
      char val = 'j';
      Console.WriteLine("Value = "+val);
      res = Char.IsUpper(val);
      Console.WriteLine("Is the value an uppercae letter? = "+res);
   }
}
This will produce the following output −
Value = j
Is the value an uppercae letter? = False
Program to convert binary search tree to a singly linked list in C++?

Suppose we have a binary tree; we have to convert this into a singly linked list (in place).
So, if the input is like
then the output will be
To solve this, we will follow these steps:
ser prev := null
ser prev := null
Define a recursive function solve(), that will take root as input.
Define a recursive function solve(), that will take root as input.
if root is null, then return
if root is null, then return
solve(right of root)
solve(right of root)
solve(left of root)
solve(left of root)
right of root := prev, left of root := null
right of root := prev, left of root := null
prev := root
prev := root
Let us see the following implementation to get better understanding:
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
   }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
            return;
      }else{
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
         return;
      }else{
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class Solution {
   public:
   TreeNode* prev = NULL;
   void flatten(TreeNode* root) {
      if(!root) return;
         flatten(root->right);
      flatten(root->left);
      root->right = prev;
      root->left = NULL;
      prev = root;
   }
};
main(){
   vector<int> v = {1,2,5,3,4};
   TreeNode *root = make_tree(v);
   Solution ob;
   (ob.flatten(root));
   TreeNode *ptr = root;
   while(ptr != NULL && ptr->val != 0){
      cout << ptr->val << ", ";
      ptr = ptr->right;
   }
}
{1,2,5,3,4}
1, 2, 3, 4, 5,
Pre-increment and Post-increment in C/C++

Here we will see what is the pre-increment and post-increment in C or C++. The pre-increment and post-increment both are increment operators. But they have little differences.
The pre-increment operator increments the value of a variable at first, then sends the assign it to some other variable, but in the case of postincrement, it at first assign to a variable, then increase the value.
#include<iostream>
using namespace std;
main() {
   int x, y, z;
   x = 10;
   y = 10;
   z = ++x; //z will hold 11
   cout << "Z: " << z << endl;
   z = y++; //z will hold 10, then y will be 11
   cout << "Z: " << z << " and y is: " << y << endl;
}
Z: 11
Z: 10 and y is: 11
The precedence of post increment is more than precedence of pre increment, and their associativity is also different. The associativity of pre increment is right to left, of post increment is left to right.
C++ static member variables and their initialization

Static C++ member variables are defined using the static keyword. The static member variables in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class.
The static class member variables are initialized to zero when the first object of the class is created if they are not initialized in any other way.
A program that demonstrates static member variables and their initialization in C++ is given as follows.
 Live Demo
#include <iostream>
using namespace std;
class Demo {
   public :
   static int num;
   int display() {
      cout << "The value of the static member variable num is: " << num;
   }
};
int Demo::num = 100;
int main() {
   Demo obj;
   obj.display();
   return 0;
}
The output of the above program is as follows.
The value of the static member variable num is: 100
Now let us understand the above program.
In the class Demo, the static class member variable is num. The function display() prints the value of num. The code snippet that shows this is as follows.
class Demo {
   public :
   static int num;
   int display() {
      cout << "The value of the static member variable num is: " << num;
   }
};
int Demo::num = 100;
In the function main(), an object obj of class Demo is created. Then the function display() is called that displays the value of num. The code snippet that shows this is as follows.
int main() {
   Demo obj;
   obj.display();
   return 0;
}
How to Plot Logarithmic Axes in Matplotlib? - GeeksforGeeks

21 Jan, 2021
Axes’ in all plots using Matplotlib are linear by default, yscale() and xscale() method of the matplotlib.pyplot library can be used to change the y-axis or x-axis scale to logarithmic respectively.
The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib.scale. LogScale class to the yscale or xscale method.
xscale method syntax:
Syntax : matplotlib.pyplot.xscale(value, **kwargs)
Parameters:
Value = { “linear”, “log”, “symlog”, “logit”, ... }
**kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)
Returns : Converts the x-axes to the given scale type. (Here we use the “log” scale type)
yscale method syntax:
Syntax: matplotlib.pyplot.yscale(value, **kwargs)
Parameters:
value = { “linear”, “log”, “symlog”, “logit”, ... }
**kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)
Returns : Converts the y-axes to the given scale type. (Here we use the “log” scale type)
Given below are the implementation for converting the y-axis and x-axis to logarithmic scale respectively.
Example 1: Without Logarithmic Axes. 
Python3
import matplotlib.pyplot as plt # exponential function y = 10^xdata = [10**i for i in range(5)] plt.plot(data)
Output: 
Example 2: y-axis Logarithmic Scale.
Python3
import matplotlib.pyplot as plt # exponential function y = 10^xdata = [10**i for i in range(5)] # convert y-axis to Logarithmic scaleplt.yscale("log") plt.plot(data)
Output: 
Example 3: x-axis Logarithmic Scale. 
Python3
import matplotlib.pyplot as plt # exponential function x = 10^ydatax = [ 10**i for i in range(5)]datay = [ i for i in range(5)] #convert x-axis to Logarithmic scaleplt.xscale("log") plt.plot(datax,datay)
  
Output: 
 
 
pragup
Picked
Python-matplotlib
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
sympy.log() method in Python - GeeksforGeeks

29 Jul, 2020
With the help of sympy.log() function, we can simplify the principal branch of the natural logarithm. Logarithms are taken with the natural base, e. To get a logarithm of a different base b, use log(x, y), which is essentially short-hand for log(x) / log(y). 
Syntax : sympy.log() 
Return : Return the simplified mathematical expression.  
Example #1 :  
Python3
# import sympy from sympy import *    # Use sympy.log() method gfg = log(16, 2)      print(gfg)
Output :  
4

Example #2 : 
Python3
# import sympy from sympy import *    # Use sympy.log() method gfg = log(S(8) / 3, 2)      print(gfg)
Output : 
- log(3)/log(2) + 3

SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python