code-rag-bench/online-tutorials huggingface dataset:
Multidimensional Array in R

22 Apr, 2020
Arrays are the R data objects which can store data in more than two dimensions. For example: If we create an array of dimensions (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. These types of arrays are called Multidimensional Arrays. Arrays can store only data types.
An array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array. A multidimensional array can be created by defining the value of ‘dim‘ argument as the number of dimensions that are required.
Syntax:
MArray = array(c(vec1, vec2), dim)

Examples:
# Create two vectors of different lengths.vector1 <- c(5, 9, 3)vector2 <- c(10, 11, 12, 13, 14, 15)  # Take these vectors as input to the array.result <- array(c(vector1, vector2), dim = c(3, 3, 2))print(result)
Output:
, , 1

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

, , 2

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

We can give names to the rows, columns, and matrices in the array by using the dimnames parameter.
Example:
# Create two vectors of different lengths.vector1 <- c(5, 9, 3)vector2 <- c(10, 11, 12, 13, 14, 15)column.names <- c("COL1", "COL2", "COL3")row.names <- c("ROW1", "ROW2", "ROW3")matrix.names <- c("Matrix1", "Matrix2")  # Take these vectors as input to the array.result <- array(c(vector1, vector2), dim = c(3, 3, 2),                  dimnames = list(row.names, column.names,                  matrix.names))print(result)
Output:
, , Matrix1

     COL1 COL2 COL3
ROW1    5   10   13
ROW2    9   11   14
ROW3    3   12   15

, , Matrix2

     COL1 COL2 COL3
ROW1    5   10   13
ROW2    9   11   14
ROW3    3   12   15

As the array is made up of matrices in multiple dimensions, the operations on elements of the array are carried out by accessing elements of the matrices. There are various different Operations can be performed on Arrays.
Example:
# Create two vectors of different lengths.vector1 <- c(5, 9, 3)vector2 <- c(10, 11, 12, 13, 14, 15)  # Take these vectors as input to the array.array1 <- array(c(vector1, vector2), dim = c(3, 3, 2))  # Create two vectors of different lengths.vector3 <- c(9, 1, 0)vector4 <- c(6, 0, 11, 3, 14, 1, 2, 6, 9)array2 <- array(c(vector1, vector2), dim = c(3, 3, 2))  # create matrices from these arrays.matrix1 <- array1[,,2]matrix2 <- array2[,,2]  # Add the matrices.result <- matrix1 + matrix2print(result)
Output:
     [,1] [,2] [,3]
[1,]   10   20   26
[2,]   18   22   28
[3,]    6   24   30

Picked
R-Arrays
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Creating a Data Frame from Vectors in R Programming
numpy.array_equal() in Python

29 Nov, 2018
numpy.array_equal(arr1, arr2) : This logical function that checks if two arrays have the same shape and elements.
Parameters :
arr1    : [array_like]Input array or object whose elements, we need to test.
arr2    : [array_like]Input array or object whose elements, we need to test.

Return :
True, if both arrays have same shape and value; otherwise False

 Code : Explaining Working
# Python program explaining# array_equal() functionimport numpy as np  # inputarr1 = np.arange(4)arr2 = [7, 4, 6, 7]print ("arr1 : ", arr1)print ("arr2 : ", arr2)  print ("\nResult : ", np.array_equal(arr1, arr2))  arr1 = np.arange(4)arr2 = np.arange(4)print ("\n\narr1 : ", arr1)print ("arr2 : ", arr2)  print ("\nResult : ", np.array_equal(arr1, arr2))  arr1 = np.arange(4)arr2 = np.arange(5)print ("\n\narr1 : ", arr1)print ("arr2 : ", arr2)  print ("\nResult : ", np.array_equal(arr1, arr2))
Output :
arr1 :  [0 1 2 3]
arr2 :  [7, 4, 6, 7]

Result :  False


arr1 :  [0 1 2 3]
arr2 :  [0 1 2 3]

Result :  True


arr1 :  [0 1 2 3]
arr2 :  [0 1 2 3 4]

Result :  False

References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array_equal.html.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to validate a Date in ReactJS?

16 Dec, 2020
Data validation is an important step in every application in order to authenticate the user’s entered data which can be used to calculate the date of birth or any other use. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app datevalidatedemo
Step 2: After creating your project folder i.e. datevalidatedemo, move to it using the following command:
cd datevalidatedemo
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to validate the date with basic UI.
Javascript
import React, { useState } from "react";import validator from 'validator'  const App = () => {    const [errorMessage, setErrorMessage] = useState('')      const validateDate = (value) => {        if (validator.isDate(value)) {      setErrorMessage('Valid Date :)')    } else {      setErrorMessage('Enter Valid Date!')    }  }    return (    <div style={{      marginLeft: '200px',    }}>      <pre>        <h2>Validating Date in ReactJS</h2>        <span>Enter Date: </span><input type="text"         onChange={(e) => validateDate(e.target.value)}></input> <br />        <span style={{          fontWeight: 'bold',          color: 'red',        }}>{errorMessage}</span>      </pre>    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters an invalid date as shown below:
The following will be the output if the user enters a valid date as shown below:
react-js
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | usort() Function

01 Jun, 2020
PHP comes with a number of built-in functions that are used to sort arrays in an easier way. Here, we are going to discuss a new function usort(). The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
Syntax:
boolean usort( $array, "function_name");

Parameters: This function accepts two parameters as shown in the above syntax and are described below:
$array: This parameter specifies the array which u want to sort.function_name : This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two arguments are equal, then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.
$array: This parameter specifies the array which u want to sort.
function_name : This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two arguments are equal, then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.
Return Value: This function returns the boolean type of value. It returns TRUE in case of success and FALSE in case of failure.
Below program illustrate the usort() function in PHP:
<?php      // PHP program to illustrate usort() function      // This is the user-defined function used to compare    // values to sort the input array    function comparatorFunc( $x, $y)    {           // If $x is equal to $y it returns 0        if ($x== $y)            return 0;              // if x is less than y then it returns -1        // else it returns 1            if ($x < $y)            return -1;        else            return 1;    }          // Input array    $arr= array(2, 9, 1, 3, 5);       usort($arr, "comparatorFunc");          print_r($arr);  ?>
Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 9
)

Reference:http://php.net/manual/en/function.usort.php
Akanksha_Rai
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create horizontal legend using ggplot2 in R?

The default legend direction is vertical but it can be changed to horizontal as well and for this purpose we can use legend.direction argument of theme function of ggplot2 package. For example, if we want to create a bar chart with x as categories and y as frequencies tjat are contained in a data frame df then the bar chart with horizontal legends for categories in x can be created as −
ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.direction="horizontal")
Consider the below data frame −
Live Demo
> x<-c("A","B","C")
> y<-c(27,25,28)
> df<-data.frame(x,y)
> df
x y
1 A 27
2 B 25
3 C 28
Loading ggplot2 package and creating the bar chart −
> library(ggplot2)
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")
Creating the chart with horizontal legend −
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.direction="horizontal")
Counting number of paragraphs in text file using java


