code-rag-bench/online-tutorials huggingface dataset:
How to compute derivative using Numpy?

21 Apr, 2021
In this article, we will learn how to compute derivatives using NumPy. Generally, NumPy does not provide any robust function to compute the derivatives of different polynomials. However, NumPy can compute the special cases of one-dimensional polynomials using the functions numpy.poly1d() and deriv().
poly1d(): It helps to define a polynomial expression or a function.
deriv(): Calculates and gives us the derivative expression
At first, we need to define a polynomial function using the numpy.poly1d() function.
Then we need to derive the derivative expression using the derive() function.
At last, we can give the required value to x to calculate the derivative numerically.
Below are some examples where we compute the derivative of some expressions using NumPy. Here we are taking the expression in variable ‘var’ and differentiating it with respect to ‘x’.
Example 1:
Python3
import numpy as np  # defining polynomial functionvar = np.poly1d([1, 0, 1])print("Polynomial function, f(x):\n", var)  # calculating the derivativederivative = var.deriv()print("Derivative, f(x)'=", derivative)  # calculates the derivative of after # given value of xprint("When x=5  f(x)'=", derivative(5))
Output:
Example 2:
Python3
import numpy as np  # defining polynomial functionvar = np.poly1d([4, 9, 5, 1, 6])print("Polynomial function, f(x):\n", var)  # calculating the derivativederivative = var.deriv()print("Derivative, f(x)'=\n", derivative)  # calculates the derivative of after # given value of xprint("When x=3  f(x)'=", derivative(3))
Output:
Example 3:
Python3
import numpy as np  # defining polynomial functionvar = np.poly1d([5, 4, 9, 5, 1, 6])print("Polynomial function:\n", var)  # calculating the derivativederivative = var.deriv()print("Derivative, f(x)'=\n", derivative)  # calculates the derivative of after # given value of xprint("When x=2  f(x)'=", derivative(0.2))
Output:
To calculate double derivative we can simply use the deriv() function twice.
Example 4:
Python3
import numpy as np  # defining polynomial functionvar = np.poly1d([3, 5, 4, 9, 5, 1, 6])print("Polynomial function:\n", var)  # calculating the derivativederivative = var.deriv()print("Derivative, f(x)'=\n", derivative)  # calculates the derivative of after # given value of xprint("When x=1  f(x)'=", derivative(1))derivative1 = derivative.deriv()  print("\n\nDerivative, f(x)''=\n", derivative1)print("When x=1  f(x)'=", derivative1(1))
Output:
Picked
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function
What are character classes or character sets used in Python regular expression?

A "character class", or a "character set", is a set of characters put in square brackets. The regex engine matches only one out of several characters in the character class or character set. We place the characters we want to match between square brackets. If you want to match any vowel, we use the character set [aeiou].
A character class or set matches only a single character. The order of the characters inside a character class or set does not matter. The results are identical.
We use a hyphen inside a character class to specify a range of characters. [0-9] matches a single digit between 0 and 9. Similarly for uppercase and lowercase letters we have the character class [A-Za-z]
The following code finds and prints all the vowels in the given string
import re
s = 'mother of all battles'
result = re.findall(r'[aeiou]', s)
print result
This gives the output
['o', 'e', 'o', 'a', 'a', 'e']
C++ Program to Implement Johnson’s Algorithm

Here we will see the Johnson’s Algorithm to find shortest path between two vertices. 
The graph is given here. The shortest path between the edges is like below. This program will take the number of vertices, number of edges, and the edges with their costs.
Input − Vertices: 3
Edges: 5
Edge with costs −
1 2 8
2 1 12
1 3 22
3 1 6
2 3 4
Output − The distance matrix of the graph.
Input − The cost matrix of given Graph.
Output − Matrix to for shortest path between any vertex to any vertex.
Begin
   Create another matrix ‘A’ same as cost matrix, if there is no edge between ith row and jth column, put infinity at A[i,j].
   for k := 1 to n, do
      for i := 1 to n, do
         for j := 1 to n, do
            A[i, j] = minimum of A[i, j] and (A[i, k] + A[k, j])
         done
      done
   done
   display the current A matrix
End
 Live Demo
