code-rag-bench/online-tutorials huggingface dataset:
How to click on sign up button using Java in Selenium I am able to open page but not able to click?

We can click on the Sign up button using Java in Selenium. First of all, we have to identify the Sign up button with the help of any of the locators like id, class name, name, link text, xpath, css or partial link text. After identification, we have to click on the Sign up the button with the help of the method click.
WebElement m=driver. findElement(By.id("loc-txt"));
m.click();
Code Implementation with click
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class SignIn{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      // identify element with class name then use click method
      WebElement m=driver.
      findElement(By.className("sign-in-form__submit-button"));
      m.click();
      driver.close();
   }
}
Also, we can click on the Sign up button with the help of the sendKeys method and pass Keys.ENTER as a parameter to that method.
WebElement m=driver. findElement(By.id("loc-txt"));
m.sendKeys(Keys.ENTER);
Code Implementation with sendKeys
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class SignInSendKeys{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      // identify element with class name then use sendKeys method
      WebElement m=driver.
      findElement(By.className("sign-in-form__submit-button"));
      m.sendKeys(Keys.ENTER);
      driver.close();
   }
}
Matplotlib.axes.Axes.bar() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.bar() function in axes module of matplotlib library is used to make a bar plot.
Syntax: Axes.bar(self, x, height, width=0.8, bottom=None, *, align=’center’, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the sequence of horizontal coordinates of the bar.
height: This parameter is the height(s) of the bars.
width: This parameter is an optional parameter. And it is the width(s) of the bars with default value 0.8.
bottom: This parameter is also an optional parameter. And it is the y coordinate(s) of the bars bases with default value 0.
alighn: This parameter is also an optional parameter. And it is used for alignment of the bars to the x coordinates.
Returns: This returns the following:
BarContainer:This returns the container with all the bars and optionally errorbars.
Below examples illustrate the matplotlib.axes.Axes.bar() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib function          import matplotlib.pyplot as pltimport numpy as np  data = ((30, 1000), (10, 28), (100, 30),        (500, 800), (50, 10))  dim = len(data[0])w = 0.6dimw = w / dim  fig, ax = plt.subplots()x = np.arange(len(data))for i in range(len(data[0])):    y = [d[i] for d in data]    b = ax.bar(x + i * dimw, y,                dimw,                bottom = 0.001)  ax.set_xticks(x + dimw / 2)ax.set_xticklabels(map(str, x))ax.set_yscale('log')  ax.set_xlabel('x')ax.set_ylabel('y')  ax.set_title('matplotlib.axes.Axes.bar Example')  plt.show()
Output:
Example #2:
# ImpleMinetation of matplotlib function          import numpy as npimport matplotlib.pyplot as plt    labels = ['Month1', 'Month2', 'Month3', 'Month4']mine = [21, 52, 33, 54]others = [54, 23, 32, 41]Mine_std = [2, 3, 4, 1]Others_std = [3, 5, 2, 3]width = 0.3  fig, ax = plt.subplots()  ax.bar(labels, mine, width,        yerr = Mine_std,        label ='Mine')  ax.bar(labels, others, width,        yerr = Others_std,       bottom = mine,       label ='Others')  ax.set_ylabel('Articles')ax.legend()  ax.set_title('matplotlib.axes.Axes.bar Example')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
How to Convert Epoch Time to Date in SQL?

17 Dec, 2021
DATEADD() function in SQL Server is used to sum up a time or a date interval to a specified date then returns the modified date. There are some features of DATEADD() below: 
This function is used to sum up a time or a date interval to a date specified.
This function comes under Date Functions.
This function accepts three parameters namely interval, number, and date.
This function can also include time in the interval section. 
Here we will see, how to convert epoch time to date in SQL Server using the DATEADD() function. For the purpose of demonstration, we will be creating an EpochDB table in a database called “geeks“.
Step 1: Creating the Database
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks:
USE geeks;
Step 3: Table Definition
We have the following EpochDB in our geeks database.
CREATE TABLE EpochDOB (
Id INT,
Person VARCHAR(50), 
Dt BIGINT 
);
Step 4: Adding data to the table
Use the below statement to add data to the EpochDB table:
INSERT INTO EpochDOB VALUES
(1,'Anuj',848698632000),
(2,'Harsh',957532509000),
(3,'Ravi',1547455833000);
Step 5: To verify the contents of the table use the below statement
SELECT * FROM EpochDOB;
Step 6: Result
Because our Epoch time is specified in milliseconds, we may convert it to seconds. To convert milliseconds to seconds, first, divide the millisecond count by 1000. Later, we use DATEADD() to add the number of seconds since the epoch, which is January 1, 1970 and cast the result to retrieve the date since the epoch.
SELECT *, CAST(DATEADD(SECOND, Dt/1000
 ,'1970/1/1') AS DATE) DOBDate
FROM EpochDOB;
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Property binding in angular 8

11 Sep, 2020
Property Binding is a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code. Actually, Angular internally converts string interpolation into property binding.
In this, we bind the property of a defined element to an HTML DOM element.
Syntax:
<element [property]= 'typescript_property'>
Approach:
Define a property element in the app.component.ts file.
In the app.component.html file, set the property of the HTML element by assigning the property value to the app.component.ts file’s element.
Example 1: setting value of an input element using property binding.
app.component.html
<input style = "color:green;                margin-top: 40px;                 margin-left: 100px;" [value]='title'>
app.component.ts
import { Component } from '@angular/core';    @Component({      selector: 'app-root',      templateUrl: './app.component.html',      styleUrls: ['./app.component.css']    })    export class AppComponent {     title = 'GeeksforGeeks'; }
Output:
Example 2: getting source of the image using property binding.
app.component.html
<img [src]='src'>
app.component.ts
import { Component } from '@angular/core';    @Component({      selector: 'app-root',      templateUrl: './app.component.html',      styleUrls: ['./app.component.css']    })    export class AppComponent {     src = 'https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png'; }
Output:
Example 3: disabling a button using property binding.
app.component.html
<button [disabled]='bool' style="margin-top: 20px;">GeekyButton</button>
app.component.ts
import { Component } from '@angular/core';    @Component({      selector: 'app-root',      templateUrl: './app.component.html',      styleUrls: ['./app.component.css']    })    export class AppComponent {     bool = 'true'; }
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for QuickSort

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using the concept of quicksort
Here we first partition the array and sort the separate partition to get the sorted array.
Now let’s observe the solution in the implementation below −
 Live Demo
# divide function
def partition(arr,low,high):
   i = ( low-1 )
   pivot = arr[high] # pivot element
   for j in range(low , high):
      # If current element is smaller
      if arr[j] <= pivot:
         # increment
         i = i+1
         arr[i],arr[j] = arr[j],arr[i]
   arr[i+1],arr[high] = arr[high],arr[i+1]
   return ( i+1 )
# sort
def quickSort(arr,low,high):
   if low < high:
      # index
      pi = partition(arr,low,high)
      # sort the partitions
      quickSort(arr, low, pi-1)
      quickSort(arr, pi+1, high)
# main
arr = [2,5,3,8,6,5,4,7]
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
   print (arr[i],end=" ")
Sorted array is
2 3 4 5 5 6 7 8
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for QuickSort
Python File seek() Method

Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
Following is the syntax for seek() method −
fileObject.seek(offset[, whence])

offset − This is the position of the read/write pointer within the file.
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
This method does not return any value.
The following example shows the usage of seek() method.
Python is a great language
Python is a great language

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print "Read Line: %s" % (line)

# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)

# Close opend file
fo.close()
When we run above program, it produces following result −
Name of the file:  foo.txt
Read Line: Python is a great language.

Read Line: Python is a great language.
PyQt5 QCalendarWidget – Clicked signal

25 Nov, 2021
In this article we will see how we can get the clicked signal from the QCalendarWidget. Clicked signal is emitted when a mouse button is clicked i.e when the mouse was clicked on the specified date. The signal is only emitted when clicked on a valid date, e.g., dates are not outside the minimum date and maximum date. If the selection mode is NoSelection, this signal will not be emitted.
In order to do this we will use clicked method with the QCalendarWidget object.Syntax : calendar.clicked.connect(lambda: print(“Clicked”))Argument : It takes method as argumentAction Performed : It will print the message whenever activated signal get emitted  
Below is the implementation 
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sysclass Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 600, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QCalendarWidget object        calendar = QCalendarWidget(self)         # setting geometry to the calendar        calendar.setGeometry(10, 10, 400, 250)         # creating a label        label = QLabel(self)         # setting geometry to the label        label.setGeometry(100, 280, 250, 60)         # making label multi line        label.setWordWrap(True)         # text        text = "Clicked Signals received (No.) : "         # current count        self.count = 0         # getting the clicked signal and        # when receives the signal printing the message        calendar.clicked.connect(lambda: label.setText(text + str(get_count())))         # method to increase the count value        def get_count():            self.count += 1            return self.count  # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output : 
 
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to insert a line break in PHP string ?

07 Oct, 2021
In this article, we will discuss how to insert a line break in PHP string. We will get it by using nl2br() function. This function is used to give a new line break wherever ‘\n’ is placed.
Syntax:
nl2br("string \n");
where, string is the input string.
Example 1: PHP Program to insert a line break in a string.
PHP
<?php  // Insert a new line breakecho nl2br("This is first line \n This is second line");  ?>
This is first line <br />
 This is second line
Example 2:
PHP
<?php  // Insert a line break with new lineecho nl2br("This is first line \n This is second "   + "line \n This is third line \n This is forth line");  ?>
This is first line <br />
 This is second line <br />
 This is third line <br />
 This is forth line
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Why Does BufferedReader Throw IOException in Java?

30 Aug, 2021
IOException is a type of checked exception which occurs during input/output operation. BufferedReader is used to read data from a file, input stream, database, etc. Below is the simplified steps of how a file is read using a BufferedReader in java.
In RAM a buffered reader object is created.Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM.Now with the help of a buffered reader object our program can read the buffer in RAM.If all the lines are read then next some lines of the file are copied from secondary memory into the buffer.
In RAM a buffered reader object is created.
Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM.
Now with the help of a buffered reader object our program can read the buffer in RAM.
If all the lines are read then next some lines of the file are copied from secondary memory into the buffer.
Buffered Reader Work Flow Overview
This file system reading can fail at any time for many reasons. It may occur due to the file deleted or viruses in the file. Sometimes BufferedReader takes data from a network stream where the reading system can fail at any time.
So this type of error can occur in input operation when a BufferedReader is used. This is why a buffered reader throws IOException.
Below is an example of BufferedReader use
Input: a = 5, b = 3
Output: 8
Implementation:
Java
// This is an example of use of BufferedReader Class import java.io.*; class GFG {     // Define BufferedReader object    static BufferedReader br = new BufferedReader(        new InputStreamReader(System.in));     // If you delete 'throws IOException'    // you will get an error    public static void main(String[] args)        throws IOException    {        int a = Integer.parseInt(br.readLine());        int b = Integer.parseInt(br.readLine());        System.out.println(a + b);    }}
  Output:
If the file is deleted from the server-side while reading the input from the server-side, IOException is thrown.
 
surindertarika1234
adnanirshad158
Java-Exceptions
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
Prime numbers in a range - JavaScript

We are required to write a JavaScript function that takes in two numbers, say, a and b and returns the total number of prime numbers between a and b (including a and b, if they are prime).
For example −
If a = 2, and b = 21, the prime numbers between them are 2, 3, 5, 7, 11, 13, 17, 19
And their count is 8. Our function should return 8.
Let’s write the code for this function −
Following is the code −
const isPrime = num => {
   let count = 2;
   while(count < (num / 2)+1){
      if(num % count !== 0){
         count++;
         continue;
      };
      return false;
   };
   return true;
};
const primeBetween = (a, b) => {
   let count = 0;
   for(let i = Math.min(a, b); i <= Math.max(a, b); i++){
      if(isPrime(i)){
         count++;
      };
   };
   return count;
};
console.log(primeBetween(2, 21));
Following is the output in the console −
8
How to get YouTube video ID with PHP Regex ? - GeeksforGeeks

21 Oct, 2021
YouTube ID is a string of 11 characters, which consists of both upper and lower case alphabets and numeric values. It is used to define a YouTube video uniquely. A link to any YouTube video consists of its YouTube ID in a query format whose variable is generally written as ‘v’ or ‘vi’ or can be represented as ‘youtu.be/’ . Examples of YouTube ID from the link given below:  
https://youtu.be/hjGD08xfg9c
https://www.youtube.com/watch?v=hjGD08xfg9c
https://www.youtube.com/watch?vi=hjGD08xfg9c
https://www.youtube.com/?v=hjGD08xfg9c
https://www.youtube.com/?vi=hjGD08xfg9c
In all these urls’s the string ‘hjGD08xfg9c’ is the YouTube ID. Now using this knowledge, a regular expression can be built for fetching the YouTube ID from a given link in PHP.Regex: Now we know that there are five basic formats in which we can get a YouTube ID i.e. by v= or vi= or v/ or vi/ or youtu.be/. So as the query starts from ‘?’ or ‘yout.be/’, start regex by ‘?’ or look for ‘yout.be/’. It will ignore the URL part before ‘?’ or ‘yout.be/’. After that search for ‘v=’ or ‘vi=’ and store the next 11 characters and print it.According to this logic the regex will be  
preg_match_all("#(?<=v=|v\/|vi=|vi\/|youtu.be\/)[a-zA-Z0-9_-]{11}#", $url, $match);
Example: This example will show the YouTube ID in which input will be the link to YouTube.  
php
<?php$url = 'https://youtu.be/hjGD08xfg9c
Array
(
    [0] => hjGD08xfg9c
    [1] => hjGD08xfg9c
    [2] => hjGD08xfg9c
    [3] => hjGD08xfg9c
    [4] => hjGD08xfg9c
)
 
Alternative: Instead of using regular expression we can access the variable or the query by using two functions that are parse_str() and parse_url(). The parse_str() takes parse_url() and an output variable as parameters and puts all the query values of the url in the output variable. The parse_url() takes the url in string format and an integer value and returns the list of different properties within the url depending on the value of integer passed. Example:  
php
<?php // Store the URL into variable$url = 'https://www.youtube.com/watch?v=hjGD08xfg9c';$url1='https://www.youtube.com/?vi=hjGD08xfg9c'; // Use parse_str() function to parse the query stringparse_str( parse_url( $url, PHP_URL_QUERY ), $youtube_id_v );parse_str( parse_url( $url1, PHP_URL_QUERY ), $youtube_id_vi ); // Display the outputecho $youtube_id_v['v'] . "\n";echo $youtube_id_vi['vi']; ?>
hjGD08xfg9c
hjGD08xfg9c
 
adnanirshad158
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Design and Analysis Insertion Sort

Insertion sort is a very simple method to sort numbers in an ascending or descending order. This method follows the incremental method. It can be compared with the technique how cards are sorted at the time of playing a game.
The numbers, which are needed to be sorted, are known as keys. Here is the algorithm of the insertion sort method.
Algorithm: Insertion-Sort(A) 
for j = 2 to A.length 
   key = A[j] 
   i = j – 1 
   while i > 0 and A[i] > key 
      A[i + 1] = A[i] 
      i = i -1 
   A[i + 1] = key 

Run time of this algorithm is very much dependent on the given input.
If the given numbers are sorted, this algorithm runs in O(n) time. If the given numbers are in reverse order, the algorithm runs in O(n2) time.
Unsorted list:
1st iteration:
Key = a[2] = 13
a[1] = 2 < 13
Swap, no swap
2nd iteration:
Key = a[3] = 5
a[2] = 13 > 5
Swap 5 and 13
Next, a[1] = 2 < 13
Swap, no swap
3rd iteration:
Key = a[4] = 18
a[3] = 13 < 18,
a[2] = 5 < 18,
a[1] = 2 < 18
Swap, no swap
4th iteration:
Key = a[5] = 14
a[4] = 18 > 14
Swap 18 and 14
Next, a[3] = 13 < 14,
a[2] = 5 < 14,
a[1] = 2 < 14
So, no swap
Finally,
the sorted list is

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Redux - Testing

Testing Redux code is easy as we mostly write functions, and most of them are pure. So we can test it without even mocking them. Here, we are using JEST as a testing engine. It works in the node environment and does not access DOM.
We can install JEST with the code given below −
npm install --save-dev jest

With babel, you need to install babel-jest as follows −
npm install --save-dev babel-jest

And configure it to use babel-preset-env features in the .babelrc file as follows −
{ 
   "presets": ["@babel/preset-env"] 
}
And add the following script in your package.json:
{ 
   //Some other code 
   "scripts": {
      //code
      "test": "jest", 
      "test:watch": "npm test -- --watch" 
   }, 
   //code 
}
Finally, run npm test or npm run test. Let us check how we can write test cases for action creators and reducers.
Let us assume you have action creator as shown below −
export function itemsRequestSuccess(bool) {
   return {
      type: ITEMS_REQUEST_SUCCESS,
      isLoading: bool,
   }
}
This action creator can be tested as given below −
import * as action from '../actions/actions';
import * as types from '../../constants/ActionTypes';

describe('actions', () => {
   it('should create an action to check if item is loading', () => { 
      const isLoading = true, 
      const expectedAction = { 
         type: types.ITEMS_REQUEST_SUCCESS, isLoading 
      } 
      expect(actions.itemsRequestSuccess(isLoading)).toEqual(expectedAction) 
   })
})
We have learnt that reducer should return a new state when action is applied. So reducer is tested on this behaviour.
Consider a reducer as given below −
const initialState = {
   isLoading: false
};
const reducer = (state = initialState, action) => {
   switch (action.type) {
      case 'ITEMS_REQUEST':
         return Object.assign({}, state, {
            isLoading: action.payload.isLoading
         })
      default:
         return state;
   }
}
export default reducer;
To test above reducer, we need to pass state and action to the reducer, and return a new state as shown below −
import reducer from '../../reducer/reducer' 
import * as types from '../../constants/ActionTypes'

describe('reducer initial state', () => {
   it('should return the initial state', () => {
      expect(reducer(undefined, {})).toEqual([
         {
            isLoading: false,
         }
      ])
   })
   it('should handle ITEMS_REQUEST', () => {
      expect(
         reducer(
            {
               isLoading: false,
            },
            {
               type: types.ITEMS_REQUEST,
               payload: { isLoading: true }
            }
         )
      ).toEqual({
         isLoading: true
      })
   })
})
If you are not familiar with writing test case, you can check the basics of JEST.

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    129 Lectures 
     19.5 hours 

 Ghulam Abbas

    31 Lectures 
     3 hours 

 Saumitra Vishal

    55 Lectures 
     4 hours 

 Saumitra Vishal
 Print
 Add Notes
 Bookmark this page
Check if a large number is divisibility by 15 in C++

Here we will see how to check a number is divisible by 15 or not. In this case the number is very large number. So we put the number as string.
To check whether a number is divisible by 15, if the number is divisible by 5, and divisible by 3. So to check divisibility by 5, we have to see the last number is 0 or 5. To check divisibility by 3, we will see the sum of digits are divisible by 3 or not.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isDiv15(string num){
   int n = num.length();
   if(num[n - 1] != '5' && num[n - 1] != '0')
      return false;
      long sum = accumulate(begin(num), end(num), 0) - '0' * n;
   if(sum % 3 == 0)
      return true;
      return false;
}
int main() {
   string num = "154484585745184258458158245285260";
   if(isDiv15(num)){
      cout << "Divisible";
   } else {
      cout << "Not Divisible";
   }
}
Divisible
Python | Sort list elements by frequency

05 Apr, 2022
Given a list containing repeated and non-repeated elements, the task is to sort the given list on basis of the frequency of elements. Let’s discuss few methods for the same.
Python3
# Python code to demonstrate# sort list by frequency# of elements from collections import Counter ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7,            1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of frequency of elementsresult = [item for items, c in Counter(ini_list).most_common()                                      for item in [items] * c] # printing final resultprint("final list", str(result))
Output:
initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]
final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]
Python3
# Python code to demonstrate# sort list by frequency# of elements from collections import Counterfrom itertools import repeat, chain ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7,            1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of frequency of elementsresult = list(chain.from_iterable(repeat(i, c)         for i, c in Counter(ini_list).most_common())) # printing final resultprint("final list", str(result))
Output:
initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]
final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]
Python3
# Python code to demonstrate# sort list by frequency# of elements ini_list = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3,               5, 5, 5, 4, 4, 4, 4, 4, 4] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of frequency of elementsresult = sorted(ini_list, key = ini_list.count,                                reverse = True) # printing final resultprint("final list", str(result))
Output:
initial list [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4]
final list [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 5, 5, 5, 1, 1]
kapilsahu421
simmytarika5
Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
sprintf() in C

