code-rag-bench/online-tutorials huggingface dataset:
MongoDB - Text Search

Starting from version 2.4, MongoDB started supporting text indexes to search inside string content. The Text Search uses stemming techniques to look for specified words in the string fields by dropping stemming stop words like a, an, the, etc. At present, MongoDB supports around 15 languages.
Initially, Text Search was an experimental feature but starting from version 2.6, the configuration is enabled by default.
Consider the following document under posts collection containing the post text and its tags −
> db.posts.insert({
   "post_text": "enjoy the mongodb articles on tutorialspoint",
   "tags": ["mongodb", "tutorialspoint"]
}
{
	"post_text" : "writing tutorials on mongodb",
	"tags" : [ "mongodb", "tutorial" ]
})
WriteResult({ "nInserted" : 1 })
We will create a text index on post_text field so that we can search inside our posts' text −
>db.posts.createIndex({post_text:"text"})
{
	"createdCollectionAutomatically" : true,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
Now that we have created the text index on post_text field, we will search for all the posts having the word tutorialspoint in their text.
> db.posts.find({$text:{$search:"tutorialspoint"}}).pretty()
{
	"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
	"post_text" : "enjoy the mongodb articles on tutorialspoint",
	"tags" : [
		"mongodb",
		"tutorialspoint"
	]
}
The above command returned the following result documents having the word tutorialspoint in their post text −
{ 
   "_id" : ObjectId("53493d14d852429c10000002"), 
   "post_text" : "enjoy the mongodb articles on tutorialspoint", 
   "tags" : [ "mongodb", "tutorialspoint" ]
}

To delete an existing text index, first find the name of index using the following query −
>db.posts.getIndexes()
[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "mydb.posts"
	},
	{
		"v" : 2,
		"key" : {
			"fts" : "text",
			"ftsx" : 1
		},
		"name" : "post_text_text",
		"ns" : "mydb.posts",
		"weights" : {
			"post_text" : 1
		},
		"default_language" : "english",
		"language_override" : "language",
		"textIndexVersion" : 3
	}
]
>
After getting the name of your index from above query, run the following command. Here, post_text_text is the name of the index.
>db.posts.dropIndex("post_text_text")
{ "nIndexesWas" : 2, "ok" : 1 }

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Creating Joy Plots Using JoyPy. Using JoyPy for creating series of... | by Himanshu Sharma | Towards Data Science

Visualization is a core part of finding insights and can be used for storytelling. While creating visualization we need to think about which plot to use, which features to consider, what story will be coming out, or finding root cause analysis. Have you ever been stuck with these problems?
There are different python libraries that can be used for data visualization. In this article, will be discussing a rare type of plot known as Joy Plots. They are a series of histograms, density plots, or time series data in which we create stacked visualization by fixing the data point on the X-axis and creating a stack on the Y-axis.
In this article, we will explore JoyPy an open-source python library that is used to create Joy Plots.
Let’s get started...
We will start by installing a Joy Plots library by using pip. The command given below will do that.
!pip install joypy
In this step, we will import the required libraries for loading the dataset and visualizing it.
import joypyimport seaborn as sns
Fo this article, we will use the famous “Tips” dataset which is already defined in the seaborn library.
df = sns.load_dataset('tips')df
Now we will start by creating different types of joy plots using different columns of the data.
fig, axes = joypy.joyplot(df)
This plot shows the distribution of all the numerical columns in the dataset.
fig, axes = joypy.joyplot(df, by="smoker")
This graph shows the distribution of the numerical columns with respect to the smoker column.
fig, axes = joypy.joyplot(df, by="size", ylim='day')
fig, axes = joypy.joyplot(df, by="day", overlap=10)
Go ahead try this with different datasets and create different visualizations using JoyPy. In case you find any difficulty please let me know in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me at hmix13@gmail.com or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
How to switch between dark and light mode with CSS and JavaScript?


To switch between dark and light mode with JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      padding: 25px;
      background-color: white;
      color: black;
      font-size: 25px;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .dark-mode {
      background-color: black;
      color: white;
   }
   .toggleButton {
      padding: 12px;
      font-size: 18px;
      border: 2px solid green;
   }