#include<iostream>
#define INF 9999
using namespace std;
int min(int a, int b);
int cost[10][10], adj[10][10];
inline int min(int a, int b){
   return (a<b)?a:b;
}
main() {
   int vert, edge, i, j, k, c;
   cout << "Enter no of vertices: ";
   cin >> vert;
   cout << "Enter no of edges: ";
   cin >> edge;
   cout << "Enter the EDGE Costs:\n";
   for (k = 1; k <= edge; k++) { //take the input and store it into adj and cost matrix
      cin >> i >> j >> c;
      adj[i][j] = cost[i][j] = c;
   }
   for (i = 1; i <= vert; i++)
      for (j = 1; j <= vert; j++) {
         if (adj[i][j] == 0 && i != j)
            adj[i][j] = INF; //if there is no edge, put infinity
      }
   for (k = 1; k <= vert; k++)
      for (i = 1; i <= vert; i++)
         for (j = 1; j <= vert; j++)
            adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]); //find minimum path from i to j through k
   cout << "Resultant adj matrix\n";
   for (i = 1; i <= vert; i++) {
      for (j = 1; j <= vert; j++) {
            if (adj[i][j] != INF)
               cout << adj[i][j] << " ";
      }
      cout << "\n";
   }
}
Enter no of vertices: 3
Enter no of edges: 5
Enter the EDGE Costs:
1 2 8
2 1 12
1 3 22
3 1 6
2 3 4
Resultant adj matrix
0 8 12
10 0 4
6 14 0
Python string | swapcase() - GeeksforGeeks

05 Jan, 2018
The string swapcase() method converts all uppercase characters to lowercase and vice versa of the given string, and returns it.
Syntax:
string_name.swapcase()Here string_name is the string whose cases are to be swapped.
Parameter: The swapcase() method does not takes any parameter.
Return value:
The swapcase() method returns a string with all the cases changed.
Below is the Python implementation of the swapcase() method
# Python program to demonstrate the use of# swapcase() method    string = "gEEksFORgeeks"  # prints after swappong all casesprint(string.swapcase())     string = "striver" print(string.swapcase())  
Output:
GeeKSforGEEKS
STRIVER

python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Bootstrap 4 Tutorial

Bootstrap 4 is a newer version of Bootstrap, which is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.
Bootstrap 4 is completely free to download and use!
Start learning Bootstrap 4 now »
Learn Bootstrap 4
This Bootstrap 4 tutorial contains hundreds of Bootstrap 4 examples.
With our online editor, you can edit the code, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
This tutorial follows Bootstrap 4, which was released in 2018, as an upgrade 
to Bootstrap 3, with new components, faster 
stylesheetc, more responsiveness, etc.
Bootstrap 5 (released 2021) is the newest version of Bootstrap; 
It supports the latest, stable releases of all major browsers and 
platforms. However, Internet Explorer 11 and down is not supported.
The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that 
Bootstrap 5 has switched to JavaScript instead of jQuery.
Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes, 
and it is perfectly safe to continue to use them. However, new features will NOT be added to 
them.
We have created a responsive starter template with Bootstrap 4. You are free to modify, save, share, and use it in your projects:
Resize this responsive page to see the effect!

Link


Link


Link

Some text about me in culpa qui officia deserunt mollit anim..
Lorem ipsum dolor sit ame.

Active


Link


Link


Disabled

Some text..
Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.
Some text..
Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.
Footer
A complete list of all Bootstrap 4 CSS classes with description and examples:
If you want to do more with Bootstrap components, see our complete Bootstrap 4 JavaScript/jQuery reference - all with "Try it Yourself" examples:
Use a Bootstrap class to center the following text:
<p class=""> Hello World!</p>

Start the Exercise
Test your Bootstrap 4 skills at W3Schools!
Start Bootstrap 4 Quiz!
W3.CSS is an excellent alternative to Bootstrap 4.
W3.CSS is smaller, faster, and easier to use.
If you want to learn W3.CSS, go to our W3.CSS 
Tutorial.
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.
How to rethrow an exception in Java?


Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.
Because the exception has already been caught at the scope in which the rethrow expression occurs, it is rethrown out to the next enclosing try block. Therefore, it cannot be handled by catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the enclosing try block have an opportunity to catch the exception.
catch(Exception e) {
   System.out.println("An exception was thrown");
   throw e;
}
Live Demo
public class RethrowException {
   public static void test1() throws Exception {
      System.out.println("The Exception in test1() method");
      throw new Exception("thrown from test1() method");
   }
   public static void test2() throws Throwable {
      try {
         test1();
      } catch(Exception e) {
         System.out.println("Inside test2() method");
         throw e;
      }
   }
   public static void main(String[] args) throws Throwable {
      try {
         test2();
      } catch(Exception e) {
         System.out.println("Caught in main");
      }
   }
}
The Exception in test1() method
Inside test2() method
Caught in main
Powershell - Get-Unique Cmdlet

Get-Unique cmdlet can be used to get the unique objects from a sorted list of objects.
In this example, we're see the Get-Unique cmdlet in action.
In this example, we're set list of strings in a variable.
Type the following command in PowerShell ISE Console
$list = "one","two","two","three","four","five"
In this example, we're printing the original list of strings.
Type the following command in PowerShell ISE Console
$list
You can see following output in PowerShell console.
one
two
two
three
four
five

