code-rag-bench/online-tutorials huggingface dataset:
JavaScript Regular Expressions - GeeksforGeeks

13 Jan, 2022
Below is the example of the JavaScript Regular Expressions.  
Example:  
JAVASCRIPT
<script>function GFGFun() {    var str = "Visit geeksforGeeks";    var n = str.search(/GeeksforGeeks/i);    document.write(n);}GFGFun();</script>
Output:  
6
A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations.Syntax:  
/pattern/modifiers;
Example:  
var patt = /GeeksforGeeks/i;
Explanation: /GeeksforGeeks/i is a regular expression.GeeksforGeeks is a pattern (to be used in a search).i is a modifier (modifies the search to be Case-Insensitive).Regular Expression Modifiers :Modifiers can be used to perform multiline searches: Examples: 
 
Regular Expression Patterns :Metacharacters are characters with a special meaning: Examples: 
 
Quantifiers define quantities: Examples: 
 
Using String Methods:In JavaScript, regular expressions are often used with the two string methods: search() and replace().The search() method uses an expression to search for a match, and returns the position of the match.The replace() method returns a modified string where the pattern is replaced.Using String search() With a Regular Expression :Use a regular expression to do a case-insensitive search for “GeeksforGeeks” in a string:Example: 
JAVASCRIPT
<script>function myFunction() {     // input string    var str = "Visit geeksforGeeks!";     // searching string with modifier i    var n = str.search(/GeeksforGeeks/i);     document.write(n + '<br>');     // searching string without modifier i    var n = str.search(/GeeksforGeeks/);     document.write(n);}myFunction();</script>
Output:  
6
-1
Use String replace() With a Regular Expression : Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:Example: 
JAVASCRIPT
<script>function myFunction() {     // input string    var str = "Please visit gfG!";     // replacing with modifier i    var txt = str.replace(/gfg/i, "geeksforgeeks");         document.write(txt);}myFunction();</script>
Output:  
Please visit geeksforgeeks! 
 
adnanirshad158
JavaScript-Misc
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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 ?
Difference between var, let and const keywords in JavaScript
Pandas remove rows with special characters - GeeksforGeeks

19 Oct, 2020
In this article we will learn how to remove the rows with special characters i.e; if a row contains any value which contains special characters like @, %, &, $, #, +, -, *, /, etc. then drop such row and modify the data. To drop such types of rows, first, we have to search rows having special characters per column and then drop. To search we use regular expression either [@#&$%+-/*] or [^0-9a-zA-Z]. Let’s discuss the whole procedure with some examples :
Example 1:
This example consists of some parts with code and the dataframe used can be download by clicking data1.csv or shown below.
Python3
# importing packageimport pandas as pd # load datasetdf = pd.read_csv("data1.csv") # view datasetprint(df)
Output:
 Select rows with columns having special characters value
Python3
# select the rows# if Name column# has special charactersprint(df[df.Name.str.contains(r'[@#&$%+-/*]')])
  Output: 
Python3
# select the rows# if Grade column# has special charactersprint(df[df.Grade.str.contains(r'[^0-9a-zA-Z]')])
 Output:
 Merging of selected rows
Python3
# merge the selected rows# by using orprint(df[df.Name.str.contains(r'[^0-9a-zA-Z]')         | df.Grade.str.contains(r'[@#&$%+-/*]')])
Output:
Remove the merged selected rows 
Python3
# drop the merged selected rowsprint(df.drop(df[df.Name.str.contains(r'[^0-9a-zA-Z]')                 | df.Grade.str.contains(r'[^0-9a-zA-Z]')].index))
Output:
Example 2: This example uses a dataframe which can be download by clicking data2.csv or  shown below :
Python3
# importing packageimport pandas as pd # load datasetdf = pd.read_csv("data2.csv") # view datasetprint(df) # select and then merge rows# with special charactersprint(df[df.ID.str.contains(r'[^0-9a-zA-Z]') |         df.Name.str.contains(r'[^0-9a-zA-Z]') |         df.Age.str.contains(r'[^0-9a-zA-Z]') |         df.Country.str.contains(r'[^0-9a-zA-Z]')]) # drop the rowsprint(df.drop(df[df.ID.str.contains(r'[^0-9a-zA-Z]') |                 df.Name.str.contains(r'[^0-9a-zA-Z]') |                 df.Age.str.contains(r'[^0-9a-zA-Z]') |                 df.Country.str.contains(r'[^0-9a-zA-Z]')].index))
Output :
anshitaagarwal
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Django Request and Response cycle - HttpRequest and HttpResponse Objects - GeeksforGeeks

27 May, 2021
Prerequisite – Views In Django | PythonBefore we jump into using convenience methods that views come with, Let’s talk about the Request and Response cycle. So, when a Request happens to a Django server, a couple of things go on. One of them is Middleware. 
Middleware Middleware is like a middle ground between a request and response. It is like a window through which data passes. As in a window, light passes in and out of the house. Similarly, when a request is made it moves through middlewares to views, and data is passed through middleware as a response. Here are the default middlewares installed in Django.  
You can add your middlewares. We will be discussing that in the next articles. 
Django uses request and response objects to pass state through the system.When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. 
To explain these objects let’s create a view home as below in views.py  
Python3
# importing HttResponse from libraryfrom django.http import HttpResponse def home(request):    # request is handled using HttpResponse object    return HttpResponse("Any kind of HTML Here")
 
To handle the request let us map a URL to this view in urls.py  
Python3
# importing view from views.pyfrom .views import home urlpatterns = [    path('', home), ]
 
Now you can run the server to see the following in the browser  
 
You can use the following attributes with HttpRequest for advanced manipulation  
 
You can use the following methods with HttpRequest for advanced manipulation  
 
You can use the following attributes with HttpResponse for advanced manipulation  
 
You can use the following methods with HttpResponse for advanced manipulation  
 
ksingla02
Django-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
C# | Finding the index of first element in the array - GeeksforGeeks

01 Feb, 2019
GetLowerBound() Method is used to find the index of the first element of the specified dimension in the array.
Syntax:
public int GetLowerBound (int dimension);
Here, dimension is a zero-based dimension of the array whose lower bound needs to be determined.
Return Value: The return type of this method is System.Int32. This method returns the index of the first element of the specified dimension in the array.
Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank.
Note:
GetLowerBound(0) returns the starting index of the first dimension of the array, and GetLowerBound(Rank – 1) returns the starting index of the last dimension of the array.
The GetLowerBound method always returns a value that indicates the index of the lower bound of the array, even if the array is empty.
This method is an O(1) operation.
Below programs illustrate the use of GetLowerBound() Method:
Example 1:
// C# program to illustrate the GetLowerBound(Int32)// method in 1-D arrayusing System;  public class GFG {          // Main method    static public void Main()    {          // 1-D Array        int[] value = {1, 2, 3, 4, 5, 6, 7};          // Get the index of the first element        // in the given Array by using         // GetLowerBound(Int32) method        int myvalue = value.GetLowerBound(0);                  Console.WriteLine("Index: {0}", myvalue);    }}
Index: 0

Example 2:
// C# program to illustrate the GetLowerBound(Int32)// method when the array is emptyusing System;  public class GFG {          // Main method    static public void Main()    {          // Empty 1-D Array        int[] value = {};          // Get the index of the first element        // in the given Array by using         // GetLowerBound(Int32) method        int myvalue = value.GetLowerBound(0);                  Console.WriteLine("Index: {0}", myvalue);    }}
Index: 0

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getlowerbound?view=netcore-2.1
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types
HashSet in C# with Examples
Python - Truncated Normal Distribution in Statistics - GeeksforGeeks

10 Jan, 2020
scipy.stats.truncnorm() is a Truncated Normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : Truncated Normal continuous random variable
Code #1 : Creating Truncated Normal continuous random variable
# importing library  from scipy.stats import truncnorm     numargs = truncnorm .numargs a, b = 0.2, 0.8rv = truncnorm (a, b)     print ("RV : \n", rv)   
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D9C2FF08

Code #2 : Truncated Normal continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = truncnorm .rvs(a, b, size = 10) print ("Random Variates : \n", R)   # PDF x = np.linspace(truncnorm.ppf(0.01, a, b),                truncnorm.ppf(0.99, a, b), 10)R = truncnorm.pdf(x, 1, 3)print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 [0.56227576 0.2513349  0.66393458 0.7453009  0.79215974 0.67208054
 0.23809535 0.29203442 0.37395318 0.36091493]

Probability Distribution : 
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.04081633 0.08163265 0.12244898 0.16326531 0.20408163
 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959
 0.48979592 0.53061224 0.57142857 0.6122449  0.65306122 0.69387755
 0.73469388 0.7755102  0.81632653 0.85714286 0.89795918 0.93877551
 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347
 1.2244898  1.26530612 1.30612245 1.34693878 1.3877551  1.42857143
 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939
 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735
 1.95918367 2.        ]
  
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np   x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = truncnorm.pdf(x, a, b) y2 = truncnorm.pdf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python OpenCV | cv2.imwrite() method

