code-rag-bench/online-tutorials huggingface dataset:
Average of odd numbers till a given odd number?

The average of odd numbers till a given odd number is a simple concept. You just need to find odd numbers till that number then take their sum and divide by the number.
If average of odd number till n is to be found. Then we will find odd numbers from 1 to n add then divide it by the number of odd number.
Average of odd number till 9 is 5 i.e.
1 + 3 + 5 + 7 + 9 = 25 => 25/5 = 5
There are two methods for calculating the average of odd number till n which is an odd
number.
Using Loops
Using Formula
To calculate the average of odd numbers till n, we will add all numbers till n and then divide in by the number of odd number till than.
Program to calculate the average of odd natural numbers till n −
 Live Demo
#include <stdio.h>
int main() {
   int n = 15,count = 0;
   float sum = 0;
   for (int i = 1; i <= n; i++) {
      if(i%2 != 0) {
         sum = sum + i;
         count++;
      }
   }
   float average = sum/count;
   printf("The average of odd numbers till %d is %f",n, average);
   return 0;
}
The average of odd numbers till 15 is 8.000000
To calculate the average of odd numbers till n we can use a mathematical formula
(n+1)/2 where n is an odd number which is the given condition in our problem.
Program to calculate the average of odd natural numbers till n −
 Live Demo
#include <stdio.h>
int main() {
   int n = 15;
   float average = (n+1)/2;
   printf("The average of odd numbers till %d is %f",n, average);
   return 0;
}
The average of odd numbers till 15 is 8.000000
Redis - Keys Command

Redis KEYS command is used to search keys with a matching pattern.
List of keys with a matching pattern (Array).
Following is the basic syntax of Redis KEYS command.
redis 127.0.0.1:6379> KEYS PATTERN

First, create a key in Redis and set some value in it.
redis 127.0.0.1:6379> SET tutorial1 redis 
OK 
redis 127.0.0.1:6379> SET tutorial2 mysql 
OK 
redis 127.0.0.1:6379> SET tutorial3 mongodb 
OK 

Now, search Redis with keys starting from the keyword tutorial.
redis 127.0.0.1:6379> KEYS tutorial* 
1) "tutorial3" 
2) "tutorial1" 
3) "tutorial2" 

To get a list of all the keys available in Redis, use only *
redis 127.0.0.1:6379> KEYS * 
1) "tutorial3" 
2) "tutorial1" 
3) "tutorial2" 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Deletion from a Max Heap in Data Structure

Here we will see how to delete elements from binary max heap data structures. Suppose the initial tree is like below −
delete(heap, n) −
Begin
   if heap is empty, then exit
   else
      item := heap[1]
      last := heap[n]
      n := n – 1
      for i := 1, j := 2, j <= n, set i := j and j := j * 2, do
         if j < n, then
            if heap[j] < heap[j + 1], then j := j + 1
         end if
         if last >= heap[j], then break
         heap[i] := heap[j]
      done
   end if
   heap[i] := last
End
Suppose we want to delete 30 from the final heap −
Frequency plot in Python/Pandas DataFrame using Matplotlib

To show a frequency plot in Python/Pandas dataframe using Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Make a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Return a Series containing the counts of unique values.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

df = pd.DataFrame({'numbers': [2, 4, 1, 4, 3, 2, 1, 3, 2, 4]})
df['numbers'].value_counts().plot(ax=ax, kind='bar', xlabel='numbers', ylabel='frequency')

plt.show()
Tcl - For Loops

A for loop is a repetition control structure that allows you to efficiently write a code that needs to be executed for a specific number of times.
The syntax of a for loop in Tcl language is −
for {initialization} {condition} {increment} {
   statement(s);
}

Here is the flow of control in a for loop −
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
#!/usr/bin/tclsh