</style>
</head>
<body>
<h1>Toggle Dark/Light Mode Example</h1>
<button class="toggleButton">Toggle dark mode</button>
<h2>Click the above button to toggle dark mode</h2>
<script>
   document .querySelector(".toggleButton") .addEventListener("click", toggleDarKMode);
   function toggleDarKMode() {
      var element = document.body;
      element.classList.toggle("dark-mode");
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Toggle dark mode” button −
C library function - cos()

The C library function double cos(double x) returns the cosine of a radian angle x.
Following is the declaration for cos() function.
double cos(double x)
x − This is the floating point value representing an angle expressed in radians.
x − This is the floating point value representing an angle expressed in radians.
This function returns the cosine of x.
The following example shows the usage of cos() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main () {
   double x, ret, val;

   x = 60.0;
   val = PI / 180.0;
   ret = cos( x*val );
   printf("The cosine of %lf is %lf degrees\n", x, ret);
   
   x = 90.0;
   val = PI / 180.0;
   ret = cos( x*val );
   printf("The cosine of %lf is %lf degrees\n", x, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
The cosine of 60.000000 is 0.500000 degrees
The cosine of 90.000000 is 0.000000 degrees


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
ArrayList get(index) Method in Java with Examples - GeeksforGeeks

01 Nov, 2021
The get() method of ArrayList in Java is used to get the element of a specified index within the list.
Syntax: 
get(index)
Parameter: Index of the elements to be returned. It is of data-type int. 
Return Type: The element at the specified index in the given list. 
Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size()) 
Note: Time Complexity: ArrayList is one of the List implementations built a top an array. Hence, get(index) is always a constant time O(1) operation.
Example:
Java
// Java Program to Demonstrate the working of// get() method in ArrayList // Importing ArrayList classimport java.util.ArrayList; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an Empty Integer ArrayList        ArrayList<Integer> arr = new ArrayList<Integer>(4);         // Using add() to initialize values        // [10, 20, 30, 40]        arr.add(10);        arr.add(20);        arr.add(30);        arr.add(40);         // Printing elements of list        System.out.println("List: " + arr);         // Getting element at index 2        int element = arr.get(2);         // Displaying element at specified index        // on console inside list        System.out.println("the element at index 2 is "                           + element);    }}
List: [10, 20, 30, 40]
the element at index 2 is 30
Example 2: Program to demonstrate the error
Java
// Java Program to Demonstrate Error Generated// while using get() method in ArrayList // Importing ArrayList classimport java.util.ArrayList; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // Creating an Empty Integer ArrayList        ArrayList<Integer> arr = new ArrayList<Integer>(4);         // Using add() method to insert elements        // and adding custom values        arr.add(10);        arr.add(20);        arr.add(30);        arr.add(40);         // Getting element at index 2        int element = arr.get(5);         // Print all the elements of ArrayList        System.out.println("the element at index 2 is "                           + element);    }}
Output : 
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at GFG.main(GFG.java:22)
shivnagarsoge
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
4 Dimensional Array in C/C++

A 4 dimensional array is an array of 3Darrays.
Begin.
   Declare the variables.
   Declare the array elements.
   Take the no of elements as input.
   Take the elements as input.
   Print the elements stored in array.
End.
Here is an example of 4D array.
#include<iostream>
using namespace std;
int main() {
   int a[2][2][3][2];
   cout << "Enter the elements of array: \n";
   for(int i = 0; i < 2; ++i) {
      for (int j = 0; j < 2; ++j) {
         for(int k = 0; k < 3; ++k ) {
            for(int l = 0; l < 2; ++l ) {
               cin >> a[i][j][k][l];
            }
         }
      }
   }
   cout<<"\narray elements are stored as:"<<endl;
   for(int i = 0; i < 2; ++i) {
      for (int j = 0; j < 2; ++j) {
         for(int k = 0; k < 3; ++k) {
            for(int l = 0; l < 2; ++l) {
               cout << "a[" << i << "][" << j << "][" << k << "] [" <<l<<"]= " << a[i][j][k][l] << endl;
            }
         }
      }
   }
   return 0;
}
Enter the elements of array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

array elements are stored as:
a[0][0][0] [0]= 1
a[0][0][0] [1]= 2
a[0][0][1] [0]= 3
a[0][0][1] [1]= 4
a[0][0][2] [0]= 5
a[0][0][2] [1]= 6
a[0][1][0] [0]= 7
a[0][1][0] [1]= 8
a[0][1][1] [0]= 9
a[0][1][1] [1]= 10
a[0][1][2] [0]= 11
a[0][1][2] [1]= 12
a[1][0][0] [0]= 13
a[1][0][0] [1]= 14
a[1][0][1] [0]= 15
a[1][0][1] [1]= 16
a[1][0][2] [0]= 17
a[1][0][2] [1]= 18
a[1][1][0] [0]= 19
a[1][1][0] [1]= 20
a[1][1][1] [0]= 21
a[1][1][1] [1]= 22
a[1][1][2] [0]= 23
a[1][1][2] [1]= 24
Python | sympy.Rational() method

02 Aug, 2019
With the help of sympy.Rational() method, we can find the rational form of any float value that is passed as parameter in sympy.Rational() method.
Syntax : sympy.Rational(val)Return : Return Rational form of float value.
Example #1 :In this example we can see that by using sympy.Rational() method, we are able to find the rational form of any float value that is passed as parameters.
# import sympyfrom sympy import *  # Using sympy.Rational() methodgfg = Rational(0.2)  print(gfg)
Output :
1/5
Example #2 :
# import sympyfrom sympy import *  # Using sympy.Rational() methodgfg = Rational(0.12)  print(gfg)
Output :
12/100
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.fmin() in Python

28 Nov, 2018
numpy.fmin() function is used to compute element-wise minimum of array elements. This function compare two arrays and returns a new array containing the element-wise minima.
If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned.
Syntax : numpy.fmin(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘fmin’)
Parameters :arr1 : [array_like] The array holding the elements to be compared.arr2 : [array_like] The array holding the elements to be compared.out : [ndarray, optional] A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.**kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional] True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return : [ndarray or scalar] The minimum of arr1 and arr2, element-wise. Returns scalar if both arr1 and arr2 are scalars.
Code #1 : Working
# Python program explaining# fmin() function  import numpy as geekin_num1 = 10in_num2 = 11  print ("Input  number1 : ", in_num1)print ("Input  number2 : ", in_num2)     out_num = geek.fmin(in_num1, in_num2) print ("minimum of 10 and 11 : ", out_num) 
Output :
Input  number1 :  10
Input  number2 :  11
minimum of 10 and 11 :  10

 Code #2 :
# Python program explaining# fmin() function  import numpy as geek  in_arr1 = [2, 8, 125, geek.nan]in_arr2 = [geek.nan, 3, 115, geek.nan]   print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2)    out_arr = geek.fmin(in_arr1, in_arr2) print ("Output array : ", out_arr) 
Output :
Input array1 :  [2, 8, 125, nan]
Input array2 :  [nan, 3, 115, nan]
Output array :  [   2.    3.  115.   nan]

 Code #3 :
# Python program explaining# fmin() function  import numpy as geek  in_arr1 = [2, 8, 125]in_arr2 = [3, 3, 115]      print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2)    out_arr = geek.fmin(in_arr1, in_arr2) print ("Output array: ", out_arr) 
Output :
Input array1 :  [2, 8, 125]
Input array2 :  [3, 3, 115]
Output array:  [  2   3 115]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Byte Objects vs String in Python

24 Jan, 2022
In Python 2, both str and bytes are the same typeByte objects whereas in Python 3 Byte objects, defined in Python 3 are “sequence of bytes” and similar to “unicode” objects from Python 2. However, there are many differences in strings and Byte objects. Some of them are depicted below: `  
Byte objects are sequence of Bytes, whereas Strings are sequence of characters.
Byte objects are in machine readable form internally, Strings are only in human readable form.
Since Byte objects are machine readable, they can be directly stored on the disk. Whereas, Strings need encoding before which they can be stored on disk.
 
There are methods to convert a byte object to String and String to byte objects. 
PNG, JPEG, MP3, WAV, ASCII, UTF-8 etc are different forms of encodings. An encoding is a format to represent audio, images, text, etc in bytes. Converting Strings to byte objects is termed as encoding. This is necessary so that the text can be stored on disk using mapping using ASCII or UTF-8 encoding techniques.This task is achieved using encode(). It take encoding technique as argument. Default technique is “UTF-8” technique. 
Python3
# Python code to demonstrate String encoding # initialising a Stringa = 'GeeksforGeeks' # initialising a byte objectc = b'GeeksforGeeks' # using encode() to encode the String# encoded version of a is stored in d# using ASCII mappingd = a.encode('ASCII') # checking if a is converted to bytes or notif (d==c):    print ("Encoding successful")else : print ("Encoding Unsuccessful")
Output:  
Encoding successful
 
Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it. Encoding and Decoding are inverse processes.  
Python3
# Python code to demonstrate Byte Decoding # initialising a Stringa = 'GeeksforGeeks' # initialising a byte objectc = b'GeeksforGeeks' # using decode() to decode the Byte object# decoded version of c is stored in d# using ASCII mappingd = c.decode('ASCII') # checking if c is converted to String or notif (d==a):    print ("Decoding successful")else : print ("Decoding Unsuccessful")
Output:  
Decoding successful
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
simmytarika5
amartyaghoshgfg
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Python Pandas - Create a time interval and use Timestamps as the bounds

To create a time interval and use Timestamps as the bounds, use pandas.Interval and set timestamp within it using pandas.Timestamp.
At first, import the required libraries −
import pandas as pd
Use Timestamps as the bounds to create a time interval. Closed interval set using the "closed" parameter with value "left"
interval = pd.Interval(pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2021-01-01 00:00:00'), closed='left')
Above, we have used Timestamps as the bounds. Display the interval
print("Interval...\n",interval)
Following is the code
import pandas as pd

# Use Timestamps as the bounds to create a time interval
# closed interval set using the "closed" parameter with value "left"
interval = pd.Interval(pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2021-01-01 00:00:00'), closed='left')

# display the interval
print("Interval...\n",interval)

# display the interval length
print("\nInterval length...\n",interval.length)
This will produce the following code
Interval...
[2020-01-01, 2021-01-01)

Interval length...
366 days 00:00:00
JavaScript Math floor() Method

23 Feb, 2022
Below is the example of the Math floor() Method.  
Example:  
javascript
<script type="text/javascript">         document.write("Result : " + Math.floor(.89));</script>
Output:  
Result : 0
The Math.floor method is used to round off the number passed as a parameter to its nearest integer in Downward direction of rounding i.e. towards the lesser value.Syntax:  
Math.floor(value)
Parameters: This method accepts single parameter asmentioned above and described below:  
Value: It is the value which is to be tested for Math.floor.
Return Value: The Math.floor() method returns the smallest integer greater than or equal to the given number.Below examples illustrate the Math floor() method in JavaScript:  
Example 1:  
Input : Math.floor(.89)
Output: 0
 
Example 2:  
Input :  Math.floor(-89.02)
Output : -90
 
Example 3:  
Input : Math.floor(0)
Output : 0
More codes for the above method are as follows:Program 1: When a negative number is passed as a parameter.  
javascript
<script type="text/javascript">         document.write("Result : " + Math.floor(-89.02));</script>
Output:  
Result : -90
Program 2: When zero is passed as a parameter.  
javascript
<script type="text/javascript">         document.write("Result : " + Math.floor(0));</script>
Output:  
Result : 0
Supported Browsers:  
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
 
sumitgumber28
ysachin2314
javascript-math
JavaScript-Methods
JavaScript
Mathematical
Web Technologies
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Set in C++ Standard Template Library (STL)
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Merge two sorted arrays
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple

19 May, 2022
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple.
Input: [(1, 3), (3, 2), (2, 1)]
Output: [(2, 1), (3, 2), (1, 3)]
Explanation: sort tuple based on the last digit of each tuple.
Methods #1: Using sorted().
Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence.
Approach:
Take a list of tuples from the user.
Define a function that returns the last element of each tuple in the list of tuples.
Define another function with the previous function as the key and sort the list.
Print the sorted list.
Python3
def last(n):    return n[-1]   def sort(tuples):    return sorted(tuples, key=last)  a=[(1, 3), (3, 2), (2, 1)]print("Sorted:")print(sort(a))
Output:
Sorted:
[(2, 1), (3, 2), (1, 3)]
Methods #2: Using Bubble Sort.
Access the last element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).
Python3
# Python program to sort# a list of tuples by the second Item   # Function to sort the list# of tuples by its second itemdef Sort_Tuple(tup):            # getting length of list of tuples    lst = len(tup)     for i in range(0, lst):                    for j in range(0, lst-i-1):             if (tup[j][-1] > tup[j + 1][-1]):                 temp = tup[j]                 tup[j]= tup[j + 1]                 tup[j + 1]= temp     return tup    # Driver Code tup =[(1, 3), (3, 2), (2, 1)]         print(Sort_Tuple(tup))
Output:
[(2, 1), (3, 2), (1, 3)]
Methods #3: Using sort().
The sort() method sorts the elements of a given list in a specific ascending or descending order.
Python3
# Python program to sort a list of# tuples by the second Item using sort()    # Function to sort the list by second item of tupledef Sort_Tuple(tup):        # reverse = None (Sorts in Ascending order)     # key is set to sort using second element of     # sublist lambda has been used     tup.sort(key = lambda x: x[-1])     return tup    # Driver Code tup = [(1, 3), (3, 2), (2, 1)]   # printing the sorted list of tuplesprint(Sort_Tuple(tup)) 
Output:
[(2, 1), (3, 2), (1, 3)]
sumitgumber28
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
numpy.floor() in Python

04 Dec, 2020
The numpy.floor) is a mathematical function that returns the floor of the elements of array. The floor of the scalar x is the largest integer i, such that i <= x.
Syntax : numpy.floor(x[, out]) = ufunc ‘floor’)Parameters :a : [array_like] Input array
Return : The floor of each element.
 Code #1 : Working
# Python program explaining# floor() function  import numpy as np  in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array)  flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values)    in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array)  flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values)  in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array)  flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values)
Output :
Input array : 
 [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values : 
 [  0.   1.   2.   3.   4.  10.]

Input array : 
 [0.53, 1.54, 0.71]

Rounded values : 
 [ 0.  1.  0.]

Input array : 
 [0.5538, 1.33354, 0.71445]

Rounded values : 
 [ 0.  1.  0.]
 
Code #2 : Working
# Python program explaining# floor() functionimport numpy as np  in_array = [1.67, 4.5, 7, 9, 12]print ("Input array : \n", in_array)  flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values)    in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print ("\nInput array : \n", in_array)  flooroff_values = np.floor(in_array)print ("\nRounded values upto 2: \n", flooroff_values)
Output :
Input array : 
 [1.67, 4.5, 7, 9, 12]

Rounded values : 
 [  1.   4.   7.   9.  12.]

Input array : 
 [133.0, 344.54, 437.56, 44.9, 1.2]

Rounded values upto 2: 
 [ 133.  344.  437.   44.    1.]

 References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.floor.html#numpy.floor.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
Program for Gauss Seidel Method (Computational Mathematics)

24 Oct, 2021
The Gauss Seidel method is an iterative process to solve a square system of (multiple) linear equations. It is also prominently known as ‘Liebmann’ method. In any iterative method in numerical analysis, every solution attempt is started with an approximate solution of an equation and iteration is performed until the desired accuracy is obtained. In Gauss-Seidel method, the most recent values are used in successive iterations. The Gauss-Seidel Method allows the user to control round-off error.The Gauss Seidel method is very similar to Jacobi method and is called as the method of successive displacement. (Since recently obtained values are used in the subsequent equations). The Gauss Seidel convergence criteria depend upon the following two properties: (must be satisfied).  
The matrix is diagonally dominant.
The matrix is symmetrical and positive.
Steps involved:  
Step 1: Compute value for all the linear equations for Xi. (Initial array must be available)
Step 2: Compute each Xi and repeat the above steps.
Step 3: Make use of the absolute relative approximate error after every step to check if the error occurs within a pre-specified tolerance.
Code for Gauss Seidel method:  
C
#include <stdio.h> int main(){    int count, t, limit;    float temp, error, a, sum = 0;    float matrix[10][10], y[10], allowed_error;         printf("\nEnter the Total Number of Equations:\t");    scanf("%d", & limit);    // maximum error limit till which errors are considered,    // or desired accuracy is obtained)         printf("Enter Allowed Error:\t");    scanf("%f", & allowed_error);    printf("\nEnter the Co-Efficients\n");         for(count = 1; count < = limit; count++)    {        for(t = 1; t < = limit + 1; t++)        {            printf(" Matrix[%d][%d] = " , count, t);            scanf(" %f" , & matrix[count][t]);        }    }         for(count = 1; count < = limit; count++)    {        y[count] = 0;    }    do    {        a = 0;        for(count = 1; count < = limit; count++)        {            sum = 0;            for(t = 1; t  a)            {                a = error;            }            y[count] = temp;            printf("\nY[%d]=\t%f", count, y[count]);        }        printf("\n");    }    while(a > = allowed_error);         printf("\n\nSolution\n\n");         for(count = 1; count < = limit; count++)    {        printf(" \nY[%d]:\t%f" , count, y[count]);    }    return 0;}
Output:  
Enter the Total Number of Equations:   1
Enter Allowed Error:   0.5

Enter the Co-Efficients
Matrix[1][1] = 1
Matrix[1][2] = 4

Y[1]=   4.000000

Y[1]=   4.000000

Solution

Y[1]:   4.000000  
Advantages:  
Faster iteration process. (than other methods)
Simple and easy to implement.
Low on memory requirements.
Disadvantages:  
Slower rate of convergence. (than other methods)
Requires a large number of iterations to reach the convergence point.
 
clintra
sooda367
Articles
Engineering Mathematics
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 12 - GeeksforGeeks

28 Jun, 2021
A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations enQueue and deQueue can be performed in constant time? (GATE 2004)
(A) rear node(B) front node(C) not possible with a single pointer(D) node next to frontAnswer: (A)Explanation: Answer is not “(b) front node”, as we can not get rear from front in O(1), but if p is rear we can implement both enQueue and deQueue in O(1) because from rear we can get front in O(1). Below are sample functions. Note that these functions are just sample are not working. Code to handle base cases is missing.
/* p is pointer to address of rear (double pointer).  This function adds new    node after rear and updates rear which is *p to point to new node  */void  enQueue(struct node **p, struct node *new_node){    /* Missing code to handle base cases like *p is NULL */            new_node->next = (*p)->next;     (*p)->next = new_node;     (*p) = new_node /* new is now rear */     /* Note that p->next is again front and  p is rear */   }  /* p is pointer to rear. This function removes the front element and     returns the dequeued element from the queue */struct node *deQueue(struct node *p){    /* Missing code to handle base cases like p is NULL,        p->next is NULL,...  etc */      struct node *temp = p->next;    p->next = p->next->next;    return temp;    /* Note that p->next is again front and  p is rear */}
Quiz of this QuestionQuiz of this Question
harshilmarwah
amansinghrocks81
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Tree Traversals | Question 4
Data Structures | Graph | Question 9
Data Structures | Stack | Question 1
Binary Search Tree | Set 3 (Iterative Delete)
Program to create Custom Vector Class in C++
Data Structures | Hash | Question 5
Encryption and Decryption of String according to given technique
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Data Structures | Tree Traversals | Question 5
Data Structures | Tree Traversals | Question 8
Concatenate two columns of Pandas dataframe - GeeksforGeeks

01 Aug, 2020
Let’s discuss how to Concatenate two columns of dataframe in pandas python. We can do this by using the following functions :
concat()
append()
join()
Example 1 : Using the concat() method.
# importing the moduleimport pandas as pd  # creating 2 DataFrameslocation = pd.DataFrame({'area': ['new-york', 'columbo', 'mumbai']})food = pd.DataFrame({'food': ['pizza', 'crabs', 'vada-paw']})  # concatenating the DataFramesdet = pd.concat([location, food], join = 'outer', axis = 1)  # displaying the DataFrameprint(det)
Output :
Example 2 : Using the append() method.
# importing the moduleimport pandas as pd  # creating 2 DataFramesfirst = pd.DataFrame([['one', 1], ['three', 3]], columns =['name', 'word'])second = pd.DataFrame([['two', 2], ['four', 4]], columns =['name', 'word'])  # concatenating the DataFramesdt = first.append(second, ignore_index = True)  # displaying the DataFrameprint(dt)
Output :
Example 3 : Using the .join() method.
# importing the moduleimport pandas as pd  # creating 2 DataFrameslocation = pd.DataFrame({'area' : ['new-york', 'columbo', 'mumbai']})food = pd.DataFrame({'food': ['pizza', 'crabs', 'vada-paw']})  # concatenating the DataFramesdt = location.join(food)  # displaying the DataFrameprint(dt)
Output :
For the three methods to concatenate two columns in a DataFrame, we can add different parameters to change the axis, sort, levels etc.
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
numpy.logical_and() in Python - GeeksforGeeks

29 Nov, 2018
numpy.logical_and(arr1, arr2, out=None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘logical_and’) : This is a logical function and it helps user to find out the truth value of arr1 AND arr2 element-wise. Both the arrays must be of same shape.
Parameters :
arr1 : [array_like]Input array.arr2 : [array_like]Input array.
out : [ndarray, optional]Output array with same dimensions as Input array, placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return :
An array with Boolean results of arr1 and arr2 element-wise(of the same shape).  

 Code 1 : Working
# Python program explaining# logical_and() functionimport numpy as np  # inputarr1 = [1, 3, False, 4]arr2 = [3, 0, True, False]  # outputout_arr = np.logical_and(arr1, arr2)  print ("Output Array : ", out_arr)
Output :
Output Array :  [ True False False False]

 Code 2 : Value Error if input array’s have different shapes
# Python program explaining# logical_and() functionimport numpy as np  # inputarr1 = [8, 2, False, 4]arr2 = [3, 0, True, False, 8]  # outputout_arr = np.logical_and(arr1, arr2)  print ("Output Array : ", out_arr)
Output :
ValueError:operands could not be broadcast together with shapes (4,) (5,) 
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_and.html#numpy.logical_and.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
sum() function in Python
How to Use write.table in R? - GeeksforGeeks

19 Dec, 2021
In this article, we will learn how to use the write.table() in the R Programming Language. The write.table() function is used to export a dataframe or matrix to a file in the R Language. This function converts a dataframe into a text file in the R Language and can be used to write dataframe into a variety of space-separated files for example CSV( comma separated values) files.
Syntax:
write.table( df, file)
where:
df: determines the dataframe to be converted.
file: determines the file name to write data into with full path.
Example:
Here, we will write a dataframe into a space-separated text file in the R Language by using write.table().
R
# create sample dataframesample_data <- data.frame( name= c("Geeks1", "Geeks2", "Geeks3",                                   "Geeks4", "Geeks5", "Geeks6"),                           value= c( 11, 15, 10, 23, 32, 53 ) )  # write dataframe into a space separated text filewrite.table( sample_data, file='sample.txt')
Output:
To write a dataframe into a text file separated by a manual symbol, we use the sep parameter to determine the symbol that separates the data in the text file. In this way, we can write comma-separated-values, tab-separated values, etc.
Syntax:
write.table( df, file, sep)
where:
df: determines the dataframe to be converted.
file: determines the file name to write data into with full path.
sep: determines with a symbol for separation.  Default is a space.
Example:
Here, we will write a dataframe into a comma-separated text file in the R Language by using write.table() function with sep parameter.
R
# create sample dataframesample_data <- data.frame( name= c("Geeks1", "Geeks2", "Geeks3",                                   "Geeks4", "Geeks5", "Geeks6"),                           value= c( 11, 15, 10, 23, 32, 53 ) )  # write dataframe into a space separated text filewrite.table( sample_data, file='sample.txt', sep=",")
Output:
Picked
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
Path Testing in Software Engineering - GeeksforGeeks

02 Jul, 2020
Path Testing is a method that is used to design the test cases. In path testing method, the control flow graph of a program is designed to find a set of linearly independent paths of execution. In this method Cyclomatic Complexity is used to determine the number of linearly independent paths and then test cases are generated for each path.
It give complete branch coverage but achieves that without covering all possible paths of the control flow graph. McCabe’s Cyclomatic Complexity is used in path testing. It is a structural testing method that uses the source code of a program to find every possible executable path.
Path Testing Process:
Control Flow Graph:Draw the corresponding control flow graph of the program in which all the executable paths are to be discovered.
Cyclomatic Complexity:After the generation of the control flow graph, calculate the cyclomatic complexity of the program using the following formula.McCabe's Cyclomatic Complexity = E - N + 2P

Where, 
E = Number of edges in control flow graph
N = Number of vertices in control floe graph
P = Program factor 
McCabe's Cyclomatic Complexity = E - N + 2P

Where, 
E = Number of edges in control flow graph
N = Number of vertices in control floe graph
P = Program factor 
Make Set:Make a set of all the path according to the control floe graph and calculated cyclomatic complexity. The cardinality of set is equal to the calculated cyclomatic complexity.
Create Test Cases:Create test case for each path of the set obtained in above step.
Path Testing Techniques:
Control Flow Graph:The program is converted into control flow graph by representing the code into nodes and edges.
Decision to Decision path:The control flow graph can be broken into various Decision to Decision paths and then collapsed into individual nodes.
Independent paths:Independent path is a path through a Decision to Decision path graph which cannot be reproduced from other paths by other methods.Advantages of Path Testing:Path testing method reduces the redundant tests.Path testing focuses on the logic of the programs.Path testing is used in test case design.My Personal Notes
arrow_drop_upSave
Advantages of Path Testing:
Path testing method reduces the redundant tests.Path testing focuses on the logic of the programs.Path testing is used in test case design.
Path testing method reduces the redundant tests.
Path testing focuses on the logic of the programs.
Path testing is used in test case design.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Software Engineering | Classical Waterfall Model
Differences between Verification and Validation
Software Testing | Basics
Software Requirement Specification (SRS) Format
Levels in Data Flow Diagrams (DFD)
Difference between Alpha and Beta Testing
Software Engineering | White box Testing
Software Engineering | Seven Principles of software testing
Software Engineering | Integration Testing
PLSQL | CURRENT_TIMESTAMP Function - GeeksforGeeks

24 Oct, 2019
The PLSQL CURRENT_TIMESTAMP function is used to return the current date and time in session time zone. The time zone used is the time zone of the current SQL session as set by the ALTER SESSION command. The CURRENT_TIMESTAMP function returns a value of TIMESTAMP WITH TIME ZONE while the CURRENT_DATE function returns a value of DATE without time zone data.The CURRENT_TIMESTAMP function accepts no parameters.
Syntax:
CURRENT_TIMESTAMP
Parameters Used:The CURRENT_TIMESTAMP function accepts no parameters.
Return Value:The CURRENT_TIMESTAMP function returns a value of the current timestamp in TIMESTAMP WITH TIME ZONE data type.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1: Using the CURRENT_TIMESTAMP function to show the current timestamp in the session time zone.
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT
  CURRENT_TIMESTAMP
FROM
  dual; 
Output:
Session altered.

CURRENT_TIMESTAMP
22-OCT-19 07.28.32.374935 AM +00:00 
Example-2: Using the CURRENT_TIMESTAMP function to show the current timestamp using altered session time zone.
ALTER SESSION SET TIME_ZONE = '-10:00';

SELECT
  CURRENT_TIMESTAMP
FROM
  dual; 
Output:
Session altered.

CURRENT_TIMESTAMP
21-OCT-19 09.31.40.273270 PM -10:00 
The new date and time was adjusted about -10 hours as expected.
Advantage:The CURRENT_TIMESTAMP function returns a value of TIMESTAMP WITH TIME ZONE while the CURRENT_DATE function returns a value of DATE without time zone data.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
Python | Pandas Series.divide()

15 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.divide() function performs floating division of series and other, element-wise (binary operator truediv). It is equivalent to series / other, but with support to substitute a fill_value for missing data in one of the inputs.
Syntax: Series.divide(other, level=None, fill_value=None, axis=0)
Parameter :other : Series or scalar valuefill_value : Fill existing missing (NaN) values.level : Broadcast across a level, matching Index values on the passed MultiIndex level
Returns : result : Series
Example #1: Use Series.divide() function to perform floating division of the given series object with a scalar.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.divide() function to perform floating division of the given series object with a scalar.
# perform floating divisionresult = sr.divide(other = 2)  # Print the resultprint(result)
Output :As we can see in the output, the Series.divide() function has successfully performed the floating division of the given series object with a scalar. Example #2 : Use Series.divide() function to perform floating division of the given series object with a scalar. The given series object contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.divide() function to perform floating division of the given series object with a scalar. We are going to fill 50 at the place of all the missing values.
# perform floating division# fill 50 at the place of missing valuesresult = sr.divide(other = 2, fill_value = 50)  # Print the resultprint(result)
Output :
As we can see in the output, the Series.divide() function has successfully performed the floating division of the given series object with a scalar.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python