In this example, we're sorting the list and then get the unique values.
Type the following command in PowerShell ISE Console
$list | sort | get-unique
You can see following output in PowerShell console.
five
four
one
three
two


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Character.isSpaceChar() method in Java - GeeksforGeeks

06 Dec, 2018
The java.lang.Character.isSpaceChar(char ch) is an inbuilt method in java which determines if the specified character is a Unicode space character. A character is considered to be a space character if and only if it is specified to be a space character by the Unicode Standard.
This method returns true if the character’s general category type is any of the following ?
SPACE_SEPARATOR
LINE_SEPARATOR
PARAGRAPH_SEPARATOR
Syntax:
public static boolean isSpaceChar(char ch)

Parameter: The function accepts one mandatory parameter ch which specifies the character to be tested.
Return Value: This method returns a boolean value. The value is True if the character is a space character, False otherwise.
Below programs illustrate the Character.isSpaceChar() method:
Program 1:
// Java program to illustrate the// Character.isSpaceChar() methodimport java.lang.*;  public class gfg {      public static void main(String[] args)    {          // create 2 char primitives c1, c2 and assign values        char c1 = '$', c2 = '\u2025';          // Function to check if the character is a unicode space or not        boolean bool1 = Character.isSpaceChar(c1);        System.out.println("c1 is a space character? " + bool1);          // Function to check if the character is a unicode space or not        boolean bool2 = Character.isSpaceChar(c2);        System.out.println("c2 is a space character? " + bool2);    }}
c1 is a space character? false
c2 is a space character? false

Program 2:
// Java program to illustrate the// Character.isSpaceChar() methodimport java.lang.*;  public class gfg {      public static void main(String[] args)    {          // create 2 char primitives        // c1, c2 and assign values        char c1 = '*', c2 = '\u2028';          // Function to check if the character is a unicode space or not        boolean bool1 = Character.isSpaceChar(c1);        System.out.println("c1 is a space character? " + bool1);          // Function to check if the character is a unicode space or not        boolean bool2 = Character.isSpaceChar(c2);        System.out.println("c2 is a space character? " + bool2);    }}
c1 is a space character? false
c2 is a space character? true

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isSpaceChar(char)
Java-Character
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
StringBuilder Class in Java with Examples
Strings in Java
How to sum a comma separated string (string with numbers) in MySQL?

You can create a custom function to sum a comma-separated string in MySQL. Let us first create a table. Here, we have a varchar column, wherein we will add numbers in the form of strings −
mysql> create table DemoTable
   -> (
   -> ListOfValues varchar(50)
   -> );
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('20,10,40,50,60');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------+
| ListOfValues   |
+----------------+
| 20,10,40,50,60 |
+----------------+
1 row in set (0.00 sec)
Here is the query to create a function −
mysql> DELIMITER ??
mysql> create function totalSumInCommaSeparatedString(input varchar(50))
   -> returns int
   -> deterministic
   -> no sql
   -> begin
   -> declare totalSum int default 0;
   -> while instr(input, ",") > 0 do
   -> set totalSum = totalSum + substring_index(input, ",", 1);
   -> set input = mid(input, instr(input, ",") + 1);
   -> end while;
   -> return totalSum + input;
   -> end ??
Query OK, 0 rows affected (0.17 sec)
mysql> DELIMITER ;
Let us check the above function to get some of a comma-separated string in MySQL −
mysql> select totalSumInCommaSeparatedString(ListOfValues) as TotalSum from DemoTable;
This will produce the following output −
+----------+
| TotalSum |
+----------+
|      180 |
+----------+
1 row in set (0.00 sec)
Is java pass by reference or pass by value?

Call by Value means calling a method with a parameter as value. Through this, the argument value is passed to the parameter.
While Call by Reference means calling a method with a parameter as reference. Through this, the argument reference is passed to the parameter.
In call by value, the modification done to the parameter passed does not reflect in the caller's scope while in call by reference, the the modification done to the parameter passed are persistent and changes are reflected in the caller's scope.
But Java uses only call by value. It creates a copy of references and pass them as value to the methods. If reference contains objects, then the value of object can be modified in the method but not the entire object. See the example −
public class Tester {
   public static void main(String[] args) {
      Point point = new Point();
      System.out.println("X: " +point.x + ", Y: " + point.y);
      updatePoint(point);
      System.out.println("X: " +point.x + ", Y: " + point.y);
   }
   public static void updatePoint(Point point) {
      point.x = 100;
      point.y = 100;
   }
}
class Point {
   public int x, y;
}
X: 0, Y: 0
X: 100, Y: 100
How to create different Y-axis for group levels using ggplot2 in R?

