code-rag-bench/online-tutorials huggingface dataset:
JUnit - Execution Procedure

This chapter explains the execution procedure of methods in JUnit, which defines the order of the methods called. Discussed below is the execution procedure of the JUnit test API methods with example.
Create a java class file named ExecutionProcedureJunit.java in C:\>JUNIT_WORKSPACE to test annotation.
import org.junit.After;
import org.junit.AfterClass;

import org.junit.Before;
import org.junit.BeforeClass;

import org.junit.Ignore;
import org.junit.Test;

public class ExecutionProcedureJunit {
	
   //execute only once, in the starting 
   @BeforeClass
   public static void beforeClass() {
      System.out.println("in before class");
   }

   //execute only once, in the end
   @AfterClass
   public static void  afterClass() {
      System.out.println("in after class");
   }

   //execute for each test, before executing test
   @Before
   public void before() {
      System.out.println("in before");
   }
	
   //execute for each test, after executing test
   @After
   public void after() {
      System.out.println("in after");
   }
	
   //test case 1
   @Test
   public void testCase1() {
      System.out.println("in test case 1");
   }

   //test case 2
   @Test
   public void testCase2() {
      System.out.println("in test case 2");
   }
}
Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute annotations.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(ExecutionProcedureJunit.class);

      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
} 
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java

Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner

Verify the output.
in before class
in before
in test case 1
in after
in before
in test case 2
in after
in after class

See the above output. The execution procedure is as follows −
First of all, the beforeClass() method executes only once.
The afterClass() method executes only once.
The before() method executes for each test case, but before executing the test case.
The after() method executes for each test case, but after the execution of test case.
In between before() and after(), each test case executes.

    24 Lectures 
     2.5 hours 

 Nishita Bhatt

    56 Lectures 
     7.5 hours 

 Dinesh Varyani
 Print
 Add Notes
 Bookmark this page
Calculate the difference between Consecutive pair of Elements of a Vector in R Programming - diff() Function - GeeksforGeeks

05 Jun, 2020
diff() function in R Language is used to find the difference between each consecutive pair of elements of a vector.
Syntax: diff(x, lag, differences)
Parameters:x: vector or matrixlag: period between elementsdifferences: Order of difference
Example 1:
# R program to find the difference# between each pair of elements of a vector  # Creating a vectorx1 <- c(8, 2, 5, 4, 9, 6, 54, 18)x2 <- c(1:10)x3 <- c(-1:-8)  # Calling diff() functiondiff(x1)diff(x2)diff(x3)
Output:
[1]  -6   3  -1   5  -3  48 -36
[1] 1 1 1 1 1 1 1 1 1
[1] -1 -1 -1 -1 -1 -1 -1

Example 2:
# R program to find the difference# between each pair of elements of a vector  # Creating a vectorx1 <- c(8, 2, 5, 4, 9, 6, 54, 18)x2 <- c(1:10)  # Calling diff() functiondiff(x1, lag = 2, differences = 1)diff(x2, lag = 1, differences = 2)
Output:
[1] -3  2  4  2 45 12
[1] 0 0 0 0 0 0 0 0

Here, in the above code, the ‘lag’ tells the period between values, i.e. lag = 2 means, diff is calculated between 1st and 3rd value, 2nd and 4th values, etc. and ‘differences’ tells the order in which diff() function is called i.e. differences = 2 means diff() function is called twice on the vector.
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Remove rows with NA in one column of R DataFrame
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
QlikView - Synthetic Key

A Synthetic Key is QlikView's solution to create an artificial key when there is ambiguity about which key to use between two tables. This situation arises when two tables have two or more fields in common. QlikView's feature of creating association in memory
automatically detects this scenario and creates an additional table, which will hold the value of the new key created.
Let us consider the following two CSV data files, which are used as input for further illustrations.
Sales:
ProductID,ProductCategory,Country,SaleAmount
1,Outdoor Recreation,Italy,4579
2,Clothing,USA,4125
3,Costumes & Accessories,South Korea,6521

Product:
ProductID, Country
3,Brazil
3,China
2,Korea
1,USA