# for loop execution
for { set a 10}  {$a < 20} {incr a} {
   puts "value of a: $a"
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
How to unsplit a split in R data frame?

To unsplit a split in R data frame, we can follow the below steps −
First of all, create a data frame.
First of all, create a data frame.
Then, use split function to split the data frame.
Then, use split function to split the data frame.
After that, use do.call function along with rbind function unsplit the data frame.
After that, use do.call function along with rbind function unsplit the data frame.
Let’s create a data frame as shown below −
x<-rpois(25,5)
y<-rpois(25,5)
z<-rpois(25,5)
df<-data.frame(x,y,z)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
   x y z
1  4 3 3
2  5 2 3
3  5 6 3
4  9 2 5
5  8 5 5
6  3 6 5
7  6 3 4
8  2 2 5
9  2 6 4
10 6 6 4
11 2 9 5
12 4 11 4
13 5 3 5
14 6 4 6
15 3 6 4
16 4 6 5
17 6 2 8
18 3 6 5
19 5 7 6
20 2 5 3
21 3 8 5
22 7 5 6
23 1 6 3
24 7 3 6
25 4 3 5
Split the data frame
Using split function to split the data frame −
x<-rpois(25,5)
y<-rpois(25,5)
z<-rpois(25,5)
df<-data.frame(x,y,z)
new_df<-split(df,df$x)
new_df
$ `2`
   x y z
12 2 4 6

$`3`
   x y z
14 3 6 4
15 3 5 5
21 3 6 5

$`4`
    x  y z
 2  4 10 6
 4  4  7 3
 7  4  7 7
 8  4  2 3
11  4  4 4
13  4  3 4
16  4  3 4
19  4  2 2
23  4  3 6

$`5`
   x y z
1  5 3 4
25 5 9 3

$`6`
  x y z
5 6 7 0
6 6 1 8

$`7`
    x y z
3  7 7 1
9  7 3 0
18 7 2 4
22 7 9 4
24 7 9 2

$`8`
   x y z
10 8 3 4

$`9`
   x y z
20 9 2 2

$`10`
    x y z
17 10 7 9
Unsplit the data frame
Using do.call function along with rbind function unsplit the data frame df −
x<-rpois(25,5)
y<-rpois(25,5)
z<-rpois(25,5)
df<-data.frame(x,y,z)
new_df<-split(df,df$x)
do.call("rbind",new_df)
      x y z
2.13  2 7 6
2.24  2 9 5
3.5   3 2 5
3.9   3 7 2
3.11  3 3 2
3.19  3 3 8
3.20  3 5 3
4.2   4 2 4
4.3   4 3 6
4.4   4 4 1
4.25  4 8 6
5.7   5 2 5
5.8   5 4 8
5.14  5 4 5
5.15  5 4 4
5.21  5 9 2
6.1   6 8 5
6.17  6 6 5
6.18  6 2 4
7     7 8 3
8.10  8 5 4
8.16  8 6 6
9.12  9 3 4
9.22  9 4 6
9.23  9 8 5
Implement IsNumber() function in Python

06 May, 2021
In this article we will see how to implement isNumber() method using Python. This method takes in a string as input and returns True or False according to whether the string is a number or not. Examples:  
Input :  "12345"
Output :  True

Input : "-12345" 
Output : True 

Input : "abc"
Output : False
Approach : Here we will take advantage of the int() built-in function available in Python. Also with this approach we will see how Exception Handling comes to our aid. Using try-catch construct we try to convert the string to integer. In case the string cannot be converted the handler catches the exception that is thrown.Below is the Implementation:  
Python3
# Implementation of isNumber() functiondef isNumber(s):         # handle for negative values    negative = False    if(s[0] =='-'):        negative = True             if negative == True:        s = s[1:]         # try to convert the string to int    try:        n = int(s)        return True    # catch exception if cannot be converted    except ValueError:        return False              s1 = "9748513"s2 = "-9748513"s3 = "GeeksforGeeks" print("For input '{}' isNumber() returned : {}".format(s1, isNumber(s1)))print("For input '{}' isNumber() returned : {}".format(s2, isNumber(s2)))print("For input '{}' isNumber() returned : {}".format(s3, isNumber(s3)))
Output :  
For input '9748513' isNumber() returned : True
For input '-9748513' isNumber() returned : True
For input 'GeeksforGeeks' isNumber() returned : False
Note : This is not the only way to implement the isNumber() function but it is arguably the fastest way of doing so. Try/Catch doesn’t introduce much overhead because the most common exception is caught without an extensive search of stack frames. 
arorakashish0911
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Python nested IF statements

There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if  construct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
The syntax of the nested if...elif...else construct may be −
if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   elif expression4:
      statement(s)
   else:
      statement(s)
else:
   statement(s)

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
When the above code is executed, it produces following result −
Expression value is less than 200
Which is 100
Good bye!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
D3.js Array.from() Method - GeeksforGeeks

14 Sep, 2020
With the help of Array.from() method, we can convert the map into an array by using this method.
Syntax :
Array.from( map )
Return value: It returns an array of different elements.
Note: To execute the below examples you have to install the d3 library by using the command prompt we have to execute the following command.
npm install d3
Example 1: In this example we can see that by using Array.from() method, we are able to get the array from map after conversion.
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC",   amount: "34.0",   date: "11/12/2015"},  {name: "DEF",  amount: "120.11", date: "11/12/2015"},  {name: "MNO", amount: "12.01",  date: "01/04/2016"},  {name: "XYZ", amount: "34.05",  date: "01/04/2016"}]var gfg = d3.group(data, d => d.name);  console.log(Array.from(gfg));
Output:
  [ [ 'ABC', [ [Object] ] ],
  [ 'DEF', [ [Object] ] ],
  [ 'MNO', [ [Object] ] ],
  [ 'XYZ', [ [Object] ] ] ]

Example 2:
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC",   amount: "34.0",   date: "11/12/2019"},  {name: "DEF",  amount: "120.11", date: "11/02/2020"},  {name: "MNO", amount: "12.01",  date: "01/04/2020"},  {name: "XYZ", amount: "34.05",  date: "03/04/2020"}]  var gfg = d3.group(data, d => d.name, d => d.date);console.log(Array.from(gfg));
Output:
[ [ 'ABC', Map { '11/12/2019' => [Array] } ],
  [ 'DEF', Map { '11/02/2020' => [Array] } ],
  [ 'MNO', Map { '01/04/2020' => [Array] } ],
  [ 'XYZ', Map { '03/04/2020' => [Array] } ] ]

D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert.ToDateTime Method in C#

The Convert.ToDateTime method converts a given value to a DateTime value.
The following is my string.
string myDateString;
myDateString = "09/09/2018";
Now, let us convert it using the Convert.ToDateTime() method.
DateTime result;
result = Convert.ToDateTime(myDateString);
Here is the complete example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string myDateString;
      DateTime result;
      myDateString = "09/09/2018";
      result = Convert.ToDateTime(myDateString);
      Console.WriteLine("'{0}' converted to {1}", myDateString, result);
   }
}
'09/09/2018' converted to 9/9/2018 12:00:00 AM
How to set the X-axis labels in histogram using ggplot2 at the center in R?