If we have a categorical variable or a group variable then we might want to create a line chart for each of the categories or levels, this will help us to understand the range of multiple levels in a single plot. For this purpose, we can use facet_grid function of ggplot2 package as shown in the below example.
Consider the below data frame:
Live Demo
> x<-sample(LETTERS[1:4],20,replace=TRUE)
> y<-rnorm(20)
> df<-data.frame(x,y)
> df
   x     y
1 C  -1.55668689
2 A   2.41399136
3 D  -0.78520253
4 A  -0.43092594
5 C   1.94379390
6 A   0.17494763
7 C  -1.61170476
8 A  -1.55362764
9 C  -0.53384492
10 A -0.66698812
11 D  1.44100518
12 D  1.10126743
13 D -1.54194367
14 B -0.03254252
15 A -0.63927406
16 A  1.72924629
17 A -0.10003278
18 B -0.08262660
19 C  1.29335456
20 A -1.50531507
Loading ggplot2 package and creating a line chart for each of the levels in x:
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_line()
Creating the line chart for each level of x but with different scales of Y-axis chosen by R freely based on the given data:
> ggplot(df,aes(x,y))+geom_line()+facet_grid(x~.,scales="free")
JavaScript RegExp - [a-zA-Z]

[a-zA-Z] matches any character from lowercase a through uppercase Z.
Following example shows usage of RegExp expression.
<html>
   <head>
      <title>JavaScript RegExp</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         var str = "first1";
         var pattern = /[a-zA-Z]/g;

         var result = str.match(pattern);
         document.write("Test 1 - returned value : " +  result); 

         str = "Second2";
         result = str.match(pattern);
         document.write("<br/>Test 2 - returned value : " +  result); 	 		 
      </script>
   </body>
</html>
Test 1 - returned value : f,i,r,s,t
Test 2 - returned value : S,e,c,o,n,d


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Selenium - Element is not clickable at point

We can get the error - Element is not clickable at point while trying to click a link in Selenium webdriver. This is common in chromedriver as the Chrome browser determines an element with point location.
When the position of an element is changing and we make an attempt to click on it, this error is encountered. This is because the element is present in DOM, but its position is not fixed on the page.
There are some workarounds to fix this error as listed below −
Adding the explicit wait. The webdriver can wait till the expected condition - visibilityOf(webdriver shall wait for an element in DOM to be visible).
Adding the explicit wait. The webdriver can wait till the expected condition - visibilityOf(webdriver shall wait for an element in DOM to be visible).
Adding the explicit wait. The webdriver can wait till the expected condition - visibilityOfElementLocated. The webdriver shall wait for an element to be present in DOM and displayed on the page.
Adding the explicit wait. The webdriver can wait till the expected condition - visibilityOfElementLocated. The webdriver shall wait for an element to be present in DOM and displayed on the page.
Maximize the size of the browser.
Maximize the size of the browser.
Syntax
driver.manage().window().maximize()
Adding methods of the Actions class.
Adding methods of the Actions class.
Syntax
WebElement l = driver.findElement(By.name("field-name"));

Actions at = new Actions(driver);
at.moveToElement(l).click().perform();
JavaScript Executor.
JavaScript Executor.
Syntax to get location along x axis −
WebElement l = driver.findElement(By.name("field-name"));
JavascriptExecutor je =(JavascriptExecutor)driver;
je.executeScript("window.scrollTo(0,"l.getLocation().x+")");
l.click();
Syntax to get location along y axis −
WebElement l = driver.findElement(By.name("field-name"));
JavascriptExecutor je =(JavascriptExecutor)driver;
je.executeScript("window.scrollTo(0,"l.getLocation().y+")");
l.click();
MomentJS - Date Validation

MomentJS handles date validation in an easy way. You need not write lots of code to validate date. isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.
MomentJS provides the following parsing flags in cases where the date given is considered as invalid −
overflow − This will occur when the month given is 13th, day is 367th in an year or 32nd in a month, 29th for Feb on a non-leap year etc. Overflow contains the index of the invalid unit to match towards invalidAt. Note that -1 means no overflow.
invalidMonth − It shows an invalid month name. It will give the invalid month string or null.
Empty − When an input is given which is not a date. It gives a Boolean.
nullInput − A null input, like moment(null);It returns a Boolean.
invalidFormat − When the format given is empty such as moment('2018-04-25', []). It gives Boolean back.
userInvalidated − A date created explicitly as invalid, such as moment.invalid(). It returns Boolean.
meridiem − Indicates the meridiem (AM/PM) parsed, if any. It returns string.
parsedDateParts − It returns an array of date parts parsed such as parsedDateParts[0] as year, parsedDateParts[1] as month and parsedDateParts[2] as day. If no parts are present, but meridiem has value, date is invalid. It returns an array.
Consider the following example to understand date validation −
var a = moment("2018-18-10T10:20:25");
a.isValid();
a.invalidAt();
The invalidAt gives the output as 1 , which points to the month as the month value is greater than 12 and it overflows. If there is an overflow, invalidAt will give the output as shown in the table given here −
If there are multiple overflows in the date given, it will be an output for the first overflowed index.
 Print
 Add Notes
 Bookmark this page