We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file.
Next, we look at the data model by using the menu command for table viewer, Control+T. The following screen comes up, which shows the creation of a third table that supplies the value of the synthetic key as both the tables have ProductID and Country as matching keys.
Synthetic keys indicate the flaw in the data model that is being used. They do not cause any issue in the correctness of the data or performance of the report. Things will work fine if a big data model has one or two instances of synthetic keys. However, if we have too many of them, then that is an implication to redesign the data model.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
MySQL query to count frequency of students with the same age?

You can use COUNT(*) along with GROUP BY for this. Let us first create a table −
mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentAge int
   );
Query OK, 0 rows affected (0.59 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(StudentAge) values(16);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentAge) values(18);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(StudentAge) values(17);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(StudentAge) values(18);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentAge) values(18);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentAge) values(19);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentAge) values(19);
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(StudentAge) values(16);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentAge) values(16);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentAge) values(15);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+-----------+------------+
| StudentId | StudentAge |
+-----------+------------+
| 1         | 16         |
| 2         | 17         |
| 3         | 18         |
| 4         | 17         |
| 5         | 17         |
| 6         | 17         |
| 7         | 18         |
| 8         | 18         |
| 9         | 19         |
| 10        | 19         |
| 11        | 16         |
| 12        | 16         |
| 13        | 15         |
+-----------+------------+
13 rows in set (0.00 sec)
Following is the query to count frequency −
mysql> select StudentAge,count(*) AS `AgeFrequency` from DemoTable group by StudentAge;
This will produce the following output −
+------------+--------------+
| StudentAge | AgeFrequency |
+------------+--------------+
| 16         | 3            |
| 17         | 4            |
| 18         | 3            |
| 19         | 2            |
| 15         | 1            |
+------------+--------------+
5 rows in set (0.05 sec)
Difference between print() and println() in Java - GeeksforGeeks