We can read paragraphs in a file by reading it in a string and then spilting based on "\r\n" pattern. See the example below −
Consider the following text file in the classpath.
test.txt
This is Line 1

This is Line 2
This is Line 3

This is Line 4
This is Line 5

This is Line 6
This is Line 7

This is Line 8
This is Line 9
This is Line 10
Tester.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Tester {
   public static void main(String args[]) throws IOException {
      FileUtil fileUtil = new FileUtil();
      System.out.println("No. of paragraphs in file: " + fileUtil.getParaCount());
   }
}

class FileUtil {
   private static final String FILE_PATH = "data.txt";
   
   public static int getParaCount() throws IOException {
      File file = new File(FILE_PATH);
      FileInputStream fileStream = new FileInputStream(file);
      byte[] byteArray = new byte[(int)file.length()];
      fileStream.read(byteArray);
      String data = new String(byteArray);

      String[] paragraphs = data.toString().split("\r\n\r\n");

      return paragraphs.length;
   }
}
This will produce the following result −
No. of paragraphs in file: 5
numpy.eye() in Python - GeeksforGeeks

04 Aug, 2021
numpy.eye(R, C = None, k = 0, dtype = type <‘float’>) : –The eye tool returns a 2-D array with  1’s as the diagonal and  0’s elsewhere. The diagonal can be main, upper, or lower depending on the optional parameter k. A positive k is for the upper diagonal, a negative k is for the lower, and a  0 k (default) is for the main diagonal.
Parameters : 
R : Number of rows
C : [optional] Number of columns; By default M = N
k : [int, optional, 0 by default]
          Diagonal we require; k>0 means diagonal above main diagonal or vice versa.
