code-rag-bench/online-tutorials huggingface dataset:
ES6 - RegExp match()

This method retrieves the matches.
str.match(regexp)           

Regexp − A regular expression object.
Regexp − A regular expression object.
Returns an array of matches and null if no matches are found.
var str = 'Welcome to ES6.We are learning ES6'; 
var re = new RegExp("We"); 
var found = str.match(re); 
console.log(found);  
We     


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks

28 Jun, 2021
At what time between 6 a.m. and 7 a.m. will the minute hand and hour hand of a clock make an angle closest to 60o(A) 6:22 am(B) 6:27 am(C) 6:38 am(D) 6:45 amAnswer: (A)Explanation:
Speed of the Hour hand = ( 360 degree ) / ( 12 * 60 minutes ) 
                       = 0.5 degree / minute.
Speed of the minute hand = ( 360 degree ) / ( 60 minutes ) 
                         = 6 degree / minute.
At 6 am, hour hand will point vertically downward to 6 in the clock, and minute hand will point vertically upward to 12 in the clock. ( Hence they are opposite with a gap of 180 degree between them).
Now after t minutes , The angle between these two hands will be either of the below two:

(180 - 6t) + 0.5t, when the minute hand is 
                   behind the hour hand or,

6t - (180 + 0.5t), when the minute hand is 
                    ahead of hour hand,

Now the the question asks for angle of 60 degree.

Hence, 
(180 - 6t) + 0.5t = 60 , we get t = 21.8 minute
and
6t - ( 180 + 0.5t ) = 60, we get t = 48 minutess
Hence the closest to answer is 22 minutes, i.e. 6.22 am. Hence answer is A.Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
Speed up your pytest GitHub Actions with Docker | by Emeline Floc'h | Towards Data Science

GitHub introduced Actions in 2018 as a fast and easy to set up CI/CD solution. Because of its recent release date, documentation on the topic is sometimes hard to find and I couldn’t put my hands on something that explained how to set up your Actions that run pytest in a pipenv environment into a Docker container. Here is a quick summary of the method I used on a Mac.
To install Docker, download Docker Desktop from the homepage, and follow the instructions on the desktop app. You’ll need to create a Docker Hub account to publish your Docker image and be able to use it in your GitHub Actions.
To create a Docker image, create a file called Dockerfile in your python project root folder, at the same level as your Pipfile.
In Dockerfile copy the following lines.
# Get the python 3.8 base docker imageFROM python:3.8# Install pipenvRUN pip install pipenv# Copy your Pipfile and Pipfile.lock in your containerCOPY Pipfile .COPY Pipfile.lock .# Install all the dependencies from your lock file directly into the # containerRUN pipenv install — system — deploy
Once you’ve saved the Dockerfile, run the following commands to update your Pipfile.lock file, build your docker container using your Docker Hub username then push your Docker image to Docker Hub.
>> pipenv lock>> docker build -t <hub-username>/<repo-name>>> docker push <hub-username>/<repo-name>
You now have a docker image pushed to Docker Hub and it should appear in your account. You are now ready to use it within your Github Actions workflow.
The last step is creating a workflow that runs pytest in your container. Follow the following template and copy these lines in a YAML file.
name: Pytest with Pipenv & Docker# workflow triggered by any push on any branchon: [push]jobs:  build:    name: Pytest in Pipenv    # runs on the latest Ubuntu    runs-on: ubuntu-latest     # runs within your Docker container    container:      image: docker://<hub-username>/<repo-name>:latest    # checkout your code from your repository    # and runs pytest in your pipenv environment    steps:    - uses: actions/checkout@v2    - name: Test with pytest      run: |          pipenv run pytest tests/      
Save this file in your .github/workflows/ folder. Once all these steps are done and you push code to your repository with tests in your tests/ folder, you should see on the GitHub Actions page that your container has been initialized and that your tests have been run in the container. You should also see that the setup of the local environment was much faster than by simply installing the dependencies from the pipfile in your workflow.
And there you have it, the easiest way to speed up your pytest in Github Actions.
Perl Assignment Operators Example

Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage −
=
Simple assignment operator, Assigns values from right side operands to left side operand
Example − $c = $a + $b will assigned value of $a + $b into $c
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
Example − $c += $a is equivalent to $c = $c + $a
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
Example − $c -= $a is equivalent to $c = $c - $a
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
Example − $c *= $a is equivalent to $c = $c * $a
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
Example − $c /= $a is equivalent to $c = $c / $a
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
Example − $c %= $a is equivalent to $c = $c % a
**=
Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand
Example − $c **= $a is equivalent to $c = $c ** $a
Try the following example to understand all the assignment operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program.
#!/usr/local/bin/perl
 
$a = 10;
$b = 20;

print "Value of \$a = $a and value of \$b = $b\n";

$c = $a + $b;
print "After assignment value of \$c = $c\n";

$c += $a;
print "Value of \$c = $c after statement \$c += \$a\n";

$c -= $a;
print "Value of \$c = $c after statement \$c -= \$a\n";