28 Jun, 2022
Syntax: 
int sprintf(char *str, const char *string,...); 
Return: 
If successful,
it returns the total number of 
characters written excluding 
null-character appended in the string, 
in case of failure a negative number 
is returned .
sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.
C
// Example program to demonstrate sprintf()#include <stdio.h>int main(){    char buffer[50];    int a = 10, b = 20, c;    c = a + b;    sprintf(buffer, "Sum of %d and %d is %d", a, b, c);     // The string "sum of 10 and 20 is 30" is stored    // into buffer instead of printing on stdout    printf("%s", buffer);     return 0;}
Sum of 10 and 20 is 30
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Time Complexity: O(n), where n is the number of elements being stored in buffer.Auxiliary Space:  O(n), where n is the number of elements being stored in buffer.
harpreet0745
anandkumarshivam2266
hardikkoriintern
cpp-input-output
CPP-Library
C Language
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
How to make a vertical line using HTML ?

10 May, 2022
To make a vertical line, use border-left or border-right property. The height property is used to set the height of border (vertical line) element. Position property is used to set the position of vertical line.
Example 1: It creates a vertical line using border-left, height and position property. 
html
<!DOCTYPE html><html> <head>    <title>        HTML border Property    </title>         <!-- style to create vertical line -->    <style>        .vertical {            border-left: 6px solid black;            height: 200px;            position:absolute;            left: 50%;        }    </style></head> <body style = "text-align: center;">     <h1 style = "color: green;">        GeeksForGeeks    </h1>             <div class = "vertical"></div> </body> </html>                                     
Output:  
Example 2: It creates a vertical line using border-left and height property. 
html
<!DOCTYPE html><html> <head>    <title>        HTML border Property    </title>         <!-- border-left property is used to        create vertical line -->    <style>        .vertical {            border-left: 5px solid black;            height: 200px;        }    </style></head> <body>     <h1 style= "color: green;">        GeeksForGeeks    </h1>             <div class= "vertical"></div> </body> </html>                   
Output:  
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
ysachin2314
hardikkoriintern
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to select all child elements recursively using CSS?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
Python | Program to count number of lists in a list of lists