The boundary argument of geom_histogram function and breaks argument of scale_x_continuous function can help us to set the X-axis labels in histogram using ggplot2 at the center. We need to be careful about choosing the boundary and breaks depending on the scale of the X-axis values. Check out the below example to understand how it works.
Consider the below data frame −
Live Demo
> x<-rpois(20,5)
> df<-data.frame(x)
> df
x
1 5
2 7
3 6
4 4
5 7
6 7
7 10
8 3
9 6
10 6
11 5
12 4
13 4
14 6
15 7
16 4
17 1
18 11
19 6
20 9
Loading ggplot2 package and creating the histogram −
> library(ggplot2)
> ggplot(df,aes(x))+ geom_histogram(binwidth=1)
Creating the histogram with X-axis labels at the center −
>ggplot(df,aes(x))+geom_histogram(binwidth=1,boundary=-0.5)+ scale_x_continuous(breaks=1:11)
Java Program to set Horizontal Alignment of content in a JTextField

The content in the JTextFile is by default left aligned, but you can change it using the setHorizontalAlignment() method. Let’s say the following is our JTextField −
JTextField emailId = new JTextField(20);
Now, we will set the horizontal alignment and set the alignment to the right for the JTextPane −
emailId.setHorizontalAlignment(JTextField.RIGHT);
The following is an example to set horizontal alignment of content in a JTextField −
package my;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("Email-Id : ", SwingConstants.LEFT);
      JTextField emailId = new JTextField(20);
      emailId.setHorizontalAlignment(JTextField.RIGHT);
      frame.add(label);
      frame.add(emailId);
      frame.setSize(550,250);
      frame.setVisible(true);
   }
}
Python | Append K character N times