07 Aug, 2019
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imwrite() method is used to save an image to any storage device. This will save the image according to the specified format in current working directory.
Syntax: cv2.imwrite(filename, image)
Parameters:filename: A string representing the file name. The filename must include image format like .jpg, .png, etc.image: It is the image that is to be saved.
Return Value: It returns true if image is saved successfully.
Example #1:
# Python program to explain cv2.imwrite() method  # importing cv2 import cv2  # importing os module  import os  # Image pathimage_path = r'C:\Users\Rajnish\Desktop\GeeksforGeeks\geeks.png'  # Image directorydirectory = r'C:\Users\Rajnish\Desktop\GeeksforGeeks'  # Using cv2.imread() method# to read the imageimg = cv2.imread(image_path)  # Change the current directory # to specified directory os.chdir(directory)  # List files and directories  # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'  print("Before saving image:")  print(os.listdir(directory))    # Filenamefilename = 'savedImage.jpg'  # Using cv2.imwrite() method# Saving the imagecv2.imwrite(filename, img)  # List files and directories  # in 'C:/Users / Rajnish / Desktop / GeeksforGeeks'  print("After saving image:")  print(os.listdir(directory))  print('Successfully saved')
Output:
Before saving image:
['geeks.png']
After saving image:
['geeks.png', 'savedImage.jpg']
Successfully saved

OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Bubble Sort

13 Jun, 2022
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. 
Python3
# Python program for implementation of Bubble Sort def bubbleSort(arr):    n = len(arr)    # optimize code, so if the array is already sorted, it doesn't need    # to go through the entire process    swapped = False    # Traverse through all array elements    for i in range(n-1):        # range(n) also work but outer loop will        # repeat one time more than needed.        # Last i elements are already in place        for j in range(0, n-i-1):             # traverse the array from 0 to n-i-1            # Swap if the element found is greater            # than the next element            if arr[j] > arr[j + 1]:                swapped = True                arr[j], arr[j + 1] = arr[j + 1], arr[j]                 if not swapped:            # if we haven't needed to make a single swap, we            # can just exit the main loop.            return  # Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print("Sorted array is:")for i in range(len(arr)):    print("% d" % arr[i], end=" ")
Sorted array is:
 11  12  22  25  34  64  90 
Time Complexity:  O(n2).
Auxiliary Space: O(1).
Please refer complete article on Bubble Sort for more details! 
Python3
def bubblesort(elements):    swapped = False    # Looping from size of array from last index[-1] to index [0]    for n in range(len(elements)-1, 0, -1):        for i in range(n):            if elements[i] > elements[i + 1]:                swapped = True                # swapping data if the element is less than next element in the array                elements[i], elements[i + 1] = elements[i + 1], elements[i]               if not swapped:            # exiting the function if we didn't make a single swap            # meaning that the array is already sorted.            return elements = [39, 12, 18, 85, 72, 10, 2, 18] print("Unsorted list is,")print(elements)bubblesort(elements)print("Sorted Array is, ")print(elements)
Unsorted list is,
[39, 12, 18, 85, 72, 10, 2, 18]
Sorted Array is, 
[2, 10, 12, 18, 18, 39, 72, 85]
Time Complexity:  O(n2). However in practice, this optimized version might take less time as when array gets sorted, function would return.
Auxiliary Space: O(1).
banvariguptajhinjhak
priyampatel9911
surinderdawra388
surindertarika1234
satyam00so
amartyaghoshgfg
talktoanmol
chandramauliguptach
BubbleSort
python sorting-exercises
Python Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to add two numbers
Python Program for factorial of a number
Iterate over characters of a string in Python
Python program to interchange first and last elements in a list
Python program to find second largest number in a list
Merge Sort
QuickSort
Insertion Sort
Selection Sort Algorithm
ln command in Linux with Examples

