code-rag-bench/online-tutorials huggingface dataset:
How to check if a variable is an array in JavaScript?

In javascript we can check whether a variable is array or not by using three methods.
The Array.isArray() method checks whether the passed variable is array or not. If the variable is an array it displays true else displays false.
Array.isArray(variableName)
Live Demo
<html>
<body>
<script type="text/javascript">
   arr = [1,2,3,4,5];
   str = "i love my india";
   document.write( Array.isArray(arr));
   document.write("</br>");
   document.write( Array.isArray(str));
</script>
</body>
</html>
true
false
The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In the following example the instanceof operator checks whether there exists an array prototype.
variable instanceof Array
Live Demo
<html>
<body>
<script type="text/javascript">
   arr = [1,2,3,4,5];
   str = "i love my india";
   document.write(str instanceof Array);
   document.write("</br>");
   document.write(arr instanceof Array);
</script>
</body>
</html>
false
true
It displays true when the variable is same as what we specified. Here we specified that the variable should be array. So when the variable is array this method displays true else displays false.
variable.constructor === Array
Live Demo
<html>
<body>
<script type="text/javascript">
   arr = [1,2,3,4,5];
   str = "i love my india";
   document.write(str.constructor === Array);
   document.write("</br>");
   document.write(arr.constructor === Array);
</script>
</body>
</html>
false
true
Combining multiple images into a single one using JavaScript