C++ Program to Represent Graph Using 2D Arrays

This is a C++ program represents a graph using 2D arrays.
The time complexity of this algorithm is O(v*v).
Begin
   Take the input of the number of vertex ‘v’ and edges ‘e’.
   Assign memory to the graph[][] matrix.
   Take the input of ‘e’ pairs of vertexes of the given graph in graph[][].
   For each pair of connected vertex(v1, v2), store 1 in the graph[][] at the index (v1, v2) and (v2, v1).
   Print the matrix using PrintMatrix().
End
#include<iostream>
#include<iomanip>
using namespace std;
void PrintMatrix(int **matrix, int n) {
   int i, j;
      cout<<"\n\n"<<setw(4)<<"";
   for(i = 0; i < n; i++)
      cout<<setw(3)<<"("<<i+1<<")";
      cout<<"\n\n";
   for(i = 0; i < n; i++) {
      cout<<setw(3)<<"("<<i+1<<")";
      for(j = 0; j < n; j++) {
         cout<<setw(4)<<matrix[i][j];
      }
      cout<<"\n\n";
   }
}
int main() {
   int i, v, e, j, v1, v2;
   cout<<"Enter the number of vertexes of the graph: ";
   cin>>v;
   int **graph;
   graph = new int*[v];
   for(i = 0; i < v; i++) {
      graph[i] = new int[v];
      for(j = 0; j < v; j++) graph[i][j] = 0;
   }
   cout<<"\nEnter the number of edges of the graph: ";
   cin>>e;
   for(i = 0; i < e; i++) {
      cout<<"\nEnter the vertex pair for edge "<<i+1;
      cout<<"\nV(1): ";
      cin>>v1;
      cout<<"V(2): ";
      cin>>v2;
      graph[v1-1][v2-1] = 1;
      graph[v2-1][v1-1] = 1;
   }
   PrintMatrix(graph, v);
}
Enter the number of vertexes of the graph: 5
Enter the number of edges of the graph: 4
Enter the vertex pair for edge 1
V(1): 2
V(2): 1
Enter the vertex pair for edge 2
V(1): 3
V(2): 2
Enter the vertex pair for edge 3
V(1): 1
V(2): 1
Enter the vertex pair for edge 4
V(1): 3
V(2): 1
(1) (2) (3) (4) (5)
(1) 1 1 1 0 0
(2) 1 0 1 0 0
(3) 1 1 0 0 0
(4) 0 0 0 0 0
(5) 0 0 0 0 0
How to get the path of the currently executing script in PowerShell?

To get the full path of the script we need to use the $myInvocation command. This is an automatic variable and it is only invoked when the script or the function is executed.
$MyInvocation.MyCommand.Path command is useful to get the full path of the script where it resides while $MyInvocation.MyCommand.Name is useful to get the name of the script. 
$mypath = $MyInvocation.MyCommand.Path
Write-Output "Path of the script : $mypath"
PS C:\WINDOWS\system32> C:\Temp\TestPS.ps1
Path of the script : C:\Temp\TestPS.ps1
Please note that we are running the above script from the System32 directory and the output path is C:\temp. To get the script directory, we can use the Split-Path command. for example,
Split-Path $mypath -Parent
To get the name of the script, use can use the Name property as mentioned earlier. 
$ScriptName = $MyInvocation.MyCommand.Name
Write-Output "`nName of the script : $scriptname"
PS C:\WINDOWS\system32> C:\Temp\TestPS.ps1
Name of the script : TestPS.ps1
When you run the above commands directly from the console, it won’t give any output because $MyInvocation can only produce output when the script is invoked. For example,
Quantile Quantile plots - GeeksforGeeks

22 Jan, 2021
The quantile-quantile plot is a graphical method for determining whether two samples of data came from the same population or not. A q-q plot is a plot of the quantiles of the first data set against the quantiles of the second data set. By a quantile, we mean the fraction (or percent) of points below the given value. 
For the reference purpose, a 45% line is also plotted, if the samples are from the same population then the points are along this line.
The normal distribution (aka Gaussian Distribution/ Bell curve) is a continuous probability distribution representing distribution obtained from the randomly generated real values.
 
Below is the portion of data representing different standard deviation
 