$c *= $a;
print "Value of \$c = $c after statement \$c *= \$a\n";

$c /= $a;
print "Value of \$c = $c after statement \$c /= \$a\n";

$c %= $a;
print "Value of \$c = $c after statement \$c %= \$a\n";

$c = 2;
$a = 4;
print "Value of \$a = $a and value of \$c = $c\n";
$c **= $a;
print "Value of \$c = $c after statement \$c **= \$a\n";
When the above code is executed, it produces the following result −
Value of $a = 10 and value of $b = 20
After assignment value of $c = 30
Value of $c = 40 after statement $c += $a
Value of $c = 30 after statement $c -= $a
Value of $c = 300 after statement $c *= $a
Value of $c = 30 after statement $c /= $a
Value of $c = 0 after statement $c %= $a
Value of $a = 4 and value of $c = 2
Value of $c = 16 after statement $c **= $a


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to convert an array into a matrix in R?

To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c). We need to understand the dimension of the array making the conversion otherwise the output will not be as expected.
Consider the below array −
 Live Demo
x1<-array(1:50,dim=c(5,5,2))
x1
, , 1
    [,1] [,2] [,3] [,4]  [,5]
[1,]  1   6    11   16    21
[2,]  2   7    12   17    22
[3,]  3   8    13   18    23
[4,]  4   9    14   19    24
[5,]  5  10    15   20    25
, , 2
    [,1] [,2] [,3] [,4] [,5]
[1,] 26  31   36   41   46
[2,] 27  32   37   42   47
[3,] 28  33   38   43   48
[4,] 29  34   39   44   49
[5,] 30  35   40   45   50
Converting x1 into a matrix −
apply(x1,2,c)
    [,1] [,2] [,3] [,4] [,5]
[1,]  1    6   11   16   21
[2,]  2    7   12   17   22
[3,]  3    8   13   18   23
[4,]  4    9   14   19   24
[5,]  5   10   15   20   25
[6,] 26   31   36   41   46
[7,] 27   32   37   42   47
[8,] 28   33   38   43   48
[9,] 29   34   39   44   49
[10,] 30  35   40   45   50
 Live Demo
x2<-array(rpois(20,5),dim=c(10,2,2))
x2
, , 1
    [,1] [,2]
[1,]  8    7
[2,]  8    9
[3,]  6    6
[4,]  5    5
[5,]  5    6
[6,]  5    7
[7,]  1    3
[8,]  8    7 
[9,]  6    3
[10,] 3    2
, , 2
   [,1] [,2]
[1,] 8    7
[2,] 8    9
[3,] 6    6
[4,] 5    5
[5,] 5    6
[6,] 5    7
[7,] 1    3
[8,] 8    7
[9,] 6    3
[10,] 3   2
Converting x2 into a matrix −
apply(x2,2,c)
   [,1] [,2]
[1,] 8    7
[2,] 8    9
[3,] 6    6
[4,] 5    5
[5,] 5    6
[6,] 5    7
[7,] 1    3
[8,] 8    7
[9,] 6    3
[10,] 3   2
[11,] 8   7
[12,] 8   9
[13,] 6   6
[14,] 5   5
[15,] 5   6
[16,] 5   7
[17,] 1   3
[18,] 8   7 
[19,] 6   3
[20,] 3   2
Query MongoDB with “like” implementation on name and email field beginning with a specific letter?