dtype : [optional, float(by Default)] Data type of returned array.  
Returns : 
array of shape, R x C, an array where all elements 
are equal to zero, except for the k-th diagonal, 
whose values are equal to one.
Example:
Python
# Python Programming illustrating# numpy.eye method import numpy as geek # 2x2 matrix with 1's on main diagonalb = geek.eye(2, dtype = float)print("Matrix b : \n", b) # matrix with R=4 C=5 and 1 on diagonal# below main diagonala = geek.eye(4, 5, k = -1)print("\nMatrix a : \n", a)
Output : 
Matrix b : 
 [[ 1.  0.]
 [ 0.  1.]]

Matrix a : 
 [[ 0.  0.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]]
Note : These codes won’t run on online-ID. Please run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . 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. 
anshitaagarwal
gabaa406
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
acos() function in C++ STL

The acos() function returns the inverse cosine of an angle given in radians. It is an inbuilt function in C++ STL.
The syntax of the acos() function is given as follows.
acos(var)
As can be seen from the syntax, the function acos() accepts a parameter var of data type float, double or long double. The value of this parameter should be between -1 and 1. It returns the inverse cosine of var in the range of -pi to pi.
A program that demonstrates acos() in C++ is given as follows.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   double d = 0.75, ans;
   ans = acos(d);
   cout << "acos("<< d <<") = " << ans << endl;
   return 0;
}
acos(0.75) = 0.722734
In the above program, first the variable d is initialized. Then inverse cosine of d is found using acos() and stored in ans. Finally the value of ans is displayed. This is demonstrated by the following code snippet.
double d = 0.75, ans;
ans = acos(d);
cout << "acos("<< d <<") = " << ans << endl;
The result obtained by using the acos() function can be converted into degrees and displayed. A program to demonstrate this is as follows.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   double d = 0.75, ans;
   ans = acos(d);
   ans = ans*180/3.14159;
   cout << "acos("<< d <<") = " << ans << endl;
   return 0;
}
acos(0.75) = 41.4097
In the above program, the inverse cosine is obtained using acos(). Then this value is converted into degrees. Finally, the output is displayed. This is demonstrated by the following code snippet.
double d = 0.75, ans;
ans = acos(d);
ans = ans*180/3.14159;
cout << "acos("<< d <<") = " << ans << endl;
Spring Boot - Quick Start

This chapter will teach you how to create a Spring Boot application using Maven and Gradle.
Your system need to have the following minimum requirements to create a Spring Boot application −
Java 7
Maven 3.2
Gradle 2.5
The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This is the easiest way to create a Spring Boot application by using the Spring Boot Command Line Interface. You can create, run and test the application in command prompt itself.
This section explains you the steps involved in manual installation of Spring Boot CLI. For further help, you can use the following link: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot 
You can also download the Spring CLI distribution from the Spring Software repository at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation
For manual installation, you need to use the following two folders −
spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip
spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip
spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz
spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz
After the download, unpack the archive file and follow the steps given in the install.txt file. Not that it does not require any environment setup.
In Windows, go to the Spring Boot CLI bin directory in the command prompt and run the command spring –-version to make sure spring CLI is installed correctly. After executing the command, you can see the spring CLI version as shown below −
Create a simple groovy file which contains the Rest Endpoint script and run the groovy file with spring boot CLI. Observe the code shown here for this purpose −
@Controller
class Example {
   @RequestMapping("/")
   @ResponseBody
   public String hello() {
      "Hello Spring Boot"
   }
}
Now, save the groovy file with the name hello.groovy. Note that in this example, we saved the groovy file inside the Spring Boot CLI bin directory. Now run the application by using the command spring run hello.groovy as shown in the screenshot given below −
Once you run the groovy file, required dependencies will download automatically and it will start the application in Tomcat 8080 port as shown in the screenshot given below −
Once Tomcat starts, go to the web browser and hit the URL http://localhost:8080/ and you can see the output as shown.

    102 Lectures 
     8 hours 

 Karthikeya T

    39 Lectures 
     5 hours 

 Chaand Sheikh

    73 Lectures 
     5.5 hours 

 Senol Atac

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac

    69 Lectures 
     5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python program to Get Month Name from Month Number - GeeksforGeeks