Normal Distribution with Area Under CUrve
The Quantile-Quantile plot is used for the following purpose:
Determine whether two samples are from the same population.
Whether two samples have the same tail
Whether two samples have the same distribution shape.
Whether two samples have common location behavior.
Collect the data for plotting the quantile-quantile plot.
Sort the data in ascending or descending order.
Draw a normal distribution curve.
Find the z-value (cut-off point) for each segment.
Plot the dataset values against the normalizing cut-off points.
Since Q-Q plot is like probability plot. So, while comparing two datasets the sample size need not to be equal.
Since we need to normalize the dataset, so we don’t need to care about the dimensions of values.
For Left-tailed distribution: Below is the
For the uniform distribution: Below is the q-q plot distribution for uniform distribution:
uniform distribution Q-Q plot
# codeimport scipy.stats as statsimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline  n = 2000observation = np.random.binomial(n, 0.53, size=1000)/n  z = (observation-np.mean(observation))/np.std(observation)  stats.probplot(z, dist="norm", plot=plt)plt.title("Normal Q-Q plot")plt.show()
Output:
Normal Q-Q plot
Data Visualization
ML-EDA
ML-plots
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Support Vector Machine Algorithm
Types of Environments in AI
k-nearest neighbor algorithm in Python
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
Python | Stemming words with NLTK
Normalization vs Standardization
Intuition of Adam Optimizer
How can I verify Error Message on a webpage using Selenium Webdriver?

We can verify error messages on a webpage using Selenium webdriver using the Assertion. In case, the actual and expected values do not match, an Assertion Error is thrown.
Let us try to verify the highlighted error message.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
public class VerifyErrorMsg{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      // identify element
      WebElement l = driver.findElement(By.id("session_key"));
      l.sendKeys("abc");
      WebElement t = driver.findElement(By.className("sign-in-form__submit-button"));
      t.click();
      //expected error text
      String exp = "Please enter a valid email address or mobile number.";
      //identify actual error message
      WebElement m = driver.findElement(By.className("alert-content"));
      String act = m.getText();
      System.out.println("Error message is: "+ act);
      //verify error message with Assertion
      Assert.assertEquals(exp, act);
      driver.quit();
   }
}
What is the difference between String s1 = "Hello" and String s1= new String("Hello") in java?

When you store a String as
String str1 = "Hello";
directly, then JVM creates a String object with the given value in a separate block of memory known as String constant pool.
And whenever we try to create another String as
String str2 = "Hello";
JVM verifies whether any String object with the same value exists in the String constant pool, if so, instead of creating a new object JVM assigns the reference of the existing object to the new variable.
And when we store String as
String str = new String("Hello");
using the new keyword, a new object with the given value is created irrespective of the contents of the String constant pool.
Python Program for Selection Sort

In this article, we will learn about the Selection sort and its implementation in Python 3.x. Or earlier.
In the selection sort algorithm, an array is sorted by recursively finding the minimum element from the unsorted part and inserting it at the beginning. Two subarrays are formed during the execution of Selection sort on a given array.
The subarray, which is already sorted
The subarray, which is unsorted.
During every iteration of selection sort, the minimum element from the unsorted subarray is popped and inserted into the sorted subarray.
Let’s see the visual representation of the algorithm −
Now let’s see the implementation of the algorithm −
 Live Demo
A = ['t','u','t','o','r','i','a','l']
for i in range(len(A)):
   min_= i
   for j in range(i+1, len(A)):
      if A[min_] > A[j]:
         min_ = j
   #swap
A[i], A[min_] = A[min_], A[i]
# main
for i in range(len(A)):
   print(A[i])
a
i
l
o
r
t
t
u
Here we received output from the algorithm in ascending order. Min_ is the current value which is getting compared with all other values. The analysis parameters of the algorithm are listed below −
Time Complexity − O(n^2)
Auxiliary Space − O(1)
Here all the variables are declared in the global frame as shown in the image below
In this article, we learned about Selection sort and its implementation in Python 3.x. Or earlier.
Multiple Inserts for a single column in MySQL?

The syntax for multiple inserts for a single column in MySQL is as follows −
INSERT INTO yourTableName(yourColumnName) values(‘yourValue1'),(‘yourValue2'),(‘yourValue3'),(‘yourValue4'),.........N;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table InsertMultipleDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserName varchar(10),
   -> UserRole varchar(20)
   -> ,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (3.14 sec)
Now you can insert some records in the table using insert command. Here is the query to insert multiple values using insert command −
mysql> insert into InsertMultipleDemo(UserRole) values('Admin'),('Author'),('Driver'),('Guest');
Query OK, 4 rows affected (0.17 sec)
Records: 4 Duplicates: 0 Warnings: 0
As you can see above, 4 rows are affected.
Display all records from the table using select statement. The query is as follows −
mysql> select UserRole from InsertMultipleDemo;
The following is the output −
+----------+
| UserRole |
+----------+
| Admin    |
| Author   |
| Driver   |
| Guest    |
+----------+
4 rows in set (0.00 sec)
HTML - <marquee> Tag