23 May, 2019
The ln command is used to create links between files. Before going into the application of the ln command in detail, please refer the below link for a clear understanding of the hard link and soft link in Linux. Hard and Soft Links in Linux
Syntax:
ln [OPTION]... [-T] TARGET LINK_NAME   (1st form)
ln [OPTION]... TARGET... DIRECTORY     (2nd form)
ln [OPTION]... -t DIRECTORY TARGET...  (3rd form)

Basically, ln command is used to create hard links and soft links for files in Linux. Let’s discuss all the three forms one by one.
1st Form: This form is simple, the source file with destination link name you have to specify:
2nd Form: Here, we have to give source file and directory as a link, simply the source file will be copied to the directory which you specify. See the example below.
3rd Form: Here, we will specify the directory name and a file to be linked to the directory. It is mostly same to 2nd form.
Most Useful Options:
verbose or -v : This option will help you to know which file is linked to which file. Basically, it prints the name of each linked file.
Help or -h : It will display help option of ln command, you could even see more detailed information in those help command.
version or -v : This will display the version detail, author detail of the command.
Applications:
Symbolic links are most useful for avoiding complicated paths. Don’t want to have to remember a path that is 73 characters long? No problem, just create a symbolic link to remember where it is.
Symbolic links make it easy to make some set of files appear to exist in multiple locations without having to make separate copies.
Hard links are most useful for keeping file content in a single location by avoiding duplication of what might be a very large amount of data.
Practical Example of creation and deletion of links in Linux:
Example 1:
Example 2:
Example 3:
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
How to display array structure and values in PHP ?

07 Oct, 2021
In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions.
It includes 
Array size
Array values
Array value with Index
Each value data type
We will display the array structure using var_dump() function. This function is used to dump information about a variable. This function displays structured information such as the type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.
Syntax:
var_dump( $array_name )
Parameters: The function takes a single argument $array_name that may be one single variable or an expression containing several space-separated variables of any type.
Return Type: Array Structure
Example: PHP Program to create an array and display its structure.
PHP
<?php  // Array with subjects$array1 = array(      '0' => "Python",       '1' => "java",       '2' => "c/cpp");  // Display array structurevar_dump($array1);  ?>
array(3) {
  [0]=>
  string(6) "Python"
  [1]=>
  string(4) "java"
  [2]=>
  string(5) "c/cpp"
}

Here, 
array(3) is the size of the array ( 3 elements)
string(6) is the data type of element 1 with its size
string(4) is the data type of element 2 with its size
string(5) is the data type of element 3 with its size
Array Values: We will display the array values by using the print_r() function. This function is used to print or display information stored in a variable.
Syntax:
print_r( $variable, $isStore )
Parameters:
$variable: This parameter specifies the variable to be printed and is a mandatory parameter.
$isStore: This is an optional parameter. This parameter is of boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the print_r() function will return the output which it is supposed to print.
Return Value: Array with values.
Example: PHP program to display an array of values.
PHP
<?php  // Array with subjects$array1 = array(      '0' => "Python",       '1' => "java",       '2' => "c/cpp");  // Display array valuesprint_r($array1);  ?>
Array
(
    [0] => Python
    [1] => java
    [2] => c/cpp
)

PHP-array
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.
HTML | <img> src Attribute

27 May, 2019
The <img> src attribute is used to specify the URL of the source image.
Syntax:
<img src="URL">
Attribute Values: It contains single value URL which specifies the link of source image. There are two types of URL link which are listed below:
Absolute URL: It points to another webpage.
Relative URL: It points to other files of same web page.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML img src Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML img src Attribute</h2>      <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"          alt="GeeksforGeeks logo"></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <img> src attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Remove tags using BeautifulSoup in Python?

08 Sep, 2021
Prerequisite- Beautifulsoup module
In this article, we are going to draft a python script that removes a tag from the tree and then completely destroys it and its contents. For this, decompose() method is used which comes built into the module.
Syntax:
Beautifulsoup.Tag.decompose()