09 May, 2021
Given a datetime object or month number, the task is to write a Python program to get the corresponding month name from it. 
Examples:
Input : test_date = datetime(2020, 4, 8)
Output : April
Explanation : 4th Month is April.
Input : test_date = datetime(2020, 1, 8)
Output : January
Explanation : 1st Month is January.
In this, we use strftime() which converts date object to a string using a format, and by providing %B, it’s enforced to just return a Month Name.
Python3
# Python3 code to demonstrate working of# Get Month Name from Month Number# Using strftime() + %Bfrom datetime import datetime  # initializing datetest_date = datetime(2020, 4, 8)               # printing original dateprint("The original date is : " + str(test_date))  # getting month name using %Bres = test_date.strftime("%B")  # printing resultprint("Month Name from Date : " + str(res))
Output:
The original date is : 2020-04-08 00:00:00
Month Name from Date : April
In this variant, rather than having datetime object as input, the month name as an input is accepted and the result is the month name returned.
Python3
# Python3 code to demonstrate working of# Get Month Name from Month Number# Using calendar library and month numberimport calendar  # initializing month numbertest_num = 5               # printing original month numberprint("The original month number is : " + str(test_num))  # using month_name() to get month name res = calendar.month_name[test_num]  # printing resultprint("Month Name from Number : " + str(res))
Output:
The original month number is : 5
Month Name from Number : May
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to change the background color using jQuery?

To change the background color using jQuery, use the jQuery css() property. We will change background color on mouse hover with the jQuery on() and css() method. 
You can try to run the following code to learn how to change background color using jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("body").on({
        mouseenter: function(){
            $(this).css("background-color", "gray");
        },  
       
        mouseleave: function(){
            $(this).css("background-color", "red");
        },
       
        dblclick: function(){
            $(this).css("background-color", "yellow");
        }
    });
});
</script>
</head>
<body>

<p>Double click and move the mouse pointer to change the background color.</p>

</body>
</html>
Finding The Biggest Key In A Python Dictionary?

If you have a dict with string-integer mappings, you can use the max method on the dictionary's item pairs to get the largest value. 
d = {
   'foo': 100,
   'bar': 25,
   'baz': 360
}
print(max(k for k, v in d.items()))
This will give the output −
foo
foo is largest in alphabetical order.
C++ program for length of a string using recursion

Given with the string and the task is to calculate the length of the given string using a user defined function or in-built function.
Length of a string can be calculated using two different ways −
Using user defined function − In this, traverse the entire string until ‘\o’ is found and keep incrementing the value by 1 through recursive call to a function.
Using user in-build function − There is an in-build function strlen() defined within “string.h” header file which is used for calculating the length of a string. This function takes single argument of type string and return integer value as length.
Input-: str[] = "tutorials point"
Output-: length of string is 15
Explanation-: in the string “tutorials point” there are total 14 characters and 1 space making it a total of length 15.
Start
Step 1-> declare function to find length using recursion
   int length(char* str)
      IF (*str == '\0')
         return 0
      End
      Else
      return 1 + length(str + 1)
   End