The HTML <marquee> tag is used for scrolling piece of text or image displayed either horizontally across or vertically down your web site page depending on the settings.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML marquee Tag</title>
   </head>

   <body>
      <marquee>This is basic example of marquee</marquee>
      <marquee direction = "up">The direction of text will be from bottom to top.</marquee>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <marquee> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
What are Snippets in Postman?

Snippets are small scripts used in Postman which are used to verify an API. These are pre-developed scripts that can be utilized directly. Thus it helps to save a good amount of time.
Snippets can be used in the Pre-request Script and Tests tabs in Postman. Navigate to the Tests tab and the SNIPPETS section should be available to the extreme right of the screen. Click on any snippet to use it in a script.
On clicking the link Get a variable, the below script gets populated in the Tests tab which can be used in our own script −
pm.variables.get("variable_key");
Navigate to the Pre-Request Script tab and the SNIPPETS section should be available to the extreme right of the screen. Click on any snippet to use it in a script.
On clicking the link Get an environment variable, the below script gets populated in the Pre-request Script tab which can be used in our own script −
pm.environment.get("variable_key");
How to extract image metadata in Python?

03 Jan, 2021
Prerequisites: PIL
Metadata stands for data about data. In case of images, metadata means details about the image and its production. Some metadata is generated automatically by the capturing device. 
Some details contained by image metadata is as follows:
Height
Width
Date and Time
Model etc.
Python has PIL library which makes the task of extracting metadata from an image extremely easy that too by using just a few lines.
Import the pillow module.
Load the image
Get the metadata. The metadata so obtained
Convert it into human-readable form
There are many types of metadata but in this we are only focusing on Exif metadata
Exif
These metadata, often created by cameras and other capture devices, include technical information about an image and its capture method, such as exposure settings, capture time, GPS location information and camera model.
for this i have used this picture(link for this is below) make sure whatever picture you are using it  should have some metadata of EXIF type and most of the capturing devices have exif data
https://drive.google.com/file/d/1z2RaRvzC8Cd8oxD8pZJu2U0rpRr8tbwV/view 
NOTE:-please avoid the image shared through whatsapp. Whatsapp strips away all metadata from any image 
Implementation:
Step 1: Importing modules.
Step 2: Load the image and extract the exif data.
Step 3: Convert the exif tag id(denoted by tagid in the code ) into human readable form denoted by tagname in the code and getting its respective value.
Application to extract  Metadata from a image with pillow : below script implements the above approach
Python3
from PIL import Imagefrom PIL.ExifTags import TAGS  # open the imageimage = Image.open("img.jpg")  # extracting the exif metadataexifdata = image.getexif()  # looping through all the tags present in exifdatafor tagid in exifdata:          # getting the tag name instead of tag id    tagname = TAGS.get(tagid, tagid)      # passing the tagid to get its respective value    value = exifdata.get(tagid)        # printing the final result    print(f"{tagname:25}: {value}")
Output:
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Multiply each element in a sublist by its index

29 May, 2019
Given a list of lists, the task is to multiply each element in a sublist by its index and return a summed list.
Given below are a few methods to solve the problem.
Method #1: Using Naive Method
# Python3 code to demonstrate# to multiply numbers with position# and add them to return num  import numpy as np  # initialising listini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]]  # printing initial_listprint ("initial_list ", ini_list)  res = []# Using Naive Methodfor sub_list in ini_list:    sublistsum = 0      for i, value in enumerate(sub_list):        sublistsum = sublistsum + i * value      res.append(sublistsum)  # printing resultprint ("result", res)
initial_list  [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]]
result [18, 23, 17, 38]

 Method #2: Using List comprehension
# Python3 code to demonstrate# to multiply numbers with position# and add them to return num    # initialising listini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]]  # printing initial_listprint ("initial_list ", ini_list)  # Using list comprehensionres = [sum(i * j for i, j in enumerate(sublist))                          for sublist in ini_list]  # printing resultprint ("result", res)             
initial_list  [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]]
result [18, 23, 17, 38]

 Method #3: Using numpy
# Python3 code to demonstrate# to multiply numbers with position# and add them to return num  import numpy as np  # initialising listini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]]  # printing initial_listprint ("initial_list ", ini_list)  # Using numpyres = [np.arange(len(sublist)).dot(sublist) for sublist in ini_list]  # printing resultprint ("result", res)                           
initial_list  [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]]
result [18, 23, 17, 38]