Tag.decompose() removes a tag from the tree of a given HTML document, then completely destroys it and its contents.
Implementation:
Example 1:
Python3
# import modulefrom bs4 import BeautifulSoup  # URL for scrapping data markup = '<a href="https://www.geeksforgeeks.org/">Welcome to <i>geeksforgeeks.com</i></a>'  # get URL html soup = BeautifulSoup(markup, 'html.parser')  # display before decomposeprint("Before Decompose")print(soup.a)  # decomposing the# soup datanew_tag = soup.a.decompose()print("After decomposing:")print(new_tag)
Output:
Before Decompose
<a href=”https://www.geeksforgeeks.org/”>Welcome to <i>geeksforgeeks.com</i></a>
After decomposing:
None 
Example 2: Implementation of given URL to scrape the HTML document.
Python3
# import modulefrom bs4 import BeautifulSoupimport requests  # Get URL html# Scraping the data from# Html docurl = 'https://www.geeksforgeeks.org/'reqs = requests.get(url)soup = BeautifulSoup(reqs.text, 'html.parser')  # Before decomposingprint("Before Decomposing")print(soup)  # decompose the soupresult = soup.decompose()print("After decomposing:")print(result)
Output:
Before Decomposing
<!DOCTYPE html>
<!–[if IE 7]>
<html class=”ie ie7′′ lang=”en-US” prefix=”og: http://ogp.me/ns#”>
<![endif]–>
<!–[if IE 8]>
<html class=”ie ie8′′ lang=”en-US” prefix=”og: http://ogp.me/ns#”>
<![endif]–>
<!–[if !(IE 7) | !(IE 8)  ]><!–>
<html lang=”en-US” prefix=”og: http://ogp.me/ns#”>
<!–<![endif]–>
<head>
<meta charset=”utf-8′′/>..
......
After decomposing:
None 
gulshankumarar231
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PLSQL | SQRT Function

18 Oct, 2019
The SQRT function is an inbuilt function in PLSQL which is used to return the square root of the given input number.
Syntax:
SQRT( number )
Parameters Used:This function accepts a parameters which are illustrated below:
number – This is the input number whose square root is going to be calculated.
Return Value:This function returns a numeric number which is square root of the given input number.
Supported Versions of Oracle/PLSQL is given below:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Let’s see some examples which illustrate the SQRT function:
Example-1:
DECLARE 
   Test_Number number := 25;
   
BEGIN 
   dbms_output.put_line(SQRT(Test_Number number)); 
   
END; 
Output:
5
In the above example, 5 is the square root of 25.
Example-2:
DECLARE 
   Test_Number number := 5.617;
   
BEGIN 
   dbms_output.put_line(SQRT(Test_Number number)); 
   
END; 
Output:
2.37002109695251
In the above example, 2.37002109695251 is the square root of 5.617
Example-3:
DECLARE 
   Test_Number number := 9;
   
BEGIN 
   dbms_output.put_line(SQRT(Test_Number number)); 
   
END; 
Output:
3
In the above example, 3 is the square root of 9
Advantage:This function is used to calculate the square root of the given input number.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sequence to sequence tutorial | by Sachin Abeywardana | Towards Data Science

This is one of the most powerful concepts in deep learning that started off in translation but has since moved on to question answering systems (Siri, Cortana etc.), audio transcribing etc. As the name suggests it’s useful for converting from one sequence to another.
The main idea behind this is that it contains an encoder RNN (LSTM) and a decoder rnn. One to ‘understand’ the input sequence and the decoder to ‘decode’ the ‘thought vector’ and construct an output sequence.
What’s really powerful about the thought vector is that you can plug in the output decoder to convert it into any language. i.e. you do not need to train on English to French dataset to convert from English to Spanish. You can simply plug in a decoder that was pretrained from a different set (say Portugese to Spanish). At least this is the theory behind it. May depend on how long you train it for, the size of your data etc.
I found the documentation behind seq2seq models quite lacking in tensorflow so I wrote my own model as seen below. The closest I found in the Tensorflow documentation was embedding_rnn_seq2seq however, it was not obvious in terms of implementing this function. Hence I wrote my own seq2seq model below:
# Tensor where we will feed the data into graphinputs = tf.placeholder(tf.int32, (None, x_seq_length), 'inputs')outputs = tf.placeholder(tf.int32, (None, None), 'output')targets = tf.placeholder(tf.int32, (None, None), 'targets')# Embedding layersinput_embedding = tf.Variable(tf.random_uniform((len(char2numX), embed_size), -1.0, 1.0), name='enc_embedding')output_embedding = tf.Variable(tf.random_uniform((len(char2numY), embed_size), -1.0, 1.0), name='dec_embedding')date_input_embed = tf.nn.embedding_lookup(input_embedding, inputs)date_output_embed = tf.nn.embedding_lookup(output_embedding, outputs)with tf.variable_scope("encoding") as encoding_scope:    lstm_enc = tf.contrib.rnn.BasicLSTMCell(nodes)    _, last_state = tf.nn.dynamic_rnn(lstm_enc, inputs=date_input_embed, dtype=tf.float32)with tf.variable_scope("decoding") as decoding_scope:    lstm_dec = tf.contrib.rnn.BasicLSTMCell(nodes)    dec_outputs, _ = tf.nn.dynamic_rnn(lstm_dec, inputs=date_output_embed, initial_state=last_state)#connect outputs to logits = tf.contrib.layers.fully_connected(dec_outputs, num_outputs=len(char2numY), activation_fn=None) with tf.name_scope("optimization"):    # Loss function    loss = tf.contrib.seq2seq.sequence_loss(logits, targets, tf.ones([batch_size, y_seq_length]))    # Optimizer    optimizer = tf.train.RMSPropOptimizer(1e-3).minimize(loss)
The full tutorial can be accessed in this video (and the code (Lesson 19) if you wish to skip the video):
See here for my course on Machine Learning and Deep Learning (Use code DEEPSCHOOL-MARCH to 85% off).
C# - Interfaces