23 Jan, 2020
Sometimes, we wish to manipulate a string in such a way in which we might need to add additional K at the end of string in case of filling the missing bits or any other specific requirement. The solution to this kind of problems is always handy and is good if one has knowledge of it. Let’s discuss certain ways in which this can be solved.
Method #1 : Using ljust()This task can be performed using the simple inbuilt string function of ljust in which we just need to pass N times required and the element to right pad, in this case being K.
# Python3 code to demonstrate# Append K character N times# using ljust()  # initializing string test_string = 'GFG'  # printing original string print("The original string : " + str(test_string))  # initializing K K = 'M'  # No. of K requiredN = 5  # using ljust()# Append K character N timesres = test_string.ljust(N + len(test_string), K)  # print resultprint("The string after adding trailing K : " + str(res))
The original string : GFG
The string after adding trailing K : GFGMMMMM

 
Method #2 : Using format()String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case right.
# Python3 code to demonstrate# Append K character N times# using format()  # initializing string test_string = 'GFG'  # printing original string print("The original string : " + str(test_string))  # initializing K K = '0'  # No. of zeros requiredN = 5  # using format()# Append K character N timestemp = '{:<' + K + str(len(test_string) + N) + '}'res = temp.format(test_string)  # print resultprint("The string after adding trailing K : " + str(res))
The original string : GFG
The string after adding trailing K : GFG00000

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python | Pandas Series.str.cat() to concatenate string

05 Oct, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.cat() is used to concatenate strings to the passed caller series of string. Distinct values from a different series can be passed but the length of both the series has to be same. .str has to be prefixed to differentiate it from the Python’s default method. 
Syntax: Series.str.cat(others=None, sep=None, na_rep=None)Parameters: others: Series, index, data frame or list of strings to concatenate sep: Separator to be put between the two strings na_rep: None or string value to replace in place of null valuesReturn type: Series with concatenated string values  
To download the Csv file used, click here.In the following examples, the data frame used contains data on some NBA players. The image of data frame before any operations is attached below.  
  Example #1: Concatenating column with separatorIn this example, the Team column is concatenated at the end of Name column with separator “, “. The Name column is overwritten with the new series and the data frame is then displayed.  
Python3
# importing pandas moduleimport pandas as pd # importing csv from linkdata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # making copy of team columnnew = data["Team"].copy() # concatenating team with name column# overwriting name columndata["Name"]= data["Name"].str.cat(new, sep =", ") # displaydata
Output: As shown in the output image, every string in the Team column having same index as string in Name column have been concatenated with separator “, “.  
  Example #2: Handling Null valuesThe most important part in analyzing data is handling null values. str.cat() provides a way to handle null values through na_rep parameter. Whatever is passed to this parameter will be replaced at every occurrence of null value. In this example, college column is concatenated with team column. “No college” is passed to na_rep parameter to replace null with this string. 
Python3
# importing pandas moduleimport pandas as pd # importing csv from linkdata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # making copy of team columnnew = data["Team"].copy() # string to replace null values withna_string ="No College" # concatenating team with name column# overwriting name columndata["College"]= data["College"].str.cat(new, sep =", ", na_rep = na_string) # displaydata
Output: As it can be seen in the data frame, at index position 4 and 5, there was NULL value which has been replaced with “No College” and the string from Team column have been concatenated successfully.  
 
prachisoda1234
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MoviePy – Getting frame from Video File Clip

30 Aug, 2020
In this article we will see how we can get the frame at given time from the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Combination of frames make the video, at each time there exist a specific frame which is similar to normal image.Getting frame means to get a numpy array representing the RGB picture of the clip at time t or (mono or stereo) value for a sound clip.
In order to do this we will use get_frame method with the VideoFileClip object
Syntax : clip.get_frame(n)
Argument : It takes float value as argument
Return : It returns numpy ndarray
Below is the implementation
# importing matplotlibfrom matplotlib import pyplot as plt  # importing numpyimport numpy as np  # Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")  # getting only first 5 secondsclip = clip.subclip(0, 5)    # getting only first 5 seconds clip = clip.subclip(0, 5)   # getting frame at time 3frame = clip.get_frame(3)  # showing the frame with the help of matplotlibplt.imshow(frame, interpolation ='nearest')  # showplt.show()
Output :
Another example
# importing matplotlibfrom matplotlib import pyplot as plt  # importing numpyimport numpy as np  # Import everything needed to edit video clips from moviepy.editor import *    # loading video dsa gfg intro video clip = VideoFileClip("dsa_geek.mp4")      # getting only first 5 secondsclip = clip.subclip(0, 5)    # getting frame at time 2frame = clip.get_frame(2)  # showing the frame with the help of matplotlibplt.imshow(frame, interpolation ='nearest')  # showplt.show()
Output :
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Python | Check if all values in numpy are zero