Step 2-> In main()
   Declare char str[] = "tutorials point"
   Call length(str)
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//recursive function for length
int length(char* str) {
   if (*str == '\0')
      return 0;
   else
      return 1 + length(str + 1);
}
int main() {
   char str[] = "tutorials point";
   cout<<"length of string is : "<<length(str);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
length of string is : 15
TypeScript - Array pop()

pop() method removes the last element from an array and returns that element.
array.pop();

Returns the removed element from the array.
var numbers = [1, 4, 9]; 
          
var element = numbers.pop(); 
console.log("element is : " + element );  
          
var element = numbers.pop(); 
console.log("element is : " + element );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
element is : 9 
element is : 4


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Python - Plot a Histogram for Pandas Dataframe with Matplotlib?

Histogram is a representation of the distribution of data. To plot a Histogram, use the hist() method. At first, import both the libraries −
import pandas as pd
import matplotlib.pyplot as plt
Create a DataFrame with 2 columns −
dataFrame = pd.DataFrame({
   "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
})
Plot a Histogram for Registration Price column −
plt.hist(dataFrame["Reg_Price"])
Following is the code −
import pandas as pd
import matplotlib.pyplot as plt

# creating dataframe
dataFrame = pd.DataFrame({
   "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
})

# plot a histogram for Registration Price column
plt.hist(dataFrame["Reg_Price"])
plt.show()
This will produce the following output −
PHP rand() Function

06 Dec, 2021
In this article, we will see how to get the random number using the rand() function in PHP, along with knowing its implementation through the example. The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max].
Syntax:
rand();
The rand() function is used to generate a random integer. To generate a random integer in some range: 
Syntax:
rand(min,max);
Parameter values:
min: It is an optional parameter that specifies the lowest value that will be returned. The default value is 0.
max: It is an optional parameter that specifies the highest value to be returned. The default value is getrandmax().
Return value: This function will return the random integer values ranging from min to getrandmax(), including the max value.
Note: If the min and max value is not specified, default is 0 and getrandmax() respectively.
Example: In this example, we will use the rand() function that will return a random integer between 0 and getrandmax(). The rand(15,35) will return a random integer in the range [15,35].
PHP
<?php      // Generating a random number      $randomNumber = rand();      print_r($randomNumber);      print_r("\n");       // Generating a random number in a      // Specified range.      $randomNumber = rand(15,35);      print_r($randomNumber);?>
Note: The output of the code may change every time it is run. So the output may not match with the specified output. 
Output:
1257424548
28
bhaskargeeksforgeeks
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
TimeSpan.FromSeconds() Method in C#

30 Sep, 2019
This method is used to get a TimeSpan that represents a specified number of seconds, accurate to the nearest millisecond.
Syntax: public static TimeSpan FromSeconds (double value);
Parameter:value: This parameter specifies the number of seconds, accurate to the nearest millisecond..
Return Value: It returns a new TimeSpan object that represents the value.
Exceptions:
OverflowException: When the given double value is smaller than smallest possible value or greater than the largest possible value or the value is PositiveInfinity or is NegativeInfinity.
ArgumentException: When the value is NaN.
Below programs illustrate the use of TimeSpan.FromSeconds(Double) Method:
Example 1:
// C# program to demonstrate the// TimeSpan.FromSeconds(Double)// Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              TimeSpan interval = TimeSpan.FromSeconds(0.43459);            Console.WriteLine("The Timespan is : {0}",                                           interval);        }          catch (OverflowException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
The Timespan is : 00:00:00.4350000

Example 2: For Overflow Exception
// C# program to demonstrate the// TimeSpan.FromSeconds(Double) // Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              TimeSpan interval =              TimeSpan.FromSeconds(Double.NegativeInfinity);              Console.WriteLine("The Timespan is : {0}",                                           interval);        }          catch (OverflowException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.OverflowException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.fromseconds?view=netframework-4.7.2
shubham_singh
CSharp-method
CSharp-TimeSpan-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
Execute both if and else statements in C/C++ simultaneously