An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.
Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities.
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration −
public interface ITransactions {
   // interface members
   void showTransaction();
   double getAmount();
}
The following example demonstrates implementation of the above interface −
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication {
   
   public interface ITransactions {
      // interface members
      void showTransaction();
      double getAmount();
   }
   public class Transaction : ITransactions {
      private string tCode;
      private string date;
      private double amount;
      
      public Transaction() {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }
      public Transaction(string c, string d, double a) {
         tCode = c;
         date = d;
         amount = a;
      }
      public double getAmount() {
         return amount;
      }
      public void showTransaction() {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());
      }
   }
   class Tester {
     
      static void Main(string[] args) {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
         
         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
World Map on HTML5 Canvas or SVG

You can use SVG to create a World Map and work with raphaeljs.
Firstly, learn how to add Raphael.js, and create a circle,
var paper = Raphael(10, 50, 320, 200);

// drawing circls
var circle = paper.circle(50, 40, 10);

circle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
Then refer the following to create a World Map.
C++ Algorithm Library - find_if_not() Function

The C++ function std::algorithm::find_if_not() finds the last occurrence of the element that satisfies the condition. It uses unary predicate to specify condition.
Following is the declaration for std::algorithm::find_if_not() function form std::algorithm header.
template <class InputIterator, class UnaryPredicate>
InputIterator find_if_not(InputIterator first, InputIterator last, UnaryPredicate pred);

first − Input iterator to the initial position.
first − Input iterator to the initial position.
last − Final iterator to the final position.
last − Final iterator to the final position.
pred − A unary predicate which accepts one argument and returns bool.
pred − A unary predicate which accepts one argument and returns bool.
returns an iterator to the first element in the range (first,last) for which unary predicate returns false. If no such element is found, the function returns last.
Throws exception if either predicate or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear.
The following example shows the usage of std::algorithm::find_if_not() function.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool unary_pred(int n) {
   return ((n % 2) == 0);
}

int main(void) {
   vector<int> v = {2, 4, 61, 8, 10};
   auto it = find_if_not(v.begin(), v.end(), unary_pred);

   if (it != end(v))
      cout << "First odd number is " << *it << endl;

   v = {2, 4, 6, 8, 10};

   it = find_if_not(v.begin(), v.end(), unary_pred);

   if (it == end(v))
      cout << "Only enven elements present in the sequence." << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
First odd number is 61
Only enven elements present in the sequence.

 Print
 Add Notes
 Bookmark this page
Compare two arrays of single characters and return the difference? JavaScript

We are required to compare, and get the difference, between two arrays containing single character strings appearing multiple times in each array.
Example of two such arrays are −
const arr1 = ['A', 'C', 'A', 'D'];
const arr2 = ['F', 'A', 'T', 'T'];
We will check each character at the same position and return only the parts who are different.
const arr1 = ['A', 'C', 'A', 'D'];
const arr2 = ['F', 'A', 'T', 'T'];
const findDifference = (arr1, arr2) => {
   const min = Math.min(arr1.length, arr2.length);
   let i = 0;
   const res = [];
   while (i < min) {
      if (arr1[i] !== arr2[i]) {
         res.push(arr1[i], arr2[i]);
      };
      ++i;
   };
   return res.concat(arr1.slice(min), arr2.slice(min));
};
console.log(findDifference(arr1, arr2));
And the output in the console will be −
[
   'A', 'F', 'C',
   'A', 'A', 'T',
   'D', 'T'
]
How to only get the data of the nested JSON object in MongoDB?

To get the data of the nested JSON object in MongoDB, use findOne(). Let us create a collection with documents −
> db.demo109.insertOne(
...    {
...       "Name" : "Chris",
...       "Subjects" : [
...          {
...             "Id" : "100",
...             "Name":"MySQL",
...             "InstructorDetails" : [
...                {
...                   "Name" : "John"
...                }
...             ]
...          },
...          {
...             "Id" : "101",
...             "Name":"MongoDB",
...             "InstructorDetails" : [
...                {
...                   "Name" : "Mike"
...                }
...             ]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2ee7df9fd5fd66da21447a")
}
Display all documents from a collection with the help of find() method −
> db.demo109.find();
This will produce the following output −
{
   "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Name" : "Chris", "Subjects" : [
      { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] },
      { "Id" : "101", "Name" : "MongoDB", "InstructorDetails" : [ { "Name" : "Mike" } ] }
   ] 
}
Following is the query to only get the data of the nested JSON object in MongoDB −
> db.demo109.findOne(
... { Name: "Chris"}
... , { 'Subjects': { $elemMatch:{'Id':"100"} } }
... , function (err, doc) { console.log(doc) });
This will produce the following output −
{
   "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"),
   "Subjects" : [
      {
         "Id" : "100",
         "Name" : "MySQL",
         "InstructorDetails" : [
            {
               "Name" : "John"
            }
         ]
      }
   ]
}
JavaScript to check consecutive numbers in array?

To check for consecutive numbers like 100, 101, 102, etc., use the concept of reduce(). TRUE
would be returned for consecutive numbers, else false is the return value.
const sequceIsConsecutive = (obj) =>
Boolean(obj.reduce((output, lastest) => (output ?
(Number(output.number) + 1=== Number(lastest.number) ? lastest : false)
: false)));
console.log("Is Consecutive="+sequceIsConsecutive ([{ number: '100'
},{number: '101'} ,{number: '102' }]));
console.log("Is Consecutive="+sequceIsConsecutive([{ number: '100' },
{number: '102'} ,{number: '104' }]));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo126.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo126.js
Is Consecutive=true
Is Consecutive=false
Longest Increasing Subsequence in Python

Suppose we have an unsorted list of integers. We have to find the longest increasing subsequence. So if the input is [10,9,2,5,3,7,101,18], then the output will be 4, as the increasing subsequence is [2,3,7,101]
To solve this, we will follow these steps −
trail := an array of length 0 to length of nums – 1, and fill this with 0
size := 0
for x in numsi := 0, j := sizewhile i is not jmid := i + (j - i) / 2if trails[mid] < x, then i := mid + 1, otherwise j := midtrails[i] := xsize := maximum of i + 1 and size
i := 0, j := size
while i is not jmid := i + (j - i) / 2if trails[mid] < x, then i := mid + 1, otherwise j := mid
mid := i + (j - i) / 2
if trails[mid] < x, then i := mid + 1, otherwise j := mid
trails[i] := x
size := maximum of i + 1 and size
return size
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def lengthOfLIS(self, nums):
      tails =[0 for i in range(len(nums))]
      size = 0
      for x in nums:
         i=0
         j=size
         while i!=j:
            mid = i + (j-i)//2
            if tails[mid]< x:
               i= mid+1
            else:
               j = mid
               tails[i] = x
               size = max(i+1,size)
               #print(tails)
      return size
ob1 = Solution()
print(ob1.lengthOfLIS([10,9,2,5,3,7,101,18]))
[10,9,2,5,3,7,101,18]
4
MySQL stored-procedure: out parameter?

Here is a stored procedure that takes one parameter for input (IN) and second parameter for output (OUT)
mysql> delimiter //
mysql> create procedure Sp_SQRT(IN Number1 INT, OUT Number2 FLOAT)
   -> Begin
   -> set Number2=sqrt(Number1);
   -> end;
   -> //
Query OK, 0 rows affected (0.24 sec)
mysql> delimiter ;
Call the stored procedure and send the value to the user variable. The syntax is as follows
CALL yourStoredProcedureName(anyIntegerValue,@anyVariableName);
Check what value is stored in the variable @anyVariableName. The syntax is as follows
SELECT @anyVariableName;
Created the stored procedure with the name ‘Sp_SQRT’. The query is as follows to call the stored procedure
mysql> call Sp_SQRT(36,@MySquareRootNumber);
Query OK, 0 rows affected (0.02 sec)
Check the value of variable @MySquareRootNumber using select statement
mysql> select @MySquareRootNumber;
The following is the output
+---------------------+
| @MySquareRootNumber |
+---------------------+
|                   6 |
+---------------------+
1 row in set (0.00 sec)
Swing Examples - Show Save File Dialog

Following example showcase how to create and show a save as file dialog in swing based application.
We are using the following APIs.
JFileChooser − To create a standard File chooser which allows user to save file/Folders.
JFileChooser − To create a standard File chooser which allows user to save file/Folders.
JFileChooser.showSaveDialog − To show the Save As dialog box.
JFileChooser.showSaveDialog − To show the Save As dialog box.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JLabel label = new JLabel();

      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            int option = fileChooser.showSaveDialog(frame);
            if(option == JFileChooser.APPROVE_OPTION){
               File file = fileChooser.getSelectedFile();
               label.setText("File Saved as: " + file.getName());
            }else{
               label.setText("Save command canceled");
            }
         }
      });

      panel.add(button);
      panel.add(label);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
}
 Print
 Add Notes
 Bookmark this page