10 Jan, 2022
Given a numpy array, the task is to check whether the numpy array contains all zeroes or not. Let’s discuss few ways to solve the above task.
Method #1: Getting count of Zeros using numpy.count_nonzero()
Python3
# Python code to demonstrate# to count the number of elements# in numpy which are zero  import numpy as np  ini_array1 = np.array([1, 2, 3, 4, 5, 6, 0])ini_array2 = np.array([0, 0, 0, 0, 0, 0])  # printing initial arraysprint("initial arrays", ini_array1)print(ini_array2)  # code to find whether all elements are zerocountzero_in1 = np.count_nonzero(ini_array1)countzero_in2 = np.count_nonzero(ini_array2)  # printing resultprint("Number of non-zeroes in array1 : ", countzero_in1)print("Number of non-zeroes in array2 : ", countzero_in2)
initial arrays [1 2 3 4 5 6 0]
[0 0 0 0 0 0]
Number of non-zeroes in array1 :  6
Number of non-zeroes in array2 :  0

 Method #2: Using numpy.any()
Python3
# Python code to check that whether# all elements in numpy are zero  import numpy as np  ini_array1 = np.array([1, 2, 3, 4, 5, 6, 0])ini_array2 = np.array([0, 0, 0, 0, 0, 0])  # printing initial arraysprint("initial arrays", ini_array1)  # code to find whether all elements are zerocountzero_in1 = not np.any(ini_array1)countzero_in2 = not np.any(ini_array2)  # printing resultprint("Whole array contains zeroes in array1 ?: ", countzero_in1)print("Whole array contains zeroes in array2 ?: ", countzero_in2)
initial arrays [1 2 3 4 5 6 0]
Whole array contains zeroes in array1 ?:  False
Whole array contains zeroes in array2 ?:  True

prachisoda1234
Python numpy-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
How to create an area inside an image-map using HTML5 ?

08 Jun, 2021
The approach of this article is to create an area inside an image-map by using a <area> tag in a HTML Document. It is used to direct the user to different links after the user clicks on the mapped portions of the image. It is used as a child tag of the <map> tag. It has no closing tag and hence it is an empty tag for HTML but incase of XHTML you need to close that properly. HTML5 has some new attributes.
Syntax:
<area> Contents </area> 
Example:  
html
<!DOCTYPE html><html> <body style="text-align: center">    <h2 style="color: green;">        GeeksForGeeks    </h2>    <h2>        How to create an area inside        an image-map using HTML5?    </h2>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190227165729/area11.png"        alt="" width="300" height="119"        class="aligncenter size-medium        wp-image-910965" usemap="#shapemap" />     <map name="shapemap">         <!-- Area tag contained image. -->        <area shape="poly"            coords="59, 31, 28, 83, 91, 83"            href="https://media.geeksforgeeks.org/wp-content/uploads/20190227165802/area2.png"            alt="Triangle">         <area shape="circle"            coords="155, 56, 26"            href="https://media.geeksforgeeks.org/wp-content/uploads/20190227165934/area3.png"            alt="Circle">         <area shape="rect"            coords="224, 30, 276, 82"            href="https://media.geeksforgeeks.org/wp-content/uploads/20190227170021/area4.png"            alt="Square">    </map></body> </html>
Output:
Before click on specific clickable area:
After click on specific clickable area: 
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
hritikbhatnagar2182
HTML-Misc
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Mathematical Functions in Python | Set 1 (Numeric Functions)

27 May, 2017
In python a number of mathematical operations can be performed with ease by importing a module named “math” which defines various functions which makes our tasks easier.
1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned.
2. floor() :- This function returns the greatest integral value smaller than the number. If number is already integer, same number is returned.
# Python code to demonstrate the working of# ceil() and floor()  # importing "math" for mathematical operationsimport math  a = 2.3  # returning the ceil of 2.3print ("The ceil of 2.3 is : ", end="")print (math.ceil(a))  # returning the floor of 2.3print ("The floor of 2.3 is : ", end="")print (math.floor(a))
Output:
The ceil of 2.3 is : 3
The floor of 2.3 is : 2