Following is the code for combining multiple images into a single one using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Combining multiple images into a single one</h1>
<img class="image" src="https://i.picsum.photos/id/845/250/250.jpg?hmac=2l7QArh4UKul2qF-JvTjaBu3-WF2KpKBgpBALmFoxWY"/>
<img class="image" src="https://i.picsum.photos/id/925/250/250.jpg?hmac=twWJdaKT46cPk1aNvB7aKdiLZoQ zvzu5VW85OEUO4ys"/>
<canvas class="result"></canvas>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to combine the two images above together</h3>
<script>
   let imgEle1 = document.querySelectorAll(".image")[0];
   let imgEle2 = document.querySelectorAll(".image")[1];
   let resEle = document.querySelector(".result");
   var context = resEle.getContext("2d");
   let BtnEle = document.querySelector(".Btn");
   BtnEle.addEventListener("click", () => {
   resEle.width = imgEle1.width;
      resEle.height = imgEle1.height;
      context.globalAlpha = 1.0;
      context.drawImage(imgEle1, 0, 0);
      context.globalAlpha = 0.5;
      context.drawImage(imgEle2, 0, 0);
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
What is the significant difference between MySQL TRUNCATE() and ROUND() function?

The TRUNCATE() function is used to return the value of X truncated to D number of decimal places. If D is 0, then the decimal point is removed. If D is negative, then D number of values in the integer part of the value is truncated. Consider the following example –
mysql> Select TRUNCATE(7.536432,2);
+----------------------+
| TRUNCATE(7.536432,2) |
+----------------------+
|                 7.53 |
+----------------------+
1 row in set (0.00 sec)
The ROUND() function returns X rounded to the nearest integer. If a second argument, D, is supplied, then the function returns X rounded to D decimal places. D must be positive or all digits to the right of the decimal point will be removed. Consider the following example −  
mysql>SELECT ROUND(5.693893);
+---------------------------------------------------------+
|                    ROUND(5.693893)                      |
+---------------------------------------------------------+
|                           6                             |
+---------------------------------------------------------+
1 row in set (0.00 sec)  

mysql>SELECT ROUND(5.693893,2);
+---------------------------------------------------------+
|                   ROUND(5.693893,2)                     |
+---------------------------------------------------------+
|                          5.69                           |
+---------------------------------------------------------+
1 row in set (0.00 sec)  
From the above definition and examples we can observe the following difference between these two functions −
ROUND() function rounds the number up or down depends upon the second argument D and the number itself(digit after D decimal places >=5 or not).  
TRUNCATE() function truncate the number up to D number of decimal places without checking whether the digit after D decimal >=5 or not.  
mysql> Select ROUND(1.289,2)AS 'AFTER ROUND',TRUNCATE(1.289,2)AS 'AFTER TRUNCATE';
+-------------+----------------+
| AFTER ROUND | AFTER TRUNCATE |
+-------------+----------------+
|        1.29 |           1.28 |
+-------------+----------------+
1 row in set (0.00 sec)
How to calculate the difference between two dates in JavaScript?

To get dates in JavaScript, use the getTime() method. Forgetting the difference between two dates, calculate the difference between date and time.
You can try to run the following code to learn how to calculate a difference between two dates −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         var dateFirst = new Date("11/25/2017");
         var dateSecond = new Date("11/28/2017");

         // time difference
         var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());

         // days difference
         var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

         // difference
         alert(diffDays);
      </script>
   </body>
</html>
Finding the multiples of a number in a given list using NumPy

In this program, we will find the index position at which a multiple of a given number exists. We will use both the Numpy and the Pandas library for this task.
Step 1: Define a Pandas series.
Step 2: Input a number n from the user.
Step 3: Find the multiples of that number from the series using argwhere() function in the numpy library.
import numpy as np

listnum = np.arange(1,20)
multiples = []

print("NumList:\n",listnum)
n = int(input("Enter the number you want to find multiples of: "))
for num in listnum:
   if num % n == 0:
      multiples.append(num)
print("Multiples of {} are {}".format(n, multiples))
NumList:
[1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
Enter the number you want to find multiples of: 5
Multiples of 5 are [5, 10, 15]
Python – tensorflow.GradientTape.gradient()

10 Jul, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 
gradient() is used to computes the gradient using operations recorded in context of this tape.
Syntax: gradient(target, sources, output_gradients, unconnected_gradients)
Parameters:
target: It is Tensor or list of Tensor to be differentiated.
sources: It is Tensor or list of Tensor. Target values are differentiated against the source.
output_gradients: It is a list of gradients with default value None.
unconnected_gradients: It’s value can be either none or zero with default value none.
Returns: It returns a list or nested structure of Tensor.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf  x = tf.constant(4.0)  # Using GradientTapewith tf.GradientTape() as gfg:  gfg.watch(x)  y = x * x * x  # Computing gradientres  = gfg.gradient(y, x)   # Printing resultprint("res: ",res)
Output:

res:  tf.Tensor(48.0, shape=(), dtype=float32)

Example 2:
Python3
# Importing the libraryimport tensorflow as tf  x = tf.constant(4.0)  # Using GradientTapewith tf.GradientTape() as gfg:  gfg.watch(x)    # Using nested GradientTape for   # calculating higher order derivative  with tf.GradientTape() as gg:    gg.watch(x)    y = x * x * x    # Computing first order gradient  first_order = gg.gradient(y, x)  # Computing Second order gradientsecond_order  = gfg.gradient(first_order, x)   # Printing resultprint("first_order: ",first_order)print("second_order: ",second_order)
Output:

first_order:  tf.Tensor(48.0, shape=(), dtype=float32)
second_order:  tf.Tensor(24.0, shape=(), dtype=float32)


Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
PyQt5 QListWidget – Getting Resize Mode Property

06 Aug, 2020
In this article we will see how we can get the resize mode property to 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. This property holds whether the items are laid out again when the view is resized. If this property is Adjust, the items will be laid out again when the view is resized. If the value is Fixed, the items will not be laid out when the view is resized. By default, this property is set to Fixed although it can be set with the help of setResizeMode method.
In order to do this we will use resizeMode method with the list widget object.
Syntax : list_widget.resizeMode()
Argument : It takes no argument
Return : It returns resize mode object, but when printed it shows the value associated with it.
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 resize mode property        list_widget.setResizeMode(QListView.Fixed)          # 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 resize mode property        value = list_widget.resizeMode()          # setting text to the label        label.setText("Resize Mode Property : " + str(value))    # 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 | Add only numeric values present in a list

30 Jun, 2022
Given a list containing characters and numbers, the task is to add only numbers from a list. Given below are a few methods to complete a given task. Method #1: Using filter() and lambda 
Python3
# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres = sum(filter(lambda i: isinstance(i, int), ini_list)) # printing resultprint ("resultant sum", res)
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15
  Method #2: Using try and except 
Python3
# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres = 0for item in ini_list:    try:        res+= int(item)    except ValueError:        pass # printing resultprint ("resultant sum", res)
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15
  Method #3: Using isinstance and conditional statements 
Python3
# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres = sum([x for x in ini_list if isinstance(x, int)]) # printing resultprint ("resultant sum", res)
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15
Method #4: Using type() and find() methods
Python3
# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres=0for i in ini_list:    p=str(type(i))    if(p.find('int')!=-1):        res+=int(i)# printing resultprint ("resultant sum", res) #contributed by Bhavya Koganti
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15
kogantibhavya
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
GATE | GATE CS 1999 | Question 12

06 Oct, 2017
A sorting technique is called stable if:
(A) It takes O(nlog n)time(B) It maintains the relative order of occurrence of non-distinct elements(C) It uses divide and conquer paradigm(D) It takes O(n) spaceAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post
GATE CS 1999
GATE-GATE CS 1999
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2001 | Question 50
How to remove extension from string in PHP?

16 Feb, 2019
There are three ways of removing an extension from string. They are as follows
Using an inbuilt function pathinfo
Using an inbuilt function basename
Using an string functions substr and strrpos
Using pathinfo() Function: The pathinfo() function returns an array containing the directory name, basename, extension and filename.
Syntax:
pathinfo ( $path, $options = PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME )
Alternatively, if only one PATHINFO_ constants is passed as a parameter it returns only that part of the full filename.
Example:
<?php  // Initializing a variable with filename$file = 'filename.html';  // Extracting only filename using constants$x = pathinfo($file, PATHINFO_FILENAME);  // Printing the resultecho $x;  ?>
filename

Note: If the filename contains a full path, then only the filename without the extension is returned.
Using basename() Function: The basename() function is used to return trailing name component of path in the form of string. The basename() operates naively on the input string, and is not aware of the actual file-system, or path components such as “..”Syntax:
basename ( $path, $suffix )
When an extension of file is known it can be passed as a parameter to basename function to tell it to remove that extension from the filename.
Example:
<?php  // Initializing a variable// with filename$file = 'filename.txt';  // Suffix is passed as second// parameter$x = basename($file, '.txt');  // Printing the resultecho $x;  ?>
filename

Using substr()and strrpos() function: Another way of removing an extension from a filename is using the string functions substr and strrpos. The substr() function returns the part of string whereas strrpos() finds the position of last occurrence of substring in a string.
Syntax:
substr ( $string, $start, $length )
Example:
<?php  // Initializing a variable// with filename$file = 'filename.txt';  // Using substr $x = substr($file, 0, strrpos($file, '.'));  // Display the filenameecho $x;  ?>
filename

Note: If the filename contains a full path, then the full path and filename without the extension is returned.
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
NaN in C++ – What is it and How to Check For it?

06 Jan, 2022
NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can’t be represented. It is used for floating-point operations. For example:
The square root of negative numbers
Division by zero
Taking the log of zero or a negative number etc.
CPP
// C++ code to demonstrate NaN exception#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){    float a = 2, b = -2;     // Prints the number (1.41421)    cout << sqrt(a) << endl;     // Prints "nan" exception    // sqrt(-2) is complex number    cout << sqrt(b) << endl;     return 0;}
1.41421
-nan
Method 1: Using compare (“==”) operator. 
In this method, we check if a number is complex by comparing it with itself. If the result is true, then the number is not complex i.e., real. But if the result is false, then “nan” is returned, i.e. the number is complex.
CPP
// C++ code to check for NaN exception// using "==" operator#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){    float a = sqrt(2);    float b = sqrt(-2);     // Returns true, a is real number    // prints "Its a real number"    a == a ? cout << "Its a real number" << endl           : cout << "Its NaN" << endl;     // Returns false, b is complex number    // prints "Its nan"    b == b ? cout << "Its a real number" << endl           : cout << "Its NaN" << endl;     return 0;}
Its a real number
Its NaN
Method 2: Using inbuilt function “isnan()”
Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file.
CPP
// C++ code to check for NaN exception// using "isnan()"#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){    float a = sqrt(2);    float b = sqrt(-2);     // Returns false as a    // is real number    isnan(a) ? cout << "Its NaN" << endl             : cout << "Its a real number" << endl;     // Returns true as b is NaN    isnan(b) ? cout << "Its NaN" << endl             : cout << "Its a real number" << endl;     return 0;}
Its a real number
Its NaN
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
cpp-data-types
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
Product of middle row and column in an odd square matrix in C

Given a square matrix, mat[row][column] where row and column are equal and are of odd length means the number of row and column must me odd, i.e, not divisible by 2, the task is to find the product of middle row and middle column of that matrix.
Like in the given figure below −
Matrix must be a square matrix.
Matrix must be a square matrix.
Column and rows must be of odd length.
Column and rows must be of odd length.
Input 
mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output 
Product of middle row = 120
Product of middle column = 80
Explanation 
Product of middle row = 4 * 5 * 6 = 120
Product of middle column = 2 * 5 * 8 = 80
Input 
mat[][] = {{3, 5, 0},
{1, 2, 7},
{9, 0, 5}}
Output 
Product of middle row = 14
Product of middle column = 0
Explanation 
Product of middle row = 1 * 2 * 7 = 120
Product of middle column = 5 * 2 * 0 = 0
Take a matrix mat[][] as an input.
Take a matrix mat[][] as an input.
Traverse the matrix as from the middle row and middle column
Traverse the matrix as from the middle row and middle column
Calculate the product of the middle row and middle column and return the result.
Calculate the product of the middle row and middle column and return the result.
Start
In function int product(int mat[][MAX], int n)
   Step 1→ Declare and initialize rproduct = 1, cproduct = 1
   Step 2→ Loop For i = 0 and i < n and i++
      Set rproduct = rproduct * mat[n / 2][i]
      Set cproduct = cproduct * mat[i][n / 2]
   Step 3→ Print "Product of middle row: rproduct “
   Step 4→ Print "Product of middle column: cproduct”
In function int main()
   Step 1→ Declare and initialize mat[][MAX] {
      { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 } }
   Step 2→ Call product(mat, MAX)
Stop
 Live Demo
#include <stdio.h>
#define MAX 3
int product(int mat[][MAX], int n){
   int rproduct = 1, cproduct = 1;
   //We will only check the middle elements and
   //find their products
   for (int i = 0; i < n; i++) {
      rproduct *= mat[n / 2][i];
      cproduct *= mat[i][n / 2];
   }
   // Printing the result
   printf("Product of middle row: %d\n", rproduct);
   printf("Product of middle column: %d\n", cproduct);
   return 0;
}
// Driver code
int main(){
   int mat[][MAX] = {
      { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 } };
   product(mat, MAX);
   return 0;
}
If run the above code it will generate the following output −
Product of middle row: 120
Product of middle column: 80
Ext.js - First Program

This chapter lists down the steps to write the first Hello World program in Ext JS.
Create an index.htm page in the editor of our choice. Include the required library files in the head section of html page as follows.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      
      <script type = "text/javascript">
         Ext.onReady(function() {
            Ext.create('Ext.Panel', {
               renderTo: 'helloWorldPanel',
               height: 200,
               width: 600,
               title: 'Hello world',
               html: 'First Ext JS Hello World Program'
            });
         });
      </script>
   </head>
   
   <body>
      <div id = "helloWorldPanel" />
   </body>
</html>
Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements.
Ext.onReady() method will be called once the Ext JS is ready to render the Ext JS elements.
Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel.
Ext.create() method is used to create an object in Ext JS. Here we are creating an object of simple panel class Ext.Panel.
Ext.Panel is the predefined class in Ext JS for creating a panel.
Ext.Panel is the predefined class in Ext JS for creating a panel.
Every Ext JS class has different properties to perform some basic functionalities.
Every Ext JS class has different properties to perform some basic functionalities.
Ext.Panel class has various properties such as −
renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file.
renderTo is the element where this panel has to render. 'helloWorldPanel' is the div id in Index.html file.
Height and width properties are for customizing the size of the panel.
Height and width properties are for customizing the size of the panel.
Title property is to provide the title to the panel.
Title property is to provide the title to the panel.
Html property is the html content to be shown in the panel.
Html property is the html content to be shown in the panel.
Open the index.htm file in a standard browser and you will get the following output on the browser.
 Print
 Add Notes
 Bookmark this page
Plotly - Slider Control

Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot.
Slider control is made up of different properties which are as follows −
steps property is required for defining sliding positions of knob over the control.
steps property is required for defining sliding positions of knob over the control.
method property is having possible values as restyle | relayout | animate | update | skip, default is restyle.
method property is having possible values as restyle | relayout | animate | update | skip, default is restyle.
args property sets the arguments values to be passed to the Plotly method set in method on slide.
args property sets the arguments values to be passed to the Plotly method set in method on slide.
We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible.
Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure object’s layout by initializing sliders property.
# Add traces, one for each slider step
for step in np.arange(0, 5, 0.1):
fig.add_trace(
   go.Scatter(
      visible = False,
      line = dict(color = "blue", width = 2),
      name = "ν = " + str(step),
      x = np.arange(0, 10, 0.01),
      y = np.sin(step * np.arange(0, 10, 0.01))
   )
)
fig.data[10].visible=True

# Create and add slider
steps = []
for i in range(len(fig.data)):
step = dict(
   method = "restyle",
   args = ["visible", [False] * len(fig.data)],
)
step["args"][1][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(active = 10, steps = steps)]
fig.layout.update(sliders=sliders)
iplot(fig)
To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below.

    12 Lectures 
     53 mins

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to print current date and time in a JSP page?

With JSP program, it is very easy to get the current date and the time. You can use a simple Date object with the toString() method to print the current date and the time as follows −
 Live Demo
<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<html>
   <head>
      <title>Display Current Date & Time</title>
   </head>
   <body>
      <center>
         <h1>Display Current Date & Time</h1>
      </center>
      <%
         Date date = new Date();
         out.print( "<h2 align = \"center\">" +date.toString()+"</h2>");
      %>
   </body>
</html>
Let us now keep the code in CurrentDate.jsp and then call this JSP using the URL http://localhost:8080/CurrentDate.jsp. You will receive the following result −
Display Current Date & Time
Mon Jun 21 21:46:49 GMT+04:00 2010
Refresh the page with the URL http://localhost:8080/CurrentDate.jsp. You will find a difference in seconds every time you would refresh.
ML | Log Loss and Mean Squared Error - GeeksforGeeks

20 Jun, 2019
It is the evaluation measure to check the performance of the classification model. It measures the amount of divergence of predicted probability with the actual label. So lesser the log loss value, more the perfectness of model. For a perfect model, log loss value = 0. For instance, as accuracy is the count of correct predictions i.e. the prediction that matches the actual label, Log Loss value is the measure of uncertainty of our predicted labels based on how it varies from the actual label.
where, 
N  : no. of samples.
M  : no. of attributes.
yij : indicates whether ith sample belongs to jth class or not.
pij : indicates probability of ith sample belonging to jth class.

from sklearn.metrics import log_loss:  LogLoss = log_loss(y_true, y_pred, eps = 1e-15,    normalize = True, sample_weight = None, labels = None)
It is simply the average of the square of the difference between the original values and the predicted values.
Implementation of Mean Squared Error using sklearn
from sklearn.metrics import mean_squared_error  MSE = mean_squared_error(y_true, y_pred)
data mining
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Search Algorithms in AI
Python | Decision tree implementation
Elbow Method for optimal value of k in KMeans
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to install a Python package into a different directory using pip?

You can specify the install-option CLI argument to set the prefix path of the installation directory while installing a new module. For example, if you want to install your package to /tmp, then run the following command −
pip install --install-option="--prefix=/tmp" package_name
How to convert a String to an InputStream object in Java?


A ByteArrayInputStream is a subclass of InputStream class and it contains an internal buffer that contains bytes that may be read from the stream. We can convert a String to an InputStream object by using the ByteArrayInputStream class. This class constructor takes the string byte array which can be done by calling the getBytes() method of a String class.
import java.io.*;
public class StringToInputStreamTest {
   public static void main(String []args) throws Exception {
      String str = "Welcome to TutorialsPoint";
      InputStream input = getInputStream(str, "UTF-8");
      int i;
      while ((i = input.read()) > -1) {
         System.out.print((char) i);
      }
      System.out.println();
   }
   public static InputStream getInputStream(String str, String encoding) throws          UnsupportedEncodingException {
      return new ByteArrayInputStream(str.getBytes(encoding));
   }
}
Welcome to TutorialsPoint
Remove Axis Labels using ggplot2 in R - GeeksforGeeks

06 Jun, 2021
In this article, we are going to see how to remove axis labels of the ggplot2 plot in the R programming language.
We will use theme() function from ggplot2 package. In this approach to remove the ggplot2 plot labels, the user first has to import and load the ggplot2 package in the R console, which is a prerequisite for this approach, then the user has to call the theme() function which is the function of the ggplot2 package and further needs to pass the element_blank() as its parameters, which will be helping to remove the ggplot2 plots labels as blank in R programming language.
theme() function: Use of this function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look.
In this example, we will be showing that how the plot looks without removing its labels.
R
library("ggplot2")   gfg_data <- data.frame(x = c(1,2,3,4,5),                       y = c(5,4,3,2,1))gfg_plot <- ggplot(gfg_data, aes(x,y)) +    geom_point()gfg_plot
Output:
Example 1: In this example, we will be removing the label of the ggplot2  scatter plot of five data point using the theme() function of the ggplot2 package in the R programming language.
R
library("ggplot2")   gfg_data<-data.frame(x = c(1,2,3,4,5),                     y = c(5,4,3,2,1))gfg_plot <- ggplot(gfg_data, aes(x,y)) +    geom_point()gfg_plot +  theme(axis.text.x = element_blank(),        axis.ticks.x = element_blank(),        axis.text.y = element_blank(),        axis.ticks.y = element_blank())
Output:
Example 2: In this example, we will be removing the labels of the ggplot2 bar plot using the theme() function from the ggplot2 package in the R programming language.
R
library("ggplot2")   gfg_data<-data.frame(x = c(1,2,3,4,5),                     y = c(5,4,3,2,1))p<-ggplot(data=gfg_data, aes(x, y)) +  geom_bar(stat="identity")p+  theme(axis.text.x = element_blank(),        axis.ticks.x = element_blank(),        axis.text.y = element_blank(),        axis.ticks.y = element_blank())
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
How to Abort a Command Execution in Command Prompt? - GeeksforGeeks

17 Sep, 2021
Command Prompt is an interpreter which helps us to execute various commands and functions. These commands may include diskpart, install, cls, etc. Using Command Prompt, we can perform a variety of functions, eg, formatting any drive/Pendrive or compiling any file, or getting IP address using ip-config.
But, what happens if any command stops executing?
What to do if the command prompt gets stuck? How to get out of it? Do we need to close the prompt or we can just abort that particular command and continue from the same place where we left?
We will find these answers in this article;
Suppose we are executing a command the below command:
 npm install bootstrap
Now we can use the below keys to terminate the command execution:
CTRL + C
or
Ctrl+ Pause/break
After you press the button a message will appear whether you want to terminate this job or not as shown below:
Now Type ‘Y’ and hit “Enter” to terminate the process.
The Command will continue to execute if we type “N” when prompted. Take a look at the below image where we run the below command:
npm start
Then we hit Ctrl+C to terminate the execution. When prompted for confirmation, we type in “N” as shown below:
In this example, after typing “N” , the command continued its execution and completed it.
Blogathon-2021
Blogathon
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to set & unset session variable in codeigniter ? - GeeksforGeeks

07 Jan, 2022
The session class in CodeIgniter allows the user to maintain a user’s “state” and track their activity while browsing the website. The session can be initialized using the library and auto-loaded in the environment using the following command.
$this->load->library('session');
Set the session variable: Session indexes can be assigned using key-value pairs. A particular key can be assigned to a value using the assignment operator. The value may be a string, key, or even an array. 
Syntax:
$_SESSION['key'] = value; 
 
Example 1:
PHP
<?PHP       // Starting a new session   session_start();     $_SESSION['id'] = 9 ;    // Check if the session name exists   if( isset($_SESSION['id']) ) {       echo 'Session id is '.$_SESSION['id'].'<br>';   }   else {       echo 'Set the session id first '.'<br>';   }    echo'<br>';      // Modifying the value of session   $_SESSION['id'] = -8 ;   echo 'New session id is '.$_SESSION['id'].'<br>';     ?> 
Output:
Session id is 9
New session id is -8
The session value can also be assigned using the set_userdata() method in CodeIgniter. This method takes a key as the first argument and the. next is the value to be assigned. 
Syntax:
set_userdata ('key' , value)
Multiple key-value pairs can also be added at the session index in CodeIgniter, indicated by the following code snippet.
Example 2:
PHP
<?php    // Setting multiple key values  $sess_arr = array('id'=>5, 'name' => 'yash');      // Setting index at logged_in  $this->session->set_userdata('logged_in', $sess_arr);    // Printing the contents at this index  print_r($_SESSION['logged_in']);?>
Output:
Array ( [id] => 5 [name] => yash ) 
Unset the session variable: The session variable can be unset by assigning it to a NULL value. This destroys the value stored at this key value. 
Syntax:
$_SESSION['ey'] = NULL
Example 3:
PHP
<?php       // Starting a new session   session_start();     // Setting multiple values   $sess_arr = array('id'=>5, 'name' => 'yash');    $_SESSION['logged_in']= $sess_arr;  echo ('Old session : ');  print_r ($_SESSION['logged_in']);  echo '</br>';    // Unsetting the value  $_SESSION['logged_in']= NULL;  echo ('New session? : ');  print_r ($_SESSION['logged_in']);?> 
Output:
Old session : Array ( [id] => 5 [name] => yash )
New session? :
anikakapoor
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to use Zoom Component in ReactJS ? - GeeksforGeeks

22 Feb, 2021
Zoom Component adds a Zoom animation to a child element or component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Zoom Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: 
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. 
App.js
import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Zoom from '@material-ui/core/Zoom';  export default function App() {    const [isChecked, setIsChecked] = React.useState(false);    return (    <div style={{ display: 'block', padding: 30 }}>      <h4>How to use Zoom Component in ReactJS?</h4>      <FormControlLabel        control={<Switch checked={isChecked} onChange={() => {          setIsChecked((prev) => !prev);        }} />}        label="Toggle me to see Zoom Effect"      />      <div style={{ display: 'flex' }}>        <Zoom in={isChecked}          style={{ transitionDelay:'100ms'}}        >          <Paper            elevation={5}            style={{ margin: 5 }} >            <svg style={{ width: 100, height: 100 }}>              <polygon points="0,50 40,0,50,90"                style={{                  fill: 'red',                  stroke: 'dimgrey',                  strokeWidth: 1,                }} />            </svg>          </Paper>        </Zoom>      </div>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/transitions/#zoom
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
What does immutable mean? Which Python types are mutable and which are not?

In Python, there are two types of Objects.
Mutable Object
Immutable Object
Mutable: Mutable objects are modified, (i.e) objects are a changeable list, set, dict, etc are mutable.
mutable objects are easy to change.
list =["Tutorials ","Point", "Pvt","Ltd"]
list[2]= 'Tutorix'
list
['Tutorials ', 'Point', 'Tutorix', 'Ltd']

list=['Car','Bike','Scooty','Bus','Metro']
list[4]= 'Bicycle'
list
['Car', 'Bike', 'Scooty', 'Bus', 'Bicycle']

Immutable: immutable objects are not modified (i.e) not changeable int, float, bool, str, tuple, Unicode, etc ... are immutable. immutable objects are expensive and difficult to change. a tuple is enclosed within the parenthesis tuples are immutable and can't be changed.
tuple=('1','2','Python','Perl')
tuple
('1', '2', 'Python', 'Perl')

tuple=('1','2','Python','Perl')
tuple[4]='2019'
tuple
TypeError Traceback (most recent call last)
in
1 tuple=('1','2','Python','Perl')
----> 2 tuple[4]='2019'
3 tuple
TypeError: 'tuple' object does not support item assignment
tuple object cant be changed by seeing above output you get a clear understanding
How to generate Unique ID of device for iPhone/iPad using Swift?

UDID(Unique Device Identifier) − A sequence of 40 hexadecimal characters that uniquely identify an iOS device.
Since from iOS 5, Apple has deprecated the UIDevice unique identifier, that means the traditional way of getting the unique id. Apple removed the truly unique identifier and introduced an identifier for each vendor i.e UUID that's the same for all apps for a given developer for each user, but varies between developers and between devices.
Apple has defined an instance property identifier for the vendor, which is an alphanumeric string that uniquely identifies a device to the app’s vendor.
You can read more about it here: https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor
So we will see how we can get, Copy the below code in viewDidLoad method,
override func viewDidLoad() {
   super.viewDidLoad()
   guard let deviceID = UIDevice.current.identifierForVendor?.uuidString else {
      return
   }
   print(deviceID) // 7ABAB8B5-E805-437F-9D6C-5448BB19AEA5
}
How do you create a legend for a contour plot in Matplotlib?

To create a legend for a contour plot in matplotlib, we can take the following steps−
Create x, y and z data points to plot the contour function.
To create a 3D filled contour plot, we can use contourf() method with x, y, z and different levels.
Make a list of rectangle with the returned contour signature collection and set face color
Now, place the legend in the plot using proxy (of step 3) and different labels.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x, y = np.meshgrid(np.arange(10), np.arange(10))
z = np.tan(x ** 2 + y ** 2)
cs = plt.contourf(x, y, z, levels=[2, 3, 4, 6])
proxy = [plt.Rectangle((1, 1), 2, 2, fc=pc.get_facecolor()[0]) for pc in
cs.collections]
plt.legend(proxy, ["C1", "C2", "C3"])
plt.show()
Tcl - Logical Operators

Following table shows all the logical operators supported by Tcl language. Assume variable A holds 1 and variable B holds 0, then −
Try the following example to understand all the logical operators available in Tcl language −
#!/usr/bin/tclsh

set a  5
set b 20

if { $a && $b } {
   puts "Line 1 - Condition is true\n"
}
if { $a || $b } {
   puts "Line 2 - Condition is true\n"
}
# lets change the value of  a and b 
set a  0
set b 10
if { $a && $b } {
   puts "Line 3 - Condition is true\n"
} else {
   puts "Line 3 - Condition is not true\n" 
}
if { !($a && $b) } {
   puts "Line 4 - Condition is true\n" 
}
When you compile and execute the above program, it produces the following result −
Line 1 - Condition is true

Line 2 - Condition is true

Line 3 - Condition is not true

Line 4 - Condition is true

 Print
 Add Notes
 Bookmark this page
Remove Duplicates from Sorted Array II in C++

Suppose we have a sorted array nums, we have to remove the duplicates in-place such that duplicates elements will appear at most twice and return the new length. To do this task we cannot take extra space. We have to solve this with O(1) amount of space. For example, if the array is like [0,0,0,1,1,1,1,2,3,3], then the output will be [0,0,1,1,2,3,3], its length is 7
Let us see the steps −
len := 2 and n := size of array
if n <= 2, then return n
for i := 2 to nif nums[i] != nums[len - 2] or nums[i] != nums[len - 1]nums[len] := nums[i], and increase len by 1
if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]nums[len] := nums[i], and increase len by 1
nums[len] := nums[i], and increase len by 1
return len
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int removeDuplicates(vector<int>& nums) {
      int len = 2;
      int n = nums.size();
      if(n <= 2)return n;
      for(int i = 2; i < n; i++){
         if( nums[i] != nums[len - 2] || nums[i] != nums[len - 1]){
            nums[len] = nums[i];
            len++;
         }
      }
      return len;
   }
};
main(){
   Solution ob;
   vector<int> v = {0,0,0,1,1,1,1,2,3,3};
   cout << ob.removeDuplicates(v);
}
[0,0,0,1,1,1,1,2,3,3]
7