06 Jan, 2021
Write a C/C++ program that executes both if-else block statements simultaneously. 
Syntax of if-else statement in C/C++ language is:
if (Boolean expression)
{
    // Statement will execute only 
    // if Boolean expression is true
}
else
{
    // Statement will execute only if 
    // the Boolean expression is false 
}
Hence we can conclude that only one of the block of if-else statement will execute according to the condition of Boolean expression. 
But we can change our code so that both the statements inside the if block and the else block gets executed, for the same condition.
The trick is to use goto statement which provides an unconditional jump from the ‘goto’ to a labeled statement in the same function.
Below is C/C++ program to execute both statements simultaneously:- 
C++
C
#include <bits/stdc++.h>using namespace std;int main(){if (1) // Replace 1 with 0 and see the magic{    label_1: cout <<"Hello ";         // Jump to the else statement after    // executing the above statement    goto label_2;}else{    // Jump to 'if block statement' if    // the Boolean condition becomes false    goto label_1;     label_2: cout <<"Geeks";}return 0;} // this code is contributed by shivanisinghss2110
#include <stdio.h>int main(){  if (1) //Replace 1 with 0 and see the magic  {    label_1: printf("Hello ");         // Jump to the else statement after    // executing the above statement    goto label_2;  }  else  {    // Jump to 'if block statement' if    // the Boolean condition becomes false    goto label_1;     label_2: printf("Geeks");  }  return 0;}
Output:  
Hello Geeks
Therefore both the statements of if and else block executed simultaneously. Another interesting fact can be seen that Output will always remain the same and will not depend upon whether the Boolean condition is true or false.
NOTE – Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. As a programmer, we should avoid the use of goto statement in C/C++.
This blog is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
HimanshuMishra9
shivanisinghss2110
c-puzzle
CPP-Basics
cpp-puzzle
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.irr() in Python

23 Aug, 2021
numpy.irr(values) : This financial function helps user to compute IRR Value i.e. Internal Rate of Return ie. “average” periodically compounded rate of return. 
 
Parameters : values : [array-like] Input cash flows per time period. net “deposits” are negative and net “withdrawals” are positiveReturn : Internal Rate of Return for periodic input values.
Code: 
Python3
# Python program explaining# irr() function import numpy as np'''Question :     Investment = 500    Withdrawls at regular interval : 50, 31, 3, 11''' Solution = np.irr([-500, 50, 31, 3, 11]) print("Solution - Internal Rate of Return : ", Solution)
Output: 
Solution - Internal Rate of Return :  -0.5296447721512683 
sumitgumber28
Python numpy-Financial Functions
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
Lodash _.mapKeys() Method

13 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.mapKeys() method is used to create an object with the same values as the object and the keys created by running each of the object’s own enumerable string keys.
Syntax:
_.mapKeys( object, iteratee )

Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the object to iterate over.
iteratee: It is the function that is invoked per iteration.
Return Value: This method returns the new mapped object.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");  // Using the _.mapKeys() method console.log(  _.mapKeys({ 'cpp': 15, 'java': 40, 'python': 63 },      function(value, key) {          return  key + value ;  }));
Output:
{'cpp15': 15, 'java40': 40, 'python63': 63}

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source objectvar info = {  'GFG': { 'user': 'amit', 'age': 23 },  'codechef': { 'user': 'priya', 'age': 21 }};  // Using the _.mapKeys() method console.log(_.mapKeys(info,  function(o) { return o.age; }));
Output:
{21: {'age': 21, 'user': "priya"}, 23: {'age': 23, 'user': "amit"}}

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Do Until Loop in Excel VBA? - GeeksforGeeks

28 Jul, 2021
In this article, we are going to see look into the Do Until loop in Excel VBA using a suitable example.
In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. 
The Developer Tab can be enabled easily by a two-step process :
Right-click on any of the existing tabs in the top of the Excel window.
Now select Customize the Ribbon from the pop-down menu.
In the Excel Options Box, check the box Developer to enable it and click on OK.
Now, the Developer Tab is visible.
Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement.
Developer  -> Visual Basic -> Tools -> Macros
Now create a Macro and give any suitable name.
This will open the Editor window where can write the code.
In Do Until loop the condition is checked. The statements inside the loop are executed when the condition becomes FALSE. When the condition becomes TRUE, the loop terminates. In the case of a Do Until we can write the condition either in the beginning or at the end. There are two possible syntaxes in the case of Do Until Loop. The keyword Do is used to perform the tasks until certain criteria are met. 
The syntax is :
Do Until condition/expression
    Statement 1
    Statement 2
    Statement 3
    ...
    Statement n
Loop
An alternate syntax is :
Do
    Statement 1
    Statement 2
    Statement 3
    ...
    Statement n
Loop Until Condition/expression
Flow Diagram :
Example : Print the age of all the employees in an organization whose age falls between thirty to forty years.
Code :
Sub Do_Until_Age_Emp()
'Initialize and declare the age of the employee
Dim Age As Integer: Age = 30
'Condition to print the age of employees between 30 to 40 years
Do Until Age > 38
    Age = Age + 1
    MsgBox ("Age:" & Age)