For “like” implementation in MongoDB, use / / and set that specific letter in between. For example −
/J/
Let us create a collection with documents −
> db.demo554.insertOne({"UserName":"John","UserMailId":"John@gmail.com"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f1cfed1d72c4545cb8679")
}
> db.demo554.insertOne({"UserName":"Chris","UserMailId":"Chris@gmail.com"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f1d0cd1d72c4545cb867a")
}
> db.demo554.insertOne({"UserName":"Jace","UserMailId":"Jace@gmail.com"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8f1d1cd1d72c4545cb867b")
}
Display all documents from a collection with the help of find() method −
> db.demo554.find();
This will produce the following output −
{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "John@gmail.com" }
{ "_id" : ObjectId("5e8f1d0cd1d72c4545cb867a"), "UserName" : "Chris", "UserMailId" : "Chris@gmail.com" }
{ "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "Jace@gmail.com" }
Following is the query to implementation of “like” −
> db.demo554.find({
...    "$or": [
...       { "UserName": /J/ },
...
...       { "UserMailId": /J/ }
...    ]
... }
... );
This will produce the following output −
{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "John@gmail.com" }
{ "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "Jace@gmail.com" }
What are Ordered dictionaries in Python?

An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, supporting the usual dict methods.If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'mango': 2}
>>> od=OrderedDict(d.items())
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('mango', 2)])
>>> od=OrderedDict(sorted(d.items()))
>>> od
OrderedDict([('apple', 4), ('banana', 3), ('mango', 2), ('pear', 1)])
>>> t=od.popitem()
>>> t
('pear', 1)
>>> od=OrderedDict(d.items())
>>> t=od.popitem()
>>> t
('mango', 2)
Find the Number Occurring Odd Number of Times using Lambda expression and reduce function in Python

In this article we are required to find that number from the list which occurs odd number of times in the given list. We are also required to use the Lambda function and the reduce function.
We design a function where the reduce function is used by applying the Lambda function to check if the element is present odd number of times.
 Live Demo
from functools import reduce
def oddcount(i):
   print(reduce(lambda x, y: x ^ y, i))
listA = [12,34,12,12,34]
print("Given list:\n",listA)
print("The element present odd number of times:")
oddcount(listA)
Running the above code gives us the following result −
Given list:
[12, 34, 12, 12, 34]
The element present odd number of times:
12
Python dictionary with keys having multiple inputs

When it is required to create a dictionary where keys have multiple inputs, an empty dictionary can be created, and the value for a specific key can be specified.
Below is the demonstration of the same −
 Live Demo
my_dict = {}

a, b, c = 15, 26, 38
my_dict[a, b, c] = a + b - c

a, b, c = 5, 4, 11
my_dict[a, b, c] = a + b - c

print("The dictionary is :")
print(my_dict)
The dictionary is :
{(15, 26, 38): 3, (5, 4, 11): -2}
The required packages are imported.
The required packages are imported.
An empty dictionary is defined.
An empty dictionary is defined.
The values for a specific key are specified.
The values for a specific key are specified.
The output is displayed on the console.
The output is displayed on the console.
What is the best way to compare two strings in JavaScript?

To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.
You can try to run the following code to compare two strings
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button onclick="compareStr()">Compare Strings</button>
      <p id="test"></p>
      <script>
         function compareStr() {
            var string1 = "World";
            var string2 = "World";
            var result = string1.localeCompare(string2);

            document.getElementById("test").innerHTML = result;
         }
      </script>
   </body>
</html>
Getting a Matrix of number of rows in R Programming - row() Function - GeeksforGeeks

04 Jun, 2020
row() function in R Language is used to get the row number of a matrix.
Syntax: row(x, as.factor=FALSE)
Parameters:x: matrixas.factor: a logical value indicating whether the value should be returned as a factor of column labels (created if necessary) rather than as numbers
Example 1:
# R program to illustrate# row function  # Initializing a matrix with# 2 rows and 2 columnsx <- matrix(c(1, 2, 3, 4), 2, 2)  # Getting the matrix representationx  # Calling the row() functionrow(x)
Output:
$Rscript main.r
     [, 1] [, 2]
[1, ]    1    3
[2, ]    2    4

     [, 1] [, 2]
[1, ]    1    1
[2, ]    2    2

Example 2:
# R program to illustrate# row function  # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(rep(1:12), 3, 3)  # Getting the matrix representationx  # Calling the row() functionrow(x)
Output:
    [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

     [, 1] [, 2] [, 3]
[1, ]    1    1    1
[2, ]    2    2    2
[3, ]    3    3    3

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
Bootstrap well class

A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well.
You can try to run the following code to implement well class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "well">This is demo text!</div>
   </body>
</html>
Mahotas - Bernsen local thresholding - GeeksforGeeks

08 Dec, 2021
In this article, we will see how we can implement bernsen local thresholding in mahotas. Bernsen’s method is one of locally adaptive binarization methods developed for image segmentation. In this study, Bernsen’s locally adaptive binarization method is implemented and then tested for different grayscale images.
In this tutorial, we will use “luispedro” image, below is the command to load it. 
mahotas.demos.load('luispedro')
Below is the luispedro image  
In order to do this we will use mahotas.thresholding.bernsen method  
Syntax : mahotas.thresholding.bernsen(image, contrast_threshold, global_threshold)Argument : It takes image object and two integer as argumentReturn : It returns image object  
Note: Input image should be filtered or should be loaded as grey
In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this 
image = image[:, :, 0]
Example 1:  
Python3
# importing required librariesimport mahotasimport mahotas.demosimport numpy as npfrom pylab import imshow, gray, showfrom os import path # loading the imagephoto = mahotas.demos.load('luispedro')  # loading image as greyphoto = mahotas.demos.load('luispedro', as_grey = True) # converting image type to unit8# because as_grey returns floating valuesphoto = photo.astype(np.uint8) # showing original imageprint("Image")imshow(photo)show() # bernsen thresholdphoto = mahotas.thresholding.bernsen(photo, 7, 200)  print("Image with bernsen threshold") # showing imageimshow(photo)show()
Output : 
Example 2: 
Python3
# importing required librariesimport mahotasimport numpy as npfrom pylab import imshow, showimport os  # loading imageimg = mahotas.imread('dog_image.png')      # setting filter to the imageimg = img[:, :, 0] print("Image") # showing the imageimshow(img)show()  # bernsen thresholdimg = mahotas.thresholding.bernsen(img, 5, 100)  print("Image with bernsen threshold") # showing imageimshow(img)show()
Output : 
 
gabaa406
arorakashish0911
simranarora5sos
sumitgumber28
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Have you tried Pylance for VS Code? If not, here’s why you should. | by SJ Porter | Towards Data Science

If you work with Python and Visual Studio Code, go ahead and do yourself a favor: download the Pylance extension (preview) and try it out for yourself.
Pylance is an extension for Visual Studio Code. More specifically, Pylance is a Python language server — this means it offers enhancements to IntelliSense, syntax highlighting, package import resolution, and a myriad of other features for an improved development experience in the Python language.
You can find the full list of features here. To keep things simple, I’m going to focus on the three most useful features based on my experience with the extension thus far.
In Python, understanding how to correctly import dependencies from both internal and external modules is a challenge for newbies and professionals alike.
The Pylance extension offers a feature which automatically adds imports to the top of your Python files when you reference a dependency in your environment. It will also show a lightbulb icon with suggestions to add or remove imports depending on the scenario.
It’s worth mentioning that you need to have the modules you’re referencing installed in your Python environment for this to work.
Pylance’s semantic highlighting means that classes, functions, properties, and other Python object types are colored (i.e. highlighted) on the screen in a much more intuitive and readable fashion.
It’s much easier to demonstrate this visually than to attempt to describe it, so here are some screenshots...
Type hinting, or the practice of specifying expected data types for variables/functions/classes/etc., is fairly new to Python. Python does not enforce type hinting, so at this point it’s essentially just a best practice for documentation.
However, with Pylance, enabling the type checking setting (see below) will help you understand if your code violates any documented type hints. There are two modes for type checking, basic and strict (configured in preferences). At this time I would recommend sticking to the basic setting.
{    "python.analysis.typeCheckingMode": "basic"}
The Pylance extension for Visual Studio Code is still in preview. There’s more work to be done to improve performance, expand upon the documentation, and resolve some bugs. However, it’s already a fantastic extension in my experience. I certainly don’t want to go back to the default language server for Python after enabling Pylance.
I recommend you try the extension out for yourself and feel free to leave a comment with your thoughts!
Extract the Day / Month / Year from a Timestamp in PHP MySQL?

To extract the Day/Month/Year from a timestamp, you need to use the date_parse() function. The syntax as follows −
print_r(date_parse(“anyTimeStampValue”));
The PHP code is as follows −
$yourTimeStampValue="2019-02-04 12:56:50";
print_r(date_parse($yourTimeStampValue));
The snapshot of PHP code is as follows −
The following is the output −
Array ( [year] => 2019 [month] => 2 [day] => 4 [hour] => 12 [minute] => 56 [second] => 50 [fraction] => 0 [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0 [errors] => Array ( ) [is_localtime] => )
The snapshot of the sample output −
Fortran - Reshape Functions

The following table describes the reshape function:
Example
The following example demonstrates the concept:
program arrayReshape
implicit none

interface
   subroutine write_matrix(a)
   real, dimension(:,:) :: a
   end subroutine write_matrix
   end interface

   real, dimension (1:9) :: b = (/ 21, 22, 23, 24, 25, 26, 27, 28, 29 /)
   real, dimension (1:3, 1:3) :: c, d, e
   real, dimension (1:4, 1:4) :: f, g, h

   integer, dimension (1:2) :: order1 = (/ 1, 2 /)
   integer, dimension (1:2) :: order2 = (/ 2, 1 /)
   real, dimension (1:16) :: pad1 = (/ -1, -2, -3, -4, -5, -6, -7, -8, &
                                 & -9, -10, -11, -12, -13, -14, -15, -16 /)

   c = reshape( b, (/ 3, 3 /) )
   call write_matrix(c)

   d = reshape( b, (/ 3, 3 /), order = order1)
   call write_matrix(d)

   e = reshape( b, (/ 3, 3 /), order = order2)
   call write_matrix(e)

   f = reshape( b, (/ 4, 4 /), pad = pad1)
   call write_matrix(f)

   g = reshape( b, (/ 4, 4 /), pad = pad1, order = order1)
   call write_matrix(g)

   h = reshape( b, (/ 4, 4 /), pad = pad1, order = order2)
   call write_matrix(h)

end program arrayReshape


subroutine write_matrix(a)
   real, dimension(:,:) :: a
   write(*,*)
   
   do i = lbound(a,1), ubound(a,1)
      write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
   end do
end subroutine write_matrix
When the above code is compiled and executed, it produces the following result:
21.0000000  24.0000000  27.0000000    
22.0000000  25.0000000  28.0000000    
23.0000000  26.0000000  29.0000000    

21.0000000  24.0000000  27.0000000    
22.0000000  25.0000000  28.0000000    
23.0000000  26.0000000  29.0000000    

21.0000000  22.0000000  23.0000000    
24.0000000  25.0000000  26.0000000    
27.0000000  28.0000000  29.0000000    

21.0000000  25.0000000  29.0000000   -4.00000000    
22.0000000  26.0000000  -1.00000000  -5.00000000    
23.0000000  27.0000000  -2.00000000  -6.00000000    
24.0000000  28.0000000  -3.00000000  -7.00000000    

21.0000000  25.0000000  29.0000000   -4.00000000    
22.0000000  26.0000000  -1.00000000  -5.00000000    
23.0000000  27.0000000  -2.00000000  -6.00000000    
24.0000000  28.0000000  -3.00000000  -7.00000000    

21.0000000  22.0000000  23.0000000   24.0000000    
25.0000000  26.0000000  27.0000000   28.0000000    
29.0000000  -1.00000000 -2.00000000  -3.00000000    
-4.00000000 -5.00000000 -6.00000000  -7.00000000    

 Print
 Add Notes
 Bookmark this page
D3.js image() Function - GeeksforGeeks

17 Aug, 2020
The d3.image() function in D3.js is a part of the request API that is used to fetch the images from any given image URL. If init is also given in the function then it sets any additional properties on the image before loading the image.  
Syntax:
d3.image(input[, init]);

Parameters: This function accepts a single parameter as mentioned above and described below:
input: It takes the address of the image to be fetched.
Return Values: It returns the image from the image URL.
Below examples illustrate the D3.js image() Function in JavaScript.
Example1:
HTML
<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8" />        <meta            name="viewport"            path1tent="width=device-width,                        initial-scale=1.0"/>        <title>D3.js image() Function</title>    </head>    <style></style>    <body>        <script src="https://d3js.org/d3.v4.min.js">        </script>        <script src="https://d3js.org/d3-dsv.v1.min.js">        </script>        <script src="https://d3js.org/d3-fetch.v1.min.js">        </script>          <script>            d3.image("https://robohash.org/image",                      { crossOrigin: "anonymous" }).then((img) => {                console.log(img);            });        </script>    </body></html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8" />        <meta            name="viewport"            path1tent="width=device-width,                        initial-scale=1.0"/>        <title>D3.js image() Function</title>    </head>    <style></style>    <body>        <script src="https://d3js.org/d3.v4.min.js">        </script>        <script src="https://d3js.org/d3-dsv.v1.min.js">        </script>        <script src="https://d3js.org/d3-fetch.v1.min.js">        </script>          <script>            d3.image(`https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv_400x400.png`,               { crossOrigin: "anonymous" }).then((img) => {                document.body.append("Image using d3.image()");                document.body.append(img);            });        </script>    </body></html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Angular File Upload
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Data Manipulation Commands in DBMS

Data manipulation commands are used to manipulate data in the database.
Some of the Data Manipulation Commands are-
Select statement retrieves the data from database according to the constraints specifies alongside.
SELECT <COLUMN NAME>
FROM <TABLE NAME>
WHERE <CONDITION>
GROUP BY <COLUMN LIST>
HAVING <CRITERIA FOR FUNCTION RESULTS>
ORDER BY <COLUMN LIST>
General syntax −
Example: select * from employee where e_id>100;
Insert statement is used to insert data into database tables.
General Syntax − 
INSERT INTO <TABLE NAME> (<COLUMNS TO INSERT>) VALUES (<VALUES TO INSERT>)
Example: insert into Employee (name, dept_id) values (‘ABC’, 3);
The update command updates existing data within a table.
General syntax −
UPDATE <TABLE NAME>
SET <COLUMN NAME> = <UPDATED COLUMN VALUE>,
<COLUMN NAME> = <UPDATED COLUMN VALUE>,
<COLUMN NAME> = <UPDATED COLUMN VALUE>,...
WHERE <CONDITION>
Example: update Employee set Name=’AMIT’ where E_id=5;
Deletes records from the database table according to the given constraints.
General Syntax −
DELETE FROM <TABLE NAME>
WHERE <CONDITION>
Example −
delete from Employee where e_id=5;
To delete all records from the table −
Delete * from <TABLE NAME>;
Use the MERGE statement to select rows from one table for update or insertion into another table. The decision whether to update or insert into the target table is based on a condition in the ON clause. It is also known as UPSERT i.e. combination of UPDATE and INSERT.
General Syntax (SQL) −
MERGE <TARGET TABLE> [AS TARGET]
USING <SOURCE TABLE> [AS SOURCE]
ON <SEARCH CONDITION>
[WHEN MATCHED
THEN <MERGE MATCHED  > ]
[WHEN NOT MATCHED [BY TARGET]
THEN < MERGE NOT MATCHED >]
[WHEN NOT MATCHED BY SOURCE
THEN <MERGE MATCHED  >];
General Syntax (Oracle)
MERGE INTO <TARGET TABLE>
USING <SOURCE TABLE>
ON <SEARCH CONDITION>
[WHEN MATCHED
THEN <MERGE MATCHED > ]
[WHEN NOT MATCHED
THEN < MERGE NOT MATCHED > ];
Groovy - For Statement

The for statement is used to iterate through a set of values. The for statement is generally used in the following way.
for(variable declaration;expression;Increment) { 
   statement #1 
   statement #2 
   ... 
}

The classic for statement consists of the following parts −
Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop.
Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop.
Expression − This will consists of an expression which will be evaluated for each iteration of the loop.
Expression − This will consists of an expression which will be evaluated for each iteration of the loop.
The increment section will contain the logic needed increment the variable declared in the for statement.
The increment section will contain the logic needed increment the variable declared in the for statement.
The following diagram shows the diagrammatic explanation of this loop.
Following is an example of the classic for statement −
class Example { 
   static void main(String[] args) {
	
      for(int i = 0;i<5;i++) {
         println(i);
      }
		
   }
}
In the above example, we are in our for loop doing three things −
Declaring a variable i and Initializing the value of i to 0
Declaring a variable i and Initializing the value of i to 0
Putting a conditional expression that the for loop should execute till the value of i is less than 5.
Putting a conditional expression that the for loop should execute till the value of i is less than 5.
Increment the value of i by 1 for each iteration.
Increment the value of i by 1 for each iteration.
The output of the above code would be −
0 
1 
2 
3 
4 


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Can I retrieve multiple documents from MongoDB by id?

Yes, to retrieve multiple docs from MongoDB by id, use the $in operator. The syntax is as follows
db.yourCollectionName.find({_id:{$in:[yourValue1,yourValue2,yourValue3,...N]}});
Let us first create a collection with documents:
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":10,"CustomerName":"John"});
{ "acknowledged" : true, "insertedId" : 10 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":14,"CustomerName":"Chris"});
{ "acknowledged" : true, "insertedId" : 14 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":20,"CustomerName":"Robert"});
{ "acknowledged" : true, "insertedId" : 20 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":25,"CustomerName":"Sam"});
{ "acknowledged" : true, "insertedId" : 25 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":30,"CustomerName":"Bob"});
{ "acknowledged" : true, "insertedId" : 30 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":34,"CustomerName":"Carol"});
{ "acknowledged" : true, "insertedId" : 34 }
Following is the query to display all documents from a collection with the help of find() method
> db.retrieveMultipleDocsByIdDemo.find().pretty();
This will produce the following output
{ "_id" : 10, "CustomerName" : "John" }
{ "_id" : 14, "CustomerName" : "Chris" }
{ "_id" : 20, "CustomerName" : "Robert" }
{ "_id" : 25, "CustomerName" : "Sam" }
{ "_id" : 30, "CustomerName" : "Bob" }
{ "_id" : 34, "CustomerName" : "Carol" }
Following is the query to retrieve multiple documents from MongoDB by id
> db.retrieveMultipleDocsByIdDemo.find({_id:{$in:[10,20,30]}});
This will produce the following output
{ "_id" : 10, "CustomerName" : "John" }
{ "_id" : 20, "CustomerName" : "Robert" }
{ "_id" : 30, "CustomerName" : "Bob" }
Ruby Integer times function with example - GeeksforGeeks

17 Mar, 2020
The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.
Syntax: (number).times
Parameter: The function takes the integer till which the numbers are returned. It also takes an block.
Return Value: The function returns all the numbers from 0 to one less than the number itself.
Example #1:
# Ruby program for times function    # Initializing the number num1 = 8   # Prints the number from 0 to num1-1 puts num1.times { |i| print i, " " }    # Initializing the numbernum2 = 5   # Prints the number from 0 to num2-1puts num2.times { |i| print i, " " }
Output :
0 1 2 3 4 5 6 7
0 1 2 3 4

Example #2:
# Ruby program for times function    # Initializing the number num1 = 4   # Prints the number from 0 to num1-1 puts num1.times { |i| print i, " " }   # Initializing the numbernum2 = -2   # Prints the number from 0 to num2puts num2.times { |i| print i, " " }
Output:
0 1 2 3
-2

Example #3:
# Ruby program for times function    # Initializing the numbernum1 = 5   # Prints enumerator as no block is given puts num1.times 
Output:
#

timcustard
Ruby Integer-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array select() function
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Numeric round() function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Types of Iterators
Include v/s Extend in Ruby
Ruby | String gsub! Method
Ruby | Data Types
Ruby | Class Method and Variables
How to add text inside a Tkinter Canvas?

Canvas is undoubtedly one of the most versatile widgets in tkinter. With Canvas, we can create shapes, texts, animate stuff, modeling 3D shapes, modeling simulations, and many more.
In order to add text inside a tkinter frame, we can use the create_text() method. We can define create_text() by adding values of font, text, and other options such as create_text(x,y,font, text, options....).
#Import the required library
from tkinter import *

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

#Set the geometry
win.geometry("750x280")

#Create a canvas object
canvas= Canvas(win, width= 1000, height= 750, bg="SpringGreen2")

#Add a text in Canvas
canvas.create_text(300, 50, text="HELLO WORLD", fill="black", font=('Helvetica 15 bold'))
canvas.pack()

win.mainloop()
Running the above code will display a canvas with some text in it.
Java Examples - Set Background to a Table

How to set background to a table in a PDF using Java.
Following is the program to set background to a table in a PDF using Java.
import com.itextpdf.kernel.color.Color; 
import com.itextpdf.kernel.pdf.PdfDocument; 
import com.itextpdf.kernel.pdf.PdfWriter; 

import com.itextpdf.layout.Document; 
import com.itextpdf.layout.border.Border; 
import com.itextpdf.layout.element.Cell; 
import com.itextpdf.layout.element.Table; 
import com.itextpdf.layout.property.TextAlignment;  

public class BackgroundToTable { 
   public static void main(String args[]) throws Exception {
      String file = "C:/EXAMPLES/itextExamples/backgroundToTable.pdf"; 

      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));     

      //Creating a Document object 
      Document doc = new Document(pdfDoc);        

      //Creating a table 
      Table table = new Table(2);     

      //Adding row 1 to the table          
      Cell c1 = new Cell(); 
      
      c1.add("Name"); 
      c1.setBackgroundColor(Color.DARK_GRAY); 
      c1.setBorder(Border.NO_BORDER); 
      c1.setTextAlignment(TextAlignment.CENTER); 
      table.addCell(c1);          

      Cell c2 = new Cell(); 
      c2.add("Raju"); 
      c2.setBackgroundColor(Color.GRAY); 
      c2.setBorder(Border.NO_BORDER); 
      c2.setTextAlignment(TextAlignment.CENTER); 
      table.addCell(c2); 

      //Adding row 2 to the table          
      Cell c3 = new Cell(); 
      
      c3.add("Id"); 
      c3.setBackgroundColor(Color.WHITE); 
      c3.setBorder(Border.NO_BORDER); 
      c3.setTextAlignment(TextAlignment.CENTER); 
      table.addCell(c3);          

      Cell c4 = new Cell(); 
      c4.add("001");
      c4.setBackgroundColor(Color.WHITE); 
      c4.setBorder(Border.NO_BORDER); 
      c4.setTextAlignment(TextAlignment.CENTER); 
      table.addCell(c4);          

      //Adding row 3 to the table 
      Cell c5 = new Cell(); 
      
      c5.add("Designation"); 
      c5.setBackgroundColor(Color.DARK_GRAY); 
      c5.setBorder(Border.NO_BORDER); 
      c5.setTextAlignment(TextAlignment.CENTER); 
      table.addCell(c5); 

      Cell c6 = new Cell(); 
      c6.add("Programmer"); 
      c6.setBackgroundColor(Color.GRAY); 
      c6.setBorder(Border.NO_BORDER); 
      c6.setTextAlignment(TextAlignment.CENTER); 
      table.addCell(c6);          

      //Adding Table to document  
      doc.add(table);  

      //Closing the document 
      doc.close();  
      System.out.println("Background added successfully.."); 
   } 
}
 Print
 Add Notes
 Bookmark this page
Matplotlib.pyplot.hexbin() function in Python - GeeksforGeeks

05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. 
The hexbin() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y.  
Syntax: matplotlib.pyplot.hexbin(x, y, C=None, gridsize=100, bins=None, xscale=’linear’, yscale=’linear’, extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=’face’, reduce_C_function=, mincnt=None, marginals=False, *, data=None, **kwargs) 
Parameters: This method accept the following parameters that are described below: 
x, y: These parameter are the sequence of data. x and y must be of the same length.
C : This parameter are the values which are accumulated in the bins.
gridsize : This parameter represents the number of hexagons in the x-direction or both direction.
xscale : This parameter uses a linear or log10 scale on the horizontal axis.
xycale : This parameter uses a linear or log10 scale on the vertical axis.
mincnt : This parameter is used to display cells with more than mincnt number of points in the cell.
marginals : This parameter is used to plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis.
extent : This parameter is the limits of the bins.
Returns: This returns the following: 
polycollection : This returns the PolyCollection defining the hexagonal bins.
Below examples illustrate the matplotlib.pyplot.hexbin() function in matplotlib.pyplot:  
Example 1: 
Python3
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np     np.random.seed(19680801)     n = 100000x = np.random.standard_normal(n) y = 12 * np.random.standard_normal(n)      plt.hexbin(x, y, gridsize = 50, cmap ='Greens') plt.title('matplotlib.pyplot.hexbin() Example') plt.show() 
Output:  
Example 2: 
Python3
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np     np.random.seed(19680801)     n = 100000x = np.random.standard_normal(n) y = 2 * np.random.standard_normal(n) z =[1, 2, 3, 4] xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max()     hb = plt.hexbin(x, y, gridsize = 50,                bins = z, cmap ='BuGn')     plt.xlim(xmin, xmax)plt.ylim(ymin, ymax)    cb = plt.colorbar(hb) cb.set_label(z)plt.title('matplotlib.pyplot.hexbin()\Example')  plt.show()
Output:  
 
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Tryit Editor v3.7

Tryit: Events sent form the server
C Program for Binary Search (Recursive and Iterative)?

The binary search algorithm is an algorithm that is based on compare and split mechanism. The binary Search algorithm is also known as half-interval search, logarithmic search, or binary chop. The binary search algorithm, search the position of the target value in a sorted array. It compares the target value with the middle element of the array. If the element is equal to the target element then the algorithm returns the index of the found element. And if they are not equal, the searching algorithm uses a half section of that array, Based on the comparison of the value, the algorithm uses either of the first-half ( when the value is less than the middle ) and the second half ( when the value is greater than the middle ). And does the same for the next array half.
Input:
A[] = {0,2,6,11,12,18,34,45,55,99}
n=55
Output:
55 at Index = 8
For our array -
We will compare 55, with the middle element of the array which is 18, which is less than 55 so we will use second-half of the array i.e. the array {24, 45, 55, 99}, again the middle is 55. Check the value of search element with it. And the value matched, then we will return the index of this value with is 8.
If the search element would be smaller than the middle than we would have used the first-half and go on until the element is found at the middle of the array.
To Implement the binary search we can write the code in two ways. these two ways defer in only the way we call the function that checks for the binary search element. they are:
Using iterations− this means using a loop inside the function that checks for the equality of the middle element.
Using iterations− this means using a loop inside the function that checks for the equality of the middle element.
Using In this method, the function calls itself again and again with a different set of values.
Using In this method, the function calls itself again and again with a different set of values.
#include<stdio.h>
int iterativeBsearch(int A[], int size, int element);
int main() {
   int A[] = {0,12,6,12,12,18,34,45,55,99};
   int n=55;
   printf("%d is found at Index %d \n",n,iterativeBsearch(A,10,n));
   return 0;
}
int iterativeBsearch(int A[], int size, int element) {
   int start = 0;
   int end = size-1;
   while(start<=end) {
      int mid = (start+end)/2;
      if( A[mid] == element) {
         return mid;
      } else if( element < A[mid] ) {
         end = mid-1;
      } else {
         start = mid+1;
      }
   }
   return -1;
}
55 is found at Index 8
#include<stdio.h>
int RecursiveBsearch(int A[], int start, int end, int element) {
   if(start>end) return -1;
      int mid = (start+end)/2;
   if( A[mid] == element ) return mid;
   else if( element < A[mid] )
      RecursiveBsearch(A, start, mid-1, element);
   else
      RecursiveBsearch(A, mid+1, end, element);
}
int main() {
   int A[] = {0,2,6,11,12,18,34,45,55,99};
   int n=55;
   printf("%d is found at Index %d \n",n,RecursiveBsearch(A,0,9,n));
   return 0;
}
55 is found at Index 8
Update all the fields in a table with null or non-null values with MySQL

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,NULL);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values(NULL,'David');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(NULL,NULL);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output−
+------+-------+
|   Id | Name  |
+------+-------+
|   10 | NULL  |
| NULL | David |
| NULL | NULL  |
+------+-------+
3 rows in set (0.00 sec)
Here is the query to update all the fields in a table with null or non-null values −
mysql> update DemoTable set Name='Robert' where Id IS NULL or Name IS NULL;
Query OK, 3 rows affected (0.22 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable;
This will produce the following output −
+------+--------+
|   Id | Name   |
+------+--------+
|   10 | Robert |
| NULL | Robert |
| NULL | Robert |
+------+--------+
3 rows in set (0.00 sec)
SAS - Date & Times

IN SAS dates are a special case of numeric values. Each day is assigned a specific numeric value starting from 1st January 1960. This date is assigned the date value 0 and the next date has a date value of 1 and so on. The previous days to this date are represented by -1 , -2 and so on. With this approach SAS can represent any date in future and any date in past.
When SAS reads the data from a source it converts the data read into a specific date format as specified the date format. The variable to store the date value is declared with the proper informat required. The output date is shown by using the output data formats.
The source data can be read properly by using specific date informats as shown below. The digit at the end of the informat indicates the minimum width of the date string to be read completely using the informat. A smaller width will give incorrect result. with SAS V9, there is a generic date format anydtdte15. which can process any date input.
The below code shows the reading of different date formats. Please note the all the output values are just numbers as we have not applied any format statement to the output values.
DATA TEMP;
INPUT @1 Date1 date11. @12 Date2 anydtdte15. @23 Date3 mmddyy10.   ;
DATALINES;
02-mar-2012 3/02/2012 3/02/2012
;
PROC PRINT DATA = TEMP;
RUN;

When the above code is executed, we get the following output.
The dates after being read , can be converted to another format as required by the display. This is achieved using the format statement for the date types. They take the same formats as informats.
In the below exampel the date is read in one format but displayed in another format.
DATA TEMP;
INPUT  @1 DOJ1 mmddyy10. @12 DOJ2 mmddyy10.;
format  DOJ1 date11.  DOJ2 worddate20. ;
DATALINES;
01/12/2012 02/11/1998 
;
PROC PRINT DATA = TEMP;
RUN;

When the above code is executed, we get the following output.

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page