3. fabs() :- This function returns the absolute value of the number.
4. factorial() :- This function returns the factorial of the number. An error message is displayed if number is not integral.
# Python code to demonstrate the working of# fabs() and factorial()  # importing "math" for mathematical operationsimport math  a = -10  b= 5  # returning the absolute value.print ("The absolute value of -10 is : ", end="")print (math.fabs(a))  # returning the factorial of 5print ("The factorial of 5 is : ", end="")print (math.factorial(b))
Output:
The absolute value of -10 is : 10.0
The factorial of 5 is : 120

5. copysign(a, b) :- This function returns the number with the value of ‘a’ but with the sign of ‘b’. The returned value is float type.
6. gcd() :- This function is used to compute the greatest common divisor of 2 numbers mentioned in its arguments. This function works in python 3.5 and above.
# Python code to demonstrate the working of# copysign() and gcd()  # importing "math" for mathematical operationsimport math  a = -10b = 5.5c = 15d = 5  # returning the copysigned value.print ("The copysigned value of -10 and 5.5 is : ", end="")print (math.copysign(5.5, -10))  # returning the gcd of 15 and 5print ("The gcd of 5 and 15 is : ", end="")print (math.gcd(5,15))
Output:
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5

This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Inheritance in C++
Scala vs Java

25 Jan, 2019
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java applications are compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.
Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express the general programming patterns in a refined, succinct, and type-safe way.
Below are some major differences between Scala and Java:
Java 8
java-basics
Scala
Scala-Basics
Java
Scala
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Random sampling in numpy | sample() function

26 Feb, 2019
numpy.random.sample() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0).
Syntax : numpy.random.sample(size=None)
Parameters :size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
Return : Array of random floats in the interval [0.0, 1.0). or a single such random float if size not provided.
Code #1 :
# Python program explaining# numpy.random.sample() function  # importing numpyimport numpy as geek  # output random valueout_val = geek.random.sample()print ("Output random value : ", out_val) 
Output random value :  0.9261509680895836

 
Code #2 :
# Python program explaining# numpy.random.sample() function  # importing numpyimport numpy as geek    # output arrayout_arr = geek.random.sample(size =(3, 3))print ("Output 2D Array filled with random floats : ", out_arr) 
Output 2D Array filled with random floats :  [[ 0.75908777  0.88295677  0.60979136]
 [ 0.68157065  0.75100312  0.08321613]
 [ 0.8360331   0.64808891  0.14731635]]

 Code #3 :
# Python program explaining# numpy.random.sample() function  # importing numpyimport numpy as geek  # output arrayout_arr = geek.random.sample((2, 2, 3))print ("Output 3D Array filled with random floats : ", out_arr) 
Output 3D Array filled with random floats :  [[[ 0.3073475   0.75709465  0.86934712]
  [ 0.21953745  0.48138292  0.30686482]]

 [[ 0.48925625  0.60222083  0.14403257]
  [ 0.87030919  0.87298872  0.2222136 ]]]

Python numpy-Random sampling
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JSON format in Cassandra

09 Dec, 2019
In this article, we will discuss JSON JavaScript Object Notation format to insert data into the table and it is useful and inserting columns and its values programmatically are more practical than using cqlsh. For testing and verifying queries cqlsh is very convenient.
Cassandra Query Language (CQL) supported JSON format in which data is inserted as a string but in actual is stored as a given data type value.
For example, if Id has int data type then the value of id will be inserted like “Id”: “101” but in actual it will be stored as an INT. Let’s consider a table student_registration in which s_id, s_name, s_city, s_email are the fields.
CREATE TABLE student_registration(
s_id int PRIMARY KEY, 
s_name text, 
s_city text, 
s_email text
); 
Now, here we will insert data into the student_registration table in JSON format. Let’s have a look.
INSERT INTO student_registration
JSON '{
"s_id" : "9001",
"s_name" : "Ashish",
"s_city" : "California",
"s_email": "a_json1@gmail.com"
}';


INSERT INTO student_registration
JSON '{
"s_id" : "9002",
"s_name" : "Ashish",
"s_email": "a_json1@gmail.com"
}' ;