06 Apr, 2022
print(): print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here. Various print() methods:
void print(boolean b) – Prints a boolean value. void print(char c) – Prints a character. void print(char[] s) – Prints an array of characters. void print(double d) – Prints a double-precision floating-point number. void print(float f) – Prints a floating-point number. void print(int i) – Prints an integer. void print(long l) – Prints a long integer. void print(Object obj) – Prints an object. void print(String s) – Prints a string.
Example: 
Java
import java.io.*; class GFG {    public static void main(String[] args)    {         // The cursor will remain        // just after the 1        System.out.print("GfG1");         // This will be printed        // just after the GfG2        System.out.print("GfG2");    }}
GfG1GfG2
println(): println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console. The next printing takes place from next line. Various println() methods:
void println() – Terminates the current line by writing the line separator string. void println(boolean x) – Prints a boolean and then terminate the line. void println(char x) – Prints a character and then terminate the line. void println(char[] x) – Prints an array of characters and then terminate the line. void println(double x) – Prints a double and then terminate the line. void println(float x) – Prints a float and then terminate the line. void println(int x) – Prints an integer and then terminate the line. void println(long x) – Prints a long and then terminate the line. void println(Object x) – Prints an Object and then terminate the line. void println(String x) – Prints a String and then terminate the line.
Example: 
Java
import java.io.*; class GFG {    public static void main(String[] args)    {         // The cursor will after GFG1        // will at the start        // of the next line        System.out.println("GfG1");         // This will be printed at the        // start of the next line        System.out.println("GfG2");    }}
GfG1
GfG2
Difference between print() and println()
shri14
sweetyty
java-basics
Java-Functions
Java-I/O
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
C++ Classes and Objects
Interfaces in Java
How to use loading animation by using the react-loader-spinner through npm ? - GeeksforGeeks

03 Sep, 2021
The spinner to indicate the loading state. We can also modify the appearance, size, and placement of the spinners with the propeTypes available in the react-loader-spinner. The react-loader-spinner is an npm package that provides a simple and attractive SVG spinner component that can be used in any of your projects. This package has more than 75k+ downloads weekly.
Here for loader, we are going to use npm package called react-loader-spinner. It is a package for loaders. For in-depth knowledge, you can visit the below link.
https://www.npmjs.com/package/react-loader-spinner
Syntax:
<Loader
  type="Spinner Type"
  color="rgb color"
  height={number}
  width={number}
  timeout={number in ms}
/>;
Types of spinner: All types of the spinner can be used similarly you just need to change the type of the loader.
Audio
Ball-Triangle
Bars
Circles
Grid
Hearts
Oval
Puff
Rings
TailSpin
ThreeDots
PropTypes: All the types of spinner accept these props.
visible: It is a boolean value that defines that the spinner should be visible or not, the default value is false.
type: This prop defines the spinner type.
height: This prop defines the height of the SVG spinner and the default value is 80.
width: This prop defines the width of the SVG spinner and the default value is 80.
color: This prop defines the color of the spinner.
secondaryColor: This prop is available on the plane and mutatingDots loaders.
timeout: This defines the effective time of the spinner.
radius: This prop set the radius of the spinner.
Creating React Application and Installing Module:
Step 1: Create the React app using the command.
 
npx create-react-app foldername 
Step 2: Now move into your project folder i.e. foldername by using this command.
 
cd foldername
Step 3: Now install the package into your project folder.
 
npm install react-loader-spinner
Step 4: Now create a new file into your src folder i.e. loader.js
Project Structure: It will look like this. Here our folder name is react_loader.
Example: In this example, we will create a loading spinner, for that, we have already created a component file that is loader.js. We will call the loadr.js file into our main rendering file App.js
 
 
 
 
Output:
 
 
Reference: https://www.npmjs.com/package/react-loader-spinner
 
rs1686740
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data from one component to other component in ReactJS ?
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Re-rendering Components in ReactJS
Axios in React: A Guide for Beginners
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
p5.js | doubleClicked() Function - GeeksforGeeks

17 Jan, 2020
The doubleClicked() function is invoked whenever a mouse or pointing device causes a dblclick event. This happens when the pointing device is clicked twice in quick succession on a single element. The MouseEvent callback argument could be used to access the details of the click.
Syntax:
doubleClicked([event])
Parameters: This function accepts a single parameter as mentioned above and described below:
event: This is an optional MouseEvent callback argument. It can be used to access the click details.
The program below illustrate the doubleClicked() function in p5.js:
Example 1: Using double click to change the fill color.
let colorVal = 0;  function setup() {  createCanvas(500, 300);  textSize(24);}  function draw() {  clear();    // apply fill based on the red component  fill(colorVal, 128, 255 - colorVal)    text("Double click to change the color", 20, 20);  circle(150, 150, 200);}  function doubleClicked() {  // change the value if  // the event occurs  if (colorVal < 255)    colorVal += 50;  else    colorVal = 0;}
Output:Example 2: Accessing the details of the MouseEvent object.
let y = 60;  function setup() {  createCanvas(500, 200);  textSize(16);  text("Double click the mouse to see doubleClicked() function fire", 10, 20);}  function doubleClicked(event) {  // get the x and y location  // of the double click  locationX = event.x;  locationY = event.y;    locString = "Mouse was double clicked at location: "    + locationX + ", " + locationY;  text(locString, 10, y);  y = y + 20;    console.log(event);}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/doubleClicked
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Golang program that uses func with variable argument list - GeeksforGeeks

10 May, 2020
In Golang, a function that can be called with a variable argument list is known as a variadic function. One can pass zero or more arguments in the variadic function. If the last parameter of a function definition is prefixed by ellipsis ..., then the function can accept any number of arguments for that parameter.
Syntax of a variadic function:
func f(elem ...Type)
Here ... operator tells Golang program to store all arguments of Type in elem parameter. After that, Go create an elem variable of the type []Type. Therefore, all the values passed are stored in an elem parameter which is a slice. A slice can also be passed in the argument instead of the argument list, as finally function is converting them into a slice.
For more information you can refer to Variadic Functions in Golang
Advantages of using a Variadic Function:
Passing a slice in a function is very easy.
Useful when the number of parameters is unknown.
Increases the readability of the program.
Let’s see some of the examples to use functions with variable argument list:
Example 1:
// Go program that uses a function// with variable argument listpackage main  // Importing required packagesimport (    "fmt")  // Variadic function to return // the sum of the numbersfunc add(num ...int) int {    sum := 0    for j := range num {        sum += j    }    return sum}  func main() {    fmt.Println("Sum =", add(1, 2, 3, 4, 5, 7, 8, 6, 5, 4))}
Output:
Sum = 45
Example 2: A slice can also be used as an argument list.
// Go program that uses a function// with variable argument list// Using a slice as the argument listpackage main  // importing required modulesimport (    "fmt")  // Function to check if an element// is present in the list or notfunc check(x int, v ...int) {      flag := false    index := 0    for i, j := range v {        if j == x {            flag = true            index = i        }    }      if flag {        fmt.Println("Element ", x, " found at index:", index)    } else {        fmt.Println("Element not present in the list")    }}func main() {    el := []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9}    check(1, el...)    check(10, el...)}
Output:
Element  1  found at index: 1
Element not present in the list

Go-Functions
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Time Durations in Golang
Strings in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Defer Keyword in Golang
Loops in Go Language
Class and Object in Golang
Python Tuple Methods

22 Jul, 2021
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples.
The count() method of Tuple returns the number of times the given element appears in the tuple.
Syntax:
tuple.count(element)
Where the element is the element that is to be counted.
Example 1: Using the Tuple count() method 
Python3
# Creating tuplesTuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)Tuple2 = ('python', 'geek', 'python',           'for', 'java', 'python')  # count the appearance of 3res = Tuple1.count(3)print('Count of 3 in Tuple1 is:', res)  # count the appearance of pythonres = Tuple2.count('python')print('Count of Python in Tuple2 is:', res)
Output:
Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3
Example 2: Counting tuples and lists as elements in Tuples
Python3
# Creating tuplesTuple = (0, 1, (2, 3), (2, 3), 1,          [3, 2], 'geeks', (0,))  # count the appearance of (2, 3)res = Tuple.count((2, 3))print('Count of (2, 3) in Tuple is:', res)  # count the appearance of [3, 2]res = Tuple.count([3, 2])print('Count of [3, 2] in Tuple is:', res)
Output:
Count of (2, 3) in Tuple is: 2
Count of [3, 2] in Tuple is: 1
The Index() method returns the first occurrence of the given element from the tuple.
Syntax:
tuple.index(element, start, end)
Parameters:
element: The element to be searched.
start (Optional): The starting index from where the searching is started
end (Optional): The ending index till where the searching is done
Note: This method raises a ValueError if the element is not found in the tuple.
Example 1: Using Tuple Index() Method
Python3
# Creating tuplesTuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)  # getting the index of 3res = Tuple.index(3)print('First occurrence of 3 is', res)  # getting the index of 3 after 4th# indexres = Tuple.index(3, 4)print('First occurrence of 3 after 4th index is:', res)
Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5
Example 2: Using Tuple() method when the element is not found
Python3
# Creating tuplesTuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)  # getting the index of 3res = Tuple.index(4)
Output:
ValueError: tuple.index(x): x not in tuple
Note: For more information on Python Tuples refer to Python Tuple Tutorial.
python-tuple
Python-tuple-functions
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Add similar value multiple times in list

30 Dec, 2018
Adding a single value in list is quite generic and easy. But to add that value more than one time, generally, a loop is used to execute this task. Having shorter tricks to perform this can be handy. Let’s discuss certain ways in which this can be done.
Method #1 : Using * operatorWe can employ * operator to multiply the occurrence of the particular value and hence can be used to perform this task of adding value multiple times in just a single line and makes it readable.
# Python3 code to demonstrate # to add multiple similar values# using * operator  # using * operator to add multiple values# adds 3, 50 times.res = [3] * 50  # printing resultprint ("The filtered list is : " + str(res))
Output :
The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
Method #2 : Using extend() + list comprehensionextend function is used to perform the list append and list comprehension part is responsible for performing the task of repetition of elements desired number of times.
# Python3 code to demonstrate # to add multiple similar values# using extend() + list comprehension  # using extend() + list comprehension to add multiple values# adds 3, 50 times.res = []res.extend([3 for i in range(50)])  # printing resultprint ("The filtered list is : " + str(res))
Output :
The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
Method #3 : Using extend() + itertools.repeat()This is similar to the above method, the task of extend() is similar, but repeat() performs the task list comprehension performed of iteration N no. of times desired.
# Python3 code to demonstrate # to add multiple similar values# using extend() + itertools.repeat()from itertools import repeat  # using extend() + itertools.repeat() to add multiple values# adds 3, 50 times.res = []res.extend(repeat(3, 50))  # printing resultprint ("The filtered list is : " + str(res))
Output :
The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
fileinput.filename() in Python

22 Apr, 2020
With the help of fileinput.filename() method, we can get the last used file name which we have used so far by using fileinput.filename() method.
Syntax : fileinput.filename()
Return : Return the last used file name.
Example #1 :In this example we can see that by using fileinput.filename() method, we are able to get the last used file name by using this method.
# import fileinputimport fileinput  # Using fileinput.input() methodfor line in fileinput.input(files ='gfg.txt'):    print(line)  print(fileinput.filename())
Output :
Example #2 :
# import fileinputimport fileinput  # Using fileinput.input() methodfor line in fileinput.input(files =('gfg.txt', 'gfg1.txt')):    print(line)  print(fileinput.filename())
Output :
Python fileinput-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shift 2D Grid in C++

Suppose we have one 2D grid of size m x n. We have another variable k. We have to shift the
grid k times. The shift operation will be as follows
Element at grid G[i, j] moves to G[i, j + 1]
Element at grid G[i, j] moves to G[i, j + 1]
Element at grid G[i, n – 1] moves to G[i + 1, 0]
Element at grid G[i, n – 1] moves to G[i + 1, 0]
Element at grid G[m - 1, n – 1] moves to G[0, 0]
Element at grid G[m - 1, n – 1] moves to G[0, 0]
So if the grid is like −
The output will be −
To solve this, we will follow these steps −
The shift operation will take the matrix as input
The shift operation will take the matrix as input
n = number of rows, m := number of columns, x := bottom right element
n = number of rows, m := number of columns, x := bottom right element
for i := n – 1, down to 0for j := m – 1 down to 0if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]else if j > 0, then G[i, j] := G[i, j – 1]
for i := n – 1, down to 0
for j := m – 1 down to 0if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]else if j > 0, then G[i, j] := G[i, j – 1]
for j := m – 1 down to 0
if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]
if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]
else if j > 0, then G[i, j] := G[i, j – 1]
else if j > 0, then G[i, j] := G[i, j – 1]
G[0, 0] := x
G[0, 0] := x
Call the shift operation by the following rule −
Call the shift operation by the following rule −
while k is not 0shift the grid Gdecrease k by 1
while k is not 0
shift the grid G
shift the grid G
decrease k by 1
decrease k by 1
return grid G
return grid G
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] <<", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   void shift(vector<vector<int>>& grid){
      int n = grid.size();
      int m = grid[0].size();
      int x = grid[n-1][m-1];
      for(int i = n-1; i>=0; i--){
         for(int j = m-1;j>=0;j--){
            if(j == 0 && i>0){
               grid[i][j] = grid[i-1][m-1];
            }
            else if(j>0){
               grid[i][j] = grid[i][j-1];
            }
         }
      }
      grid[0][0] = x;
   }
   vector<vector<int>> shiftGrid(vector<vector<int>>& g, int k) {
      while(k--){
         shift(g);
      }
      return g;
   }
};
main(){
   Solution ob;
   vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
   print_vector(ob.shiftGrid(mat, 1));
}
{{1,2,3},{4,5,6},{7,8,9}}
1
[[9, 1, 2, ],[3, 4, 5, ],[6, 7, 8, ],]
\underbrace - Tex Command