Loop
End Sub
In the above code, the condition is Do Until Age > 38. It will execute the age of employees from 31 to 39 years because when the age becomes 39 the condition becomes TRUE and the loop terminates. In the Excel message box we get the ages of the employees between 30 to 40 years.
Output :
Age : 31
Age : 32
Age : 33
Age : 34
Age : 35
Age : 36
Age : 37
Age : 38
Age : 39
Similarly, the above code can also be written as :
Sub Do_Until_Age_Emp()
'Initialize and declare the age of the employee
Dim Age As Integer: Age = 30
'Start of Do Until Loop
Do
    Age = Age + 1
    MsgBox ("Age:" & Age)
Loop Until Age > 38        'Condition to print the age of employees between 30 to 40 years
End Sub
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Macros in Excel
Using CHOOSE Function along with VLOOKUP in Excel
How to Extract the Last Word From a Cell in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Calculate Deciles in Excel?
How to copy a file, group of files, or directory in Linux?

In this article, we will learn to copy a file or directory in the Linux/Unix operating system using terminal, we use the cp command to copy a file or directory in the Linux system.
cp (copy) - The cp command is used to copy files or directories in the Linux system. If we want to copy a file from a source directory and paste it into another destination directory then we have to use the cp command. By default, the cp command will not copy directories to copy directories we have to use -R option with cp command otherwise error will be prompt.
The general syntax of the cp command is as follows −
cp [OPTION]...[-T] SOURCE DESTINATION
cp [OPTION]...SOURCE DESTINATION
cp [OPTION]...-t DIRECTORY SOURCE...
Brief description of option available in the cp command.
We will copy a file from a directory and paste it into another directory using cp command
$ cp file.txt ../snow
After executing this command files will be copied, to ensure we will change the directory and list the contents of the directory using the below command.
$ cd ../snow
$ ls
file.txt
We will copy all .txt (text) files available in a source directory and paste it into the destination directory using * wildcard with cp command in the Linux system.
$ cp *.txt ../snow
Here, we use the -i option to copy a file from the source directory and paste it into the destination directory if the file is already existing in the destination directory with the same name then a warning message will be prompt before overriding the file.
$ cp -I file1.txt ../shadow
cp: overwrite ‘../shadow/file.txt’? y
Query BinData by Type in MongoDB