Python list-programs
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python | Variance of List

17 Sep, 2019
While working with Python, we can have a problem in which we need to find variance of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding variance and perform using loop shorthands. This is the most basic approach to solve this problem.
# Python3 code to demonstrate working of# Variance of List# using loop + formula  # initialize listtest_list = [6, 7, 3, 9, 10, 15]  # printing original listprint("The original list is : " + str(test_list))  # Variance of List# using loop + formulamean = sum(test_list) / len(test_list)res = sum((i - mean) ** 2 for i in test_list) / len(test_list)  # printing resultprint("The variance of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The variance of list is : 13.888888888888891

 
Method #2 : Using statistics.variance()This task can also be performed using inbuilt function of variance().
# Python3 code to demonstrate working of# Variance of List# using statistics.varianceimport statistics   # initialize listtest_list = [6, 7, 3, 9, 10, 15]  # printing original listprint("The original list is : " + str(test_list))  # Variance of List# using statistics.varianceres = statistics.variance(test_list)  # printing resultprint("The variance of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The variance of list is : 13.888888888888891

Python list-programs
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How do I wrap text in a <pre> tag in HTML?

HTML <pre> tag defines preformatted text. It is used to display code blocks since it preserves spaces and line breaks.
If the line is large, then the <pre> tag won’t wrap it by default. To wrap it, we need to use CSS.
You can try to run the following code to learn about the usage of <pre> tag and how we can wrap text in HTML using CSS. We’ll be using CSS <style> tag to add CSS to our HTML document.
<!DOCTYPE html>
<html>
   <head>
      <style>
         pre {
            overflow-x: auto;
            white-space: pre-wrap;
            white-space: -moz-pre-wrap;
            white-space: -pre-wrap;
            white-space: -o-pre-wrap;
            word-wrap: break-word;
         }
      </style>
   </head>

   <body>
      <pre>
         This text renders large lines, which wraps now, since we used CSS
         properties with the pre tag in this example.
      </pre>
   </body>
</html>
PHPUnit assertIsInt() Function

07 Aug, 2020
The assertIsInt() function is a builtin function in PHPUnit and is used to assert whether the given actual variable is an integer or not. This assertion will return true in the case if the actual variable is an integer else returns false. In case of true the asserted test case got passed else test case got failed.
Syntax:
assertIsInt($actual[, $message = ''])

Parameters: This function accepts two parameters as mentioned above and described below:
$actual: This parameter is of any type of variable which represents the actual data.
$message: This parameter takes a string value. When the test case got failed this string message got displayed as an error message.
 Below examples illustrate the assertIsInt() function in PHPUnit:
Example 1:
PHP
<?php use PHPUnit\Framework\TestCase;     class GeeksPhpunitTestCase extends TestCase {     public function testNegativeForassertIsInt()              {        $actualvalue = 550.33;        // Assert function to test whether actual         // variable is Integer or not        $this->assertIsInt(                      $actualvalue,             "actual value is Integer or not"        );              }    } ?>
Output:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

F                                                 1 / 1 (100%)

Time: 104 ms, Memory: 10.00 MB

There was 1 failure:

1) GeeksPhpunitTestCase::testNegativeForassertIsInt
actual value is Integer or not
Failed asserting that 550.33 is of type "int".

/home/lovely/Documents/php/test.php:16

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Example 2:
PHP
<?php use PHPUnit\Framework\TestCase;     class GeeksPhpunitTestCase extends TestCase {     public function testPositiveForassertIsInt()              {        $actualvalue = 101;        // Assert function to test whether actual         // variable is Integer or not        $this->assertIsInt(                      $actualvalue,             "actual value is Integer or not"        );              }    } ?> 
Output:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.

.                                                 1 / 1 (100%)

Time: 88 ms, Memory: 10.00 MB

OK (1 test, 1 assertion)

PHP-PHPUnit
PHP
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 Upload Image into Database and Display it using 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 receive JSON POST with PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Removing Array Element and Re-Indexing in PHP
Selenium Click Link By href Value

We can click a link by href value with Selenium webdriver. To identify the link with the href attribute we can take the help of the locators xpath or css selector.
We shall use the findElement method and pass By.xpath or By.cssSelector as a parameter to this method. Let us investigate the html code of the link Privacy Policy in the below image with the anchor tag having a href attribute as /about/about_privacy.htm.
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FirstAssign{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "chromedriver");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get
      ("https://www.tutorialspoint.com/about/about_privacy.htm");
      //identify element with href value in CSS
      WebElement elm = driver
      .findElement(By.cssSelector("a[href*='about_privacy']"));
      String s = elm.getText();
      System.out.println("Text is: " + s);
      //browser close
      driver.quit();
   }
}