\underbrace - Used to put a (stretchy) under-brace under the argument.
{ \underbrace #1}
\underbrace command is used to put a (stretchy) under-brace under the argument.

\underbrace{x + \cdots + x}_{n\rm\ times}^{\text{(note here)}}

x+⋯+x⏟n times(note here)



\underbrace{x + \cdots + x}_{n\rm\ times}^{\text{(note here)}}

x+⋯+x⏟n times(note here)


\underbrace{x + \cdots + x}_{n\rm\ times}^{\text{(note here)}}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Repeated DNA Sequences in C++

Suppose we have a DNA sequence. As we know, all DNA is composed of a series of nucleotides abbreviated such as A, C, G, and T, for example: "ACGAATTCCG". When we are studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
We have to write one method to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
So if the input is like “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”, then the output will be ["AAAAACCCCC", "CCCCCAAAAA"].
To solve this, we will follow these steps −
Define an array ret, n := size of s, create two sets called visited and visited2
Define an array ret, n := size of s, create two sets called visited and visited2
define a map called bitVal.
define a map called bitVal.
Store corresponding values for ACGT like 0123 into butVal.
Store corresponding values for ACGT like 0123 into butVal.
mask := 0
mask := 0
for i in range 0 to n – 1mask := mask * 4mask := mast OR bitVal[s[i]]mask := mask AND FFFFFif i < 9, then just continue to the next iterationinsert substring form index i – 9 to 9, into retinsert mark into visited2.insert mask into visited
for i in range 0 to n – 1
mask := mask * 4
mask := mask * 4
mask := mast OR bitVal[s[i]]
mask := mast OR bitVal[s[i]]
mask := mask AND FFFFF
mask := mask AND FFFFF
if i < 9, then just continue to the next iterationinsert substring form index i – 9 to 9, into retinsert mark into visited2.
if i < 9, then just continue to the next iteration
insert substring form index i – 9 to 9, into ret
insert substring form index i – 9 to 9, into ret
insert mark into visited2.
insert mark into visited2.
insert mask into visited
insert mask into visited
return ret
return ret
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
typedef long long int lli;
class Solution {
public:
   vector<string>findRepeatedDnaSequences(string s) {
      vector <string> ret;
      int n = s.size();
      set <int> visited;
      set <int> visited2;
      map <char, int> bitVal;
      bitVal['A'] = 0;
      bitVal['C'] = 1;
      bitVal['G'] = 2;
      bitVal['T'] = 3;
      lli mask = 0;
      for(int i = 0; i < n; i++){
         mask <<= 2;
         mask |= bitVal[s[i]];
         mask &= 0xfffff;
         if(i < 9) continue;
         if(visited.count(mask) && !visited2.count(mask)){
            ret.push_back(s.substr(i - 9, 10));
            visited2.insert(mask);
         }
         visited.insert(mask);
      }
      return ret;
   }
};
main(){
   Solution ob;
   print_vector(ob.findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"));
}
"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
[AAAAACCCCC, CCCCCAAAAA, ]
Java Examples - Delete a directory

How to delete a directory?
Following example demonstares how to delete a directory after deleting its files and directories by the use ofdir.isDirectory(),dir.list() and deleteDir() methods of File class.
import java.io.File;

public class Main {
   public static void main(String[] argv) throws Exception {
      deleteDir(new File("c:\\temp"));
   }
   public static boolean deleteDir(File dir) {
      if (dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir (new File(dir, children[i]));
            
            if (!success) {
               return false;
            }
         }
      }
      return dir.delete();
      System.out.println("The directory is deleted.");
   }
}
The above code sample will produce the following result.
The directory is deleted.

 Print
 Add Notes
 Bookmark this page
Find MongoDB records based on a condition?

To find MongoDB based on a condition, use find() and set the condition. Let us create a collection with documents −
> db.demo708.insertOne({"Name":"John",Marks:54});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702e4d346dcb074dc6f33")
}
> db.demo708.insertOne({"Name":"Chris",Marks:35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702e6d346dcb074dc6f34")
}
> db.demo708.insertOne({"Name":"David",Marks:45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702ebd346dcb074dc6f35")
}
> db.demo708.insertOne({"Name":"Bob",Marks:40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea702fad346dcb074dc6f36")
}
Display all documents from a collection with the help of find() method −
> db.demo708.find();
This will produce the following output −
{ "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 }
{ "_id" : ObjectId("5ea702e6d346dcb074dc6f34"), "Name" : "Chris", "Marks" : 35 }
{ "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 }
{ "_id" : ObjectId("5ea702fad346dcb074dc6f36"), "Name" : "Bob", "Marks" : 40 }
Following is the query to find MongoDB records based on a condition −
> db.demo708.find({Marks:{$gt:40}});
This will produce the following output −
{ "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 }
{ "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 }
Can we overload the main method in Java?

Yes, we can overload the main method in Java, but When we execute the class JVM starts execution with public static void main(String[] args) method.
 Live Demo
public class Sample{
   public static void main(){
      System.out.println("This is the overloaded main method");
   }
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.main();
   }
}
This is the overloaded main method
GATE | GATE-CS-2003 | Question 31 - GeeksforGeeks

28 Jun, 2021
Let (5, ≤) be a partial order with two minimal elements a and b, and a maximum element c.
Let P : S → {True, False} be a predicate defined on S.
Suppose that P(a) = True, P(b) = False and 
P(x) ⇒ P(y) for all x, y ∈ S satisfying x ≤ y, 
where ⇒ stands for logical implication.
Which of the following statements CANNOT be true ?(A) P(x) = True for all x ∈ S such that x ≠ b(B) P(x) = False for all x ∈ S such that x ≠ a and x ≠ c(C) P(x) = False for all x ∈ S such that b ≤ x and x ≠ c(D) P(x) = False for all x ∈ S such that a ≤ x and b ≤ xAnswer: (D)Explanation:‘a’ and ‘b’ are given as minimal elements. No other element in S is of lower order than either a or b.‘c’ is given as maximum element. So, c is of higher order than any other element in S.P(a) = True means all elements ‘x’ which have an edge from element ‘a’ have to be true.Since there is an edge from ‘a’, we have to satisfy formula P(a) => P(x), which can only be done by settingP(x) = True.Elements which have an edge from b can be anything because formula P(b) => P(x) is satisfied as P(b) = False.(A) This statement is true because making all elements true trivially satisfy formula P(x) => P(y).(B) This statement is true if all elements are connected from b then all elements can be false.(C) This statement is true because b<=x ensures x!=a and for all other elements P(x) can be false without violating the given implication.(D) This statement is false. Since, P(a) = true , for all ‘x’ such that a<=x, P(x) must be true. We do have at least one such 'x', which is 'c' as it is the maximum element. Thus, option (D) is the answer. Please comment below if you find anything wrong in the above post.
Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | Gate IT 2007 | Question 30
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE MOCK 2017 | Question 19
How to capitalize the first letter of each word in a string using JavaScript?

At first, you need to split() the string on the basis of space and extract the first character using
charAt(). Use toUpperCase() for the extracted character.
function capitalizeTheFirstLetterOfEachWord(words) {
   var separateWord = words.toLowerCase().split(' ');
   for (var i = 0; i < separateWord.length; i++) {
      separateWord[i] = separateWord[i].charAt(0).toUpperCase() +
      separateWord[i].substring(1);
   }
   return separateWord.join(' ');
}
console.log(capitalizeTheFirstLetterOfEachWord("my name is john"));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo43.js.
This will produce the following output with first letter capitalize −
PS C:\Users\Amit\JavaScript-code> node demo43.js
My Name Is John
Python - math.comb() method - GeeksforGeeks

23 Jan, 2020
Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.comb() method in Python is used to get the number of ways to choose k items from n items without repetition and without order. It basically evaluates to n! / (k! * (n – k)!) when k n. It is also known as binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)n.This method is new in Python version 3.8.
Syntax: math.comb(n, k)
Parameters:n: A non-negative integerk: A non-negative integer
Returns: an integer value which represents the number of ways to choose k items from n items without repetition and without order.
Code #1: Use of math.comb() method
# Python Program to explain math.comb() method  # Importing math moduleimport math  n = 10k = 2  # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk)  n = 5k = 3  # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk)
45
10

Code #2: When k > n
# Python Program to explain math.comb() method  # Importing math moduleimport math  # When k > n # math.comb(n, k) returns 0.n = 3k = 5  # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk)
0

Code #3: Use of math.comb() method to find coefficient of k-th term in binomial expansion of expression (1 + x)n
# Python Program to explain math.comb() method  # Importing math moduleimport math  n = 5k = 2  # Find the coefficient of k-th# term in the expansion of # expression (1 + x)^nnCk = math.comb(n, k)print(nCk)  n = 8k = 3  # Find the coefficient of k-th# term in the expansion of # expression (1 + x)^nnCk = math.comb(n, k)print(nCk)
10
56

Reference: Python math library
Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
C# | Type.GetInterfaces() Method - GeeksforGeeks

11 Aug, 2021
Type.GetInterfaces() Method is used to get all the interfaces implemented or inherited by the current Type when overridden in a derived class.
Syntax: public abstract Type[] GetInterfaces ();Return Value: This method returns an array of Type objects representing all the interfaces implemented or inherited by the current Type or an empty array of type Type if no interfaces are implemented or inherited by the current Type.  
Below programs illustrate the use of Type.GetInterfaces() Method:
Example 1: 
C#
// C# program to demonstrate the// Type.GetInterfaces() Methodusing System;using System.Globalization;using System.Reflection; class GFG {     // Main Method    public static void Main()    {        // Declaring and initializing object of Type        Type objType = typeof(int);         // Getting interface of specified name        // using GetField(String) Method        Type[] minterface = objType.GetInterfaces();         // Display the Result        Console.WriteLine("Interface present in type {0}", objType);        for (int i = 0; i < minterface.Length; i++)            Console.WriteLine(" {0}", minterface[i]);    }}
Interface present in type System.Int32
 System.IFormattable
 System.IComparable
 System.IComparable`1[System.Int32]
 System.IConvertible
 System.IEquatable`1[System.Int32]
 
Example 2: For if no public field is defined
C#
// C# program to demonstrate the// Type.GetInterfaces() Methodusing System;using System.Globalization;using System.Reflection; class GFG {     // Main Method    public static void Main()    {        // Declaring and initializing object of Type        Type objType = typeof(string);         // Getting interface of specified name        // using GetField(String) Method        Type[] minterface = objType.GetInterfaces();         // Display the Result        Console.WriteLine("Interface present in type {0}", objType);        for (int i = 0; i < minterface.Length; i++)            Console.WriteLine(" {0}", minterface[i]);    }}
Interface present in type System.String
 System.ICloneable
 System.Collections.Generic.IEnumerable`1[System.Char]
 System.IComparable
 System.IComparable`1[System.String]
 System.IConvertible
 System.Collections.IEnumerable
 System.IEquatable`1[System.String]
 
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.getinterfaces?view=netframework-4.8
 
adnanirshad158
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# | Delegates
Introduction to .NET Framework
C# Dictionary with examples
Difference between Ref and Out keywords in C#
Partial Classes in C#
Extension Method in C#
Top 50 C# Interview Questions & Answers
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
C# | Encapsulation
Powershell - ForEach Loop

The following scripts demonstrates the ForEach loop.
> $array = @("item1", "item2", "item3")
 
> foreach ($element in $array) { $element }
item1
item2
item3
 
> $array | foreach { $_ }
item1
item2
item3

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Python | Functions | Question 4 - GeeksforGeeks

18 Jan, 2021
What is the output of the following program :
y = 8z = lambda x : x * yprint (z(6))
(A) 48(B) 14(C) 64(D) None of the aboveAnswer: (A)Explanation: lambdas are concise functions and thus, result = 6 * 8Quiz of this Question
jadhavhitesh207
Functions
Python-Functions
Python-Quizzes
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python-Quizzes | Python List Quiz | Question 5
Python-Quizzes | Python List Quiz | Question 4
Python-Quizzes | Python Dictionary Quiz | Question 25
Python-Quizzes | Python Dictionary Quiz | Question 23
Output of Python Program - Dictionary (set 25)
Python | Output Type | Question 1
Why do people prefer Selenium with Python?
Python | Output Type | Question 3
Python | Animated Banner showing 'GeeksForGeeks'
Python-Quizzes | Output Type | Question 10
Python MongoDB - Insert Document

You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter.
Following is the syntax of the insert method.
>db.COLLECTION_NAME.insert(DOCUMENT_NAME)

> use mydb
switched to db mydb
> db.createCollection("sample")
{ "ok" : 1 }
> doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
{ "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
> db.sample.insert(doc1)
WriteResult({ "nInserted" : 1 })
>
Similarly, you can also insert multiple documents using the insert() method.
> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = [
   {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, 
   {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, 
   {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
[
   {"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"},
   {"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"},
   {"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"}
]
> db.sample.insert(data)
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
>
Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format.
Following example inserts a document in the collection named example.
from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
coll = db['example']

#Inserting document into a collection
doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
coll.insert_one(doc1)
print(coll.find_one())
{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}

To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method.
from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['mydb']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
   {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
   {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
Data inserted ......
['101', '102', '103']


    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