To query by type, use subtype() in MongoDB. Let us create a collection with documents −
> db.demo249.insertOne({ "_id" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv") });
{
   "acknowledged" : true,
   "insertedId" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv")
}
> db.demo249.insertOne({"_id" : BinData(4,"CNDF66qIlCY92q1vFAAAAQ==")});
{
   "acknowledged" : true,
   "insertedId" : UUID("08d0c5eb-aa88-9426-3dda-ad6f14000001")
}
> db.demo249.insertOne({"_id" : BinData(3,"CNDF66qJ29g92q1vFAAAEw==")});
{
   "acknowledged" : true,
   "insertedId" : BinData(3,"CNDF66qJ29g92q1vFAAAEw==")
}
Display all documents from a collection with the help of find() method −
> db.demo249.find();
This will produce the following output −
{ "_id" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv") }
{ "_id" : UUID("08d0c5eb-aa88-9426-3dda-ad6f14000001") }
{ "_id" : BinData(3,"CNDF66qJ29g92q1vFAAAEw==") }
Following is how to query BinData by Type −
> db.demo249.find(function(){ return this._id.subtype() == 0 });
This will produce the following output −
{ "_id" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv")
Git - Rename Operation

Till now, both Tom and Jerry were using manual commands to compile their project. Now, Jerry decides to create Makefile for their project and also give a proper name to the file “string.c”.
[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project

[jerry@CentOS project]$ ls
README src

[jerry@CentOS project]$ cd src/

[jerry@CentOS src]$ git add Makefile

[jerry@CentOS src]$ git mv string.c string_operations.c

[jerry@CentOS src]$ git status -s
A Makefile
R string.c −> string_operations.c

Git is showing R before file name to indicate that the file has been renamed.
For commit operation, Jerry used -a flag, that makes git commit automatically detect the modified files.
[jerry@CentOS src]$ git commit -a -m 'Added Makefile and renamed strings.c to
string_operations.c '

[master 94f7b26] Added Makefile and renamed strings.c to string_operations.c
1 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 src/Makefile
rename src/{string.c => string_operations.c} (100%)

After commit, he pushes his changes to the repository.
[jerry@CentOS src]$ git push origin master

The above command will produce the following result −
Counting objects: 6, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 396 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
7d9ea97..94f7b26 master −> master

Now, other developers can view these modifications by updating their local repository.

    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    23 Lectures 
     2 hours 

 Asif Hussain

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    125 Lectures 
     9 hours 

 John Shea

    13 Lectures 
     2.5 hours 

 Raghu Pandey

    13 Lectures 
     3 hours 

 Sebastian Sulinski
 Print
 Add Notes
 Bookmark this page
CSS Transitions

CSS transitions allows you to change property values smoothly, over a given duration.
Mouse over the element below to see a CSS transition effect:
In this chapter you will learn about the following properties:
transition
transition-delay
transition-duration
transition-property
transition-timing-function
The numbers in the table specify the first browser version that fully supports the property.
To create a transition effect, you must specify two things:
the CSS property you want to add an effect to
the duration of the effect
Note: If the duration part is not specified, the transition will have no effect, because the default value is 0.
The following example shows a 100px * 100px red <div> element. The <div> 
element has also specified a transition effect for the width property, with a duration of 2 seconds:
The transition effect will start when the specified CSS property (width) changes value.
Now, let us specify a new value for the width property when a user mouses over the <div> element:
Notice that when the cursor mouses out of the element, it will gradually change back to its original style.
The following example adds a transition effect for both the width and height property, with a duration 
of 2 seconds for the width and 4 seconds for the height:
The transition-timing-function property specifies the speed curve of the transition effect.
The transition-timing-function property can have the following values:
ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)
linear - specifies a transition effect with the same speed from start to end
ease-in - specifies a transition effect with a slow start
ease-out - specifies a transition effect with a slow end
ease-in-out - specifies a transition effect with a slow start and end
cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function
The following example shows some of the different speed curves that can be used:
The transition-delay property specifies a delay (in seconds) for the transition effect.
The following example has a 1 second delay before starting:
The following example adds a transition effect to the transformation:
The CSS transition properties can be specified one by one, like this:
or by using the shorthand property transition:
Add a 2 second transition effect for width changes of the <div> element.
<style>
div {
  width: 100px;
  height: 100px;
  background: red;
  : ;
}

div:hover {
  width: 300px;
}
</style>

<body>
  <div>This is a div</div>
</body>

Start the Exercise
The following table lists all the CSS transition properties:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How can I write an SQL IN query with a Python tuple?

To write an SQL in query, you need to ensure that you provide the placeholders in the query using  so that the query is properly escaped. For example,
my_tuple = ("Hello", "world", "John")
placeholder= '?'
placeholders= ', '.join(placeholder for _ in my_tuple)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
print(query)
# now execute using the cursor
cursor.execute(query, my_tuple)
This will give the output
'SELECT name FROM students WHERE id IN (?, ?, ?)'
And when you call to execute, it'll replace them? placeholders correctly by the escaped values.
Built-in javascript constructors?

Javascript has provided some built-in constructors. Those built-in functions include object(), string(), number, etc. We cannot include Math object in those built-in constructors because Math is a global object. The 'new' keyword cannot be used with Math.
In the following example, many built-in constructors were used and their types were displayed as shown in the output.
Live Demo
<html>
<body>
<script>
   var a = new Object();
   var b = new String();
   var c = new Number();
   var d = new Boolean();
   var e = new Array();
   var f = new RegExp();
   document.write(
      "a: " + typeof a + "</br>" +
      "b: " + typeof b + "</br>" +
      "c: " + typeof c + "</br>" +
      "d: " + typeof d + "</br>" +
      "e: " + typeof e + "</br>" +
      "f: " + typeof f + "</br>" 
   );
</script>
</body>
</html>
a: object
b: object
c: object
d: object
e: object
f: object