Addition and Blending of images using OpenCV in Python - GeeksforGeeks

06 Feb, 2018
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images.
Below is code for Addition of two images using OpenCV :
# Python program for adding# images using OpenCV  # import OpenCV fileimport cv2  # Read Image1mountain = cv2.imread('F:\mountain.jpg', 1)  # Read image2dog = cv2.imread('F:\dog.jpg', 1)  # Add the imagesimg = cv2.add(mountain, dog)  # Show the imagecv2.imshow('image', img)  # Wait for a keycv2.waitKey(0)  # Distroy all the window opencv2.distroyAllWindows()
But sometimes we do not want to perform simple addition in image, so in this case we have blending. This is also image addition, but different weights are given to images so that it gives a feeling of blending or transparency. Images are added as per the equation below :
g(x) = (1 - a)f(x) + af1(x)
By varying a from 0 -> 1, you can perform a cool transition between one image to another. Here two images are taken to blend together. First image is given a weight of 0.3 and second image is given 0.7, cv2.addWeighted() applies following equation on the image :
img = a . img1 + b . img 2 + y
Here y is taken as zero.
Below is code for Blending of images using OpenCV :
# Python program for blending of# images using OpenCV  # import OpenCV fileimport cv2  # Read Image1mountain = cv2.imread('F:\mountain.jpg', 1)  # Read image2dog = cv2.imread('F:\dog.jpg', 1)  # Blending the images with 0.3 and 0.7img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0)  # Show the imagecv2.imshow('image', img)  # Wait for a keycv2.waitKey(0)  # Distroy all the window opencv2.distroyAllWindows()
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to compare two dates in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
int compareTo(T o)
import java.text.*;
import java.util.Date;
public class CompareTwoDatesTest {
   public static void main(String[] args) throws ParseException {
      SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
      Date d1 = sdformat.parse("2019-04-15");
      Date d2 = sdformat.parse("2019-08-10");
      System.out.println("The date 1 is: " + sdformat.format(d1));
      System.out.println("The date 2 is: " + sdformat.format(d2));
      if(d1.compareTo(d2) > 0) {
         System.out.println("Date 1 occurs after Date 2");
      } else if(d1.compareTo(d2) < 0) {
         System.out.println("Date 1 occurs before Date 2");
      } else if(d1.compareTo(d2) == 0) {
         System.out.println("Both dates are equal");
      }
   }
}
In the above example, the date d1 occurs before the date d2, so it can display "Date 1 occurs before Date 2" in the console.
The date 1 is: 2019-04-15
The date 2 is: 2019-08-10
Date 1 occurs before Date 2