INSERT INTO student_registration
JSON '{
"s_id" : "9003",
"s_name" : "Rana",
"s_email": "a_json2@gmail.com"
}' ; 
Let’s see the output using the following CQL query.
select * 
from student_registration; 
Output:
Here, s_city value is not inserted using JSON so, it is by default NULL value will be inserted.
nested JSON:Let’s understand with an example for nested JSON first we are creating user defined type permanent_address which has house_no, name, city, pin are the field.
CREATE type permanent_address
( 
house_no int, 
name text, 
city text,
pin int 
); 
Now, here we are creating registration_form table for registration purpose which has student_id, name, registration_fees, and permanent_address are the fields.
CREATE TABLE registration_form( 
"student_id" int  PRIMARY KEY, 
"name" text, 
"registration_fees" int, 
"permanent_address" list<frozen>); 
Now, here to insert data into table used the following CQL query.
INSERT INTO registration_form("student_id", "name",  
                                   "registration_fees", 
                                   "permanent_address") 
VALUES (123, 'Ashish', 2500, 
 [{ house_no : 544, name : 'ashish', city : 'california', pin : 2019 },
  { house_no : 124, name : 'rana', city : 'delhi', pin : 2020}]) ; 
Let’s see the inserted data by using the following CQL query.
select * 
from registration_form; 
Output:
toJson() is JSON function to convert a JSON string. Let’s have a look.
 select student_id, toJson(permanent_address) 
from registration_form; 
Output:
Reference – DataStax
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Draw Rectangle on Image in Matplotlib? - GeeksforGeeks

17 Dec, 2020
Prerequisites: Matplotlib
Given an image the task here is to draft a python program using matplotlib to draw a rectangle on it. Matplotlib comes handy with rectangle() function which can be used for our requirement.
Syntax: Rectangle(xy, width, height, angle=0.0, **kwargs)
Parameters:
xy: Lower left point to start the rectangle plotting
width : width of the rectangle
height: Height of the rectangle.
angle: Angle of rotation of the rectangle.
Import the necessary libraries. 
Insert and display the image.
Create the figure and axes of the plot 
Add the patch to the Axes
Display the image
Example 1: Draw a rectangle on an image
Python3
import matplotlib.pyplot as pltimport matplotlib.patches as patchesfrom PIL import Imageimport numpy as np  x = np.array(Image.open('geek.png'), dtype=np.uint8)plt.imshow(x)  # Create figure and axesfig, ax = plt.subplots(1)  # Display the imageax.imshow(x)  # Create a Rectangle patchrect = patches.Rectangle((50, 100), 40, 30, linewidth=1,                         edgecolor='r', facecolor="none")  # Add the patch to the Axesax.add_patch(rect)plt.show()
Output:
original image
image with rectangle
Example 2: Draw a filled rectangle
Python3
import matplotlib.pyplot as pltimport matplotlib.patches as patchesfrom PIL import Imageimport numpy as np  x = np.array(Image.open('geek.png'), dtype=np.uint8)plt.imshow(x)  # Create figure and axesfig, ax = plt.subplots(1)  # Display the imageax.imshow(x)  # Create a Rectangle patchrect = patches.Rectangle((50, 100), 40, 30, linewidth=1,                         edgecolor='r', facecolor="g")  # Add the patch to the Axesax.add_patch(rect)plt.show()
Output:
original image
image with rectangle
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Read a file line by line in Python
Taking input in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to get focused element using jQuery? - GeeksforGeeks

16 Oct, 2019
To focus on element there is an inbuilt selector available in jQuery, which is used to detect the currently focused element. When the element is get focused by the mouse click or by the tab-navigating button this selector return the selected element. You can add the element in JQuery to focused that element easily. Here we will use the JQuery inbuilt selector $(“:focus”)
Syntax:
$(":focus")
Example 1: This example shows how to focus an element using jQuery.
<!DOCTYPE html><html>  <head>    <title>        How to get focused element        using jQuery?    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">    </script>          <script>        $(document).ready(function() {            $("input").focus();            $(":focus").css("background-color", "yellow");        });    </script>          <style>        .geeks {            width: 350px;            height: 100px;            border: 2px solid green;            padding-bottom: 15px;            margin: 10px;        }        h1 {            color:green;        }    </style></head>  <body>    <center>        <div class="geeks">            <h1>GeeksforGeeks</h1>            <input type="text" placeholder="Focused Input" />        </div>    </center></body>  </html>                    
Output:
Example 2:
<!DOCTYPE html><html>    <head>    <title>        How to get focused element        using jQuery?    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">    </script>          <script>        $(document).ready(function(){            $("input").focus();            $(":focus").css("background-color", "red");            $("button").focus();            $(":focus").css("background-color", "green");        });    </script>          <style>         .geeks {            width: 350px;            height: 100px;            border: 2px solid green;            padding-bottom: 15px;            margin: 10px;        }        h1 {            color:green;        }    </style></head>    <body>    <center>        <div class="geeks">            <h1>GeeksforGeeks</h1>            <input type="text" placeholder="Focused Input" />            <button type="button" >                <a href="https://ide.geeksforgeeks.org/tryit.php">                    Click me visit ide                </a>            </button>        </div>    </center></body>    </html>
Output:
nidhi_biet
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to Show and Hide div elements using radio buttons?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to handle frames in Selenium?