07 May, 2019
Given a list of lists, write a Python program to count the number of lists contained within the list of lists.
Examples:
Input :  [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
Output : 3

Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']]
Output : 4

 Method #1 : Using len()
# Python3 program to Count number # of lists in a list of lists  def countList(lst):    return len(lst)      # Driver codelst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]print(countList(lst))
3

 Method #2 : Using type()
Use a for loop and in every iteration to check if the type of the current item is a list or not, and accordingly increment ‘count’ variable. This method has a benefit over approach #1, as it works well for a list of heterogeneous elements.
# Python3 program to Count number # of lists in a list of lists  def countList(lst):    count = 0    for el in lst:        if type(el)== type([]):            count+= 1                  return count      # Driver codelst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]print(countList(lst))
3

A one-liner alternative approach for the above code is given below:
def countList(lst):    return sum(type(el)== type([]) for el in lst)
 Method #3 : Using isinstance() method
# Python3 program to Count number # of lists in a list of lists  def countList(lst):    return sum(isinstance(i, list) for i in lst)      # Driver codelst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]print(countList(lst))
3

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Display the contents of a VIEW in MySQL?

Following is the syntax −
select * from yourViewName;
Let us first create a table −
mysql> create table DemoTable1388
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(40)
   -> );
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1388(StudentName) values('Chris');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1388(StudentName) values('Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1388(StudentName) values('David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1388(StudentName) values('Mike');
Query OK, 1 row affected (0.29 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1388;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Bob         |
|         3 | David       |
|         4 | Mike        |
+-----------+-------------+
4 rows in set (0.00 sec)
Following is the query to create view in MySQL −
mysql> create view view1388 as select *from DemoTable1388 where StudentId=3;
Query OK, 0 rows affected (0.13 sec)
Now, display the contents of view in MySQL −
mysql> select * from view1388;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         3 | David       |
+-----------+-------------+
1 row in set (0.19 sec)
How to implement a filter() for Objects in JavaScript? - GeeksforGeeks

28 Jan, 2020
The filter() method basically outputs all the element object that pass a specific test or satisfies a specific function. The return type of the filter() method is an array that consists of all the element(s)/object(s) satisfying the specified function.
Syntax:
var newArray = arr.filter(callback(object[, ind[, array]])[, Arg])
Parameters:
Callback is a predicate, to test each object of the array. Returns True to keep the object, False otherwise. It takes in three arguments:
Object: The current object being processed in the array.
ind (Optional): Index of the current object being processed in the array.
array (Optional): Array on which filter was called upon.
Arg (Optional): Value to use(.this) when executing callback.
Example 1:
<script>    var array =         [-1, -4, 5, 6, 8, 9, -12, -5, 4, -1];    var new_array =         array.filter(element => element >= 0);    document.write(      "<h2>Output\n</h2>", "<h3>", new_array, "</h3>");</script>
Output:The above example returns all the positive elements in a given array.
Example 2:
<script>var employees = [    {name: "Tony Stark", department: "IT"},    {name: "Peter Parker", department: "Pizza Delivery"},    {name: "Bruce Wayne", department: "IT"},    {name: "Clark Kent", department: "Editing"}];  var output =  employees.filter(employee => employee.department == "IT");for(var i=0;i<output.length;i++){   document.write("<h2>", output[i].name, "</h2>", "<br/>")};</script>
Output:
JavaScript-Misc
javascript-object
Picked
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to generate Tkinter Buttons dynamically?

In this article, we will see how to create buttons dynamically in a tkinter window.
Creating buttons dynamically means customizing the buttons and their functionality by adding events to them.
First, we will import the tkinter library in the notebook, then we will create an instance using the Button function which takes parameters such as parent or root of the window, textvariable which is the value to assign in each button and command.
Button(parent, textvariable, command)
from tkinter import *
import tkinter as tk

# create an instance of tkinter
win = tk.Tk()

#Define the size of the window
win.geometry("700x200")

#Name the title of the window
win.title("www.tutorialspoint.com")

# number of buttons
n=10

#Defining the row and column
i=3

#Iterating over the numbers till n and
#creating the button
for j in range(n):
   mybutton= Button(win, text=j)
   mybutton.grid(row=i, column=j)

# Keep the window open
win.mainloop()
Running the above code in tkinter notebook will generate the following output.
Logo - Turtle World

Logo has a number of other additional drawing commands, some of these are given below.
home
cleartext or ct
label
setxy
The label command takes a single word as a quoted string (e.g. “a_string”) or a list of words in [ ] brackets without quotation (e.g. [a string of letters]) and prints them on the graphics window at the location of the turtle. Let us consider the following code.
The setxy command takes two arguments, treats the first as the value of the abscissa (horizontal axis) and the second as a value of the ordinate (vertical axis). It places the turtle at these coordinates, possibly leaving ink while reaching these coordinates. In the following three figures, we have shown how the setxy command can be used.
The cleartext command, abbreviated ct, clears the text region of the command window.
Following is an exercise to check your aptitude on what you have learned so far in this chapter.
What kind of figure does the following command sequence produce?
cs pu setxy -60 60 pd home rt 45 fd 85 lt 135 fd 120

Interpret these commands as you read them from left to right. Try it to find out the result.
Following is a table of command summary.
Sets the turtle's x-coordinate to +100
Moves it 100 points to the right of center
No vertical change
Moves the turtle 200 points to the left of center
No vertical change
Sets the turtle's y-coordinate to 150
Moves it 150 points above center
No horizontal change
Moves the turtle 50 points below center
No horizontal change
Moves the turtle to xy coordinate 100 100
show xcor
show ycor
Reports the turtle’s x-coordinate
Reports the turtle’s y-coordinate
setheading 0
seth 0
Points the turtle straight up, “high noon”
Moves the turtle 120 degree to point to the four o’clock position
The following screenshot is a practical demonstration of some of the above commands.

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    38 Lectures 
     2.5 hours 

 Rob Cubbon

    81 Lectures 
     7.5 hours 

 YouAccel

    8 Lectures 
     34 mins

 Yash Rajoliya
 Print
 Add Notes
 Bookmark this page
How to add a date and time in HTML5?

Use the <time> tag to add date and time. The HTML <time> tag is used for displaying the human readable date and time.
The HTML <time> tag also supports the following additional attribute −
You can try to run the following code to learn how to add date and time <details> in HTML5 −
<!Doctype html>
<html>
   <head>
      <title>HTML time Tag</title>
   </head>
   <body>
      <p>The time is <time>08:30 pm</time></p>
   </body>
</html>
How to pad a number with leading zeros in JavaScript?

To pad a number with leading zeros, a function is created here, which checks the number with its length and add leading zeros.
You can try to run the following code to pad a number with leading zeros in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         String.prototype.padFunction = function(padStr, len) {
            var str = this;
            while (str.length < len)
               str = padStr + str;
            return str;
         }
         var str = "2";
         document.write(str.padFunction("0", 4));

         var str = "8";
         document.write("<br>"+str.padFunction("0", 5));
      </script>
   </body>
</html>
0002
00008
Calling an External Program in Java using Process and Runtime - GeeksforGeeks

09 Aug, 2019
Java contains the functionality of initiating an external process – an executable file or an existing application on the system, such as Google Chrome or the Media Player- by simple Java code. One way is to use following two classes for the purpose:
Process classRuntime class
Process class
Runtime class
The Process class present in the java.lang package contains many useful methods such as killing a subprocess, making a thread wait for some time, returning the I/O stream of the subprocess etc. Subsequently, the Runtime class provides a portal to interact with the Java runtime environment. It contains methods to execute a process, give the number of available processors, display the free memory in the JVM, among others.
// A sample Java program (Written for Windows OS)// to demonstrate creation of external process // using Runtime and Processclass CoolStuff{    public static void main(String[] args)    {        try        {            // Command to create an external process            String command = "C:\Program Files (x86)"+                 "\Google\Chrome\Application\chrome.exe";              // Running the above command            Runtime run  = Runtime.getRuntime();            Process proc = run.exec(command);        }          catch (IOException e)        {            e.printStackTrace();        }    }}
Runtime.getRuntime() simply returns the Runtime object associated with the current Java application. The executable path is specified in the process exec(String path) method. We also have an IOException try-catch block to handle the case where the file to be executed is not found. On running the code, an instance of Google Chrome opens up on the computer.
Another way to create an external process is using ProcessBuilder which has been discussed in below post.ProcessBuilder in Java to create a basic online Judge
This article is contributed by Anannya Uberoi. 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.
DevParzival404
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
LinkedList in Java
In JavaScript, can be use a new line in console.log?

Yes, we can use a new line using “\n” in console.log(). Following is the code −
const studentDetailsObject = new Object()
studentDetailsObject.name = 'David'
studentDetailsObject.subjectName = 'JavaScript'
studentDetailsObject.countryName = 'US'
studentDetailsObject.print = function(){
   console.log('hello David');
}
console.log("studentObject", "\n", studentDetailsObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo170.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo170.js
studentObject
{
   name: 'David',
   subjectName: 'JavaScript',
   countryName: 'US',
   print: [Function]
}