We can handle frames in Selenium with the help of following methods −
switchTo().frame( frameNumber)This method uses the frame id as the parameter. The index of frame id starts from 0. NoSuchFrameException is thrown if the frame is not found.
switchTo().frame( frameNumber)
This method uses the frame id as the parameter. The index of frame id starts from 0. NoSuchFrameException is thrown if the frame is not found.
switchTo().frame( frameName)This method uses the frame name as defined by the developer as the parameter. The frame name is considered a String and is enclosed in quotes. NoSuchFrameException is thrown if the frame is not found.
switchTo().frame( frameName)
This method uses the frame name as defined by the developer as the parameter. The frame name is considered a String and is enclosed in quotes. NoSuchFrameException is thrown if the frame is not found.
switchTo().frame( WebElement)This method uses the webelement as the parameter. NoSuchFrameException is thrown if the frame is not found. StaleElementReferenceException if the frame is no longer active.
switchTo().frame( WebElement)
This method uses the webelement as the parameter. NoSuchFrameException is thrown if the frame is not found. StaleElementReferenceException if the frame is no longer active.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FrameSet {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "url with frames";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //grabbing the first frame with the help of index
      driver.switchTo().frame(0);
      //grabbing the frame with the help of frame name
      driver.switchTo().frame(“<<name expression>>“);
      //grabbing the frame with the help of frame webelement
      WebElement name = driver.findElement(By.name(“frame-right”));
      driver.switchTo().frame(driver.findElement(By.name(“<<name expression”)));
      driver.quit();
   }
}
Python OpenCV - getTrackbarPos() Function - GeeksforGeeks

10 Feb, 2022
getTrackbarPos() is Function in Python OpenCV that returns the current position of the specified trackbar. It takes two arguments. The first is for the trackbar name and the second one is the window name which is the parent of the trackbar. Returns the trackbar position.
Syntax : cv.getTrackbarPos(trackbarname, winname)
Parameters :
trackbarname: Name of trackbar
winname: Name of the window that is the parent of the trackbar.
Return : Current position of the specified trackbar
Note: [Only for Qt Backend] Here, If the trackbar is attached to the control panel then winname can be empty or Null.
Below is the implementation:
Python3
# Demo Trackbar# importing cv2 and numpyimport cv2import numpy def nothing(x):    pass # Creating a window with black imageimg = numpy.zeros((300, 512, 3), numpy.uint8)cv2.namedWindow('image') # creating trackbars for red color changecv2.createTrackbar('R', 'image', 0, 255, nothing) # creating trackbars for Green color changecv2.createTrackbar('G', 'image', 0, 255, nothing) # creating trackbars for Blue color changecv2.createTrackbar('B', 'image', 0, 255, nothing) while(True):    # show image    cv2.imshow('image', img)     # for button pressing and changing    k = cv2.waitKey(1) & 0xFF    if k == 27:        break     # get current positions of all Three trackbars    r = cv2.getTrackbarPos('R', 'image')    g = cv2.getTrackbarPos('G', 'image')    b = cv2.getTrackbarPos('B', 'image')     # display color mixture    img[:] = [b, g, r] # close the windowcv2.destroyAllWindows()
Output:
When we move the slider of any of R, G, or B its corresponding getTrackbarPos() values changes and it returns the position of the specific slider. Through which we change the color of the below box. You can see in the code we pass to the argument to getTrackbarPos(). Let’s take r for example, we pass ‘R’ and ‘image’ to function. Here ‘R’ is the Trackbar name that we created and ‘image’ is the name of the window that opens when we run code. Basically, it is the parent window of the trackbar. This returns the position of the slider as an integer value and we save it in r. We create color box with this return value ‘r’, ‘g’ and ‘b’. 
sumitgumber28
Picked
Python-OpenCV
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 | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list