code-rag-bench/online-tutorials huggingface dataset:
Node.js path.parse() Method - GeeksforGeeks

13 Oct, 2021
The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties:
root (root name)
dir (directory name)
base (filename with extension)
ext (only extension)
name (only filename)
The values of these properties may be different for every platform. It ignores the platform’s trailing directory separators during parsing.
Syntax:
path.parse( path )
Parameters: This method accepts single parameter path which holds the file path that would be parsed by the method. It throws a TypeError if this parameter is not a string value.
Return Value: This method returns an object with the details of the path.
Below examples illustrate the path.parse() method in node.js:
Example 1: On POSIX
// Node.js program to demonstrate the   // path.parse() method  // Import the path moduleconst path = require('path');   path1 = path.parse("/users/admin/website/index.html");console.log(path1);   path2 = path.parse("website/readme.md");console.log(path2);
Output:
{
  root: '/',
  dir: '/users/admin/website',
  base: 'index.html',
  ext: '.html',
  name: 'index'
}
{
  root: '',
  dir: 'website',
  base: 'readme.md',
  ext: '.md',
  name: 'readme'
}
Example 2: On Windows
// Node.js program to demonstrate the   // path.parse() method  // Import the path moduleconst path = require('path');   path1 = path.parse("C:\\users\\admin\\website\\index.html");console.log(path1);   path2 = path.parse("website\\style.css");console.log(path2);
Output:
{
  root: 'C:\\',
  dir: 'C:\\users\\admin\\website',
  base: 'index.html',
  ext: '.html',
  name: 'index'
}
{
  root: '',
  dir: 'website',
  base: 'style.css',
  ext: '.css',
  name: 'style'
}
Reference: https://nodejs.org/api/path.html#path_path_parse_path
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
How to update NPM ?
Difference between promise and async await in Node.js
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Accessing every row and column of array in Julia - colon() Operator - GeeksforGeeks

20 Jul, 2021
The Colon() is an inbuilt operator in julia which is used to indicate and access every row and column. And also this operator is used to get index of specific element in the specified array.Example 1:  
Python
# Julia program to illustrate# the use of Colon (:) operator # Indicating every row and columnArray1 = [1 2 "Hello"; 3 4 "Geeks"]println(Array1[:, 3])println(Array1[1, :])
Output:  
Example 2:  
Python
# Julia program to illustrate# the use of Colon (:) operator # Accessing every row and columnArray1 = cat([1 2; 3 4],               ["hello" "Geeks"; "Welcome" "GFG"],               [5 6; 7 8], dims = 3)println(Array1[:, :, 3]) # Using getindex with colon operatorprintln(getindex(Array1, 1, :, 2))
Output:  
 
simmytarika5
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Getting the maximum value from a list in Julia - max() Method
Find maximum element along with its index in Julia - findmax() Method
Exception handling in Julia
Getting the absolute value of a number in Julia - abs() Method
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Working with Date and Time in Julia
MS Project - Assign Resources to Task

Once the task and resource list are complete, resources need to be assigned to tasks in order to work on them. With MS Project you can track task progress, resource and tasks costs.
Click View Tab → Gantt Chart View → Resource Name column.

Click the box below the Resource Name column for the task you need the resource to be assigned.

From the dropdown, choose the resource name. In the following screenshot as an 
   example. For Task 1 “PT1”, we have chosen the resource “Celic”.

You can also select multiple resources to work on a single task.
Click Resource tab → Under Assignments group → Assign Resources.

In the Assign Resources dialog box, click the resource name you like to assign.

Here let’s choose “Hitesh”. Now click the Assign button.
You can also select multiple resources to work on a single task.
Click View Tab → Gantt Chart → Task Name column.

Double-click the Task Name. Task Information dialog box opens.

Click the Resources tab.

Click the cell below the Resource Name column. Select the resource from the dropdown list.

You can also select multiple resources to work on a single task.
Click View Tab → Split View group → Details → Task Form.

The window is split in two, Gantt Chart view and Task Form view below it.
In the Task Form view, click under the Resource Name column and select the resource.

You can also select multiple resources to work on a single task.
Click View Tab → Gantt Chart View → Task Name column.

Double-click the Task Name. Task Information dialog box opens.

Click the Resources tab.

Click the cell below the Resource Name column. Select the resource from the dropdown list.

In the following example below, let’s choose “Travel” as cost resource and enter the cost at $800.
We can also assign other material resources to the same task.

    32 Lectures 
     2.5 hours 

 Pavan Lalwani

    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    102 Lectures 
     10 hours 

 Pavan Lalwani

    52 Lectures 
     4 hours 

 Pavan Lalwani

    239 Lectures 
     33 hours 

 Gowthami Swarna

    53 Lectures 
     5 hours 

 Akshay Magre
 Print
 Add Notes
 Bookmark this page
Create a red button that indicates danger in Bootstrap

To create a button in Bootstrap indicating danger, use the .btn-danger class.
You can try to run the following code to implement. btn-danger class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>Cick the below button in case of issues:</p>
      <div class = "container">
         <button type = "button" class="btn btn-danger">Danger</button>
      </div>
   </body>
</html>
REVERSE() Function in MySQL - GeeksforGeeks

31 Aug, 2020
REVERSE() :This function could be used to reverse a string and find the result. The REVERSE() function takes input parameter as string and results the reverse order of that string.
Syntax :
SELECT REVERSE(string)

Note –The parameter string is mandatory, It is the string that will be reversed.
Example-1:
SELECT REVERSE("GFG");

Output :
Example-2:Using REVERSE() function to reverse a string :
SELECT REVERSE("Geeksforgeeks");

Output :
Using REVERSE() function to reverse a sentence :
SELECT REVERSE("Geeksforgeeks is an interesting site");

Output :
Using REVERSE() function to find if a string is Palindrome :
DECLARE 
@input VARCHAR(100) = 'madam';
SELECT 
CASE
WHEN @input = REVERSE(@input)
THEN 'Palindrome'
ELSE 'Not Palindrome'
END result;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
Difference between DDL and DML in DBMS
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
Difference between DELETE, DROP and TRUNCATE
SQL | GROUP BY
Difference between SQL and NoSQL
How to Handle duplicate attributes in BeautifulSoup ? - GeeksforGeeks

07 Apr, 2021
Sometimes while obtaining the information, are you facing any issue in handling the information received from duplicate attributes of the same tags? If YES, then read the article and clear all your doubts.
Once you have created the list to store the items, write the given below code.
Syntax: 
list=soup.find_all(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”})
After writing the following code, remove the attributes from the output and print the certain item you want from the list.
Import module
Now, remove the last segment of the path by entering the name of Python file in which you are currently working.
Syntax:
base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working’))
Then, open the HTML file from which you want to read the value.
Syntax:
html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))
Parse the HTML file in BeautifulSoup.
Further, create a list to store all the item values of the same tag and attributes.
Next, find all the items which have same tag and attributes.
Syntax:
list=soup.find_all(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”})
Later on, remove all the attributes from the tag.
Finally, print the certain item of the widget tag.
Webpage in use:
HTML
<!DOCTYPE html><html> <head>   Geeks For Geeks </head> <body> <div>     <p id="vinayak">King</p>       <p id="vinayak">Prince</p>       <p id="vinayak">Queen</p>   </div> <p id="vinayak">Princess</p>    </body></html>
Program:
Python
# Import the libraries beautifulsoup and osfrom bs4 import BeautifulSoup as bsimport os  # Remove the last segment of the path# Here replace the name of your python file with# gfg4.pybase = os.path.dirname(os.path.abspath("gfg4.py"))  # Open the HTML in which you want to make # changeshtml = open(os.path.join(base, 'gfg.html'))  # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser')  # Create a list to store the itemslist = [3]  # Finding all the elements inside div# with paragraph having id: vinayaklist = soup.div.find_all("p", {"id": "vinayak"})  # Removing attributes from the outputfor i in list:    i.attrs = {}  # Printing the value Princeprint(list[1])  # Printing the value Queenprint(list[2])
Output:
<p>Prince</p>
<p>Queen</p>
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Stack Unwinding in C++

Here we will see what is the meaning of stack unwinding. When we call some functions, it stores the address into call stack, and after coming back from the functions, pops out the address to start the work where it was left of.
The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function.
Let us see the effect of stack unwinding through an example.
#include <iostream>
using namespace std;

void function1() throw (int) { //this function throws exception
   cout<<"\n Entering into function 1";
   throw 100;
   cout<<"\n Exiting function 1";
}

void function2() throw (int) { //This function calls function 1
   cout<<"\n Entering into function 2";
   function1();
   cout<<"\n Exiting function 2";
}

void function3() { //function to call function2, and handle
   exception thrown by function1
   cout<<"\n Entering function 3 ";
   try {
      function2(); //try to execute function 2
   }
   catch(int i) {
      cout<<"\n Caught Exception: "<<i;
   }
   cout<<"\n Exiting function 3";
}

int main() {
   function3();
   return 0;
}
Entering function 3
Entering into function 2
Entering into function 1
Caught Exception: 100
Exiting function 3
Here we can see that the control stores info of function3, then enters into function2, and then into function1. After that one exception occurs, so it removes all of the information from stack, and returns back to function3 again.
Perl fork Function

This function forks a new process using the fork( ) system call. Any shared sockets or filehandles are duplicated across processes. You must ensure that you wait on your children to prevent "zombie" processes from forming.
Following is the simple syntax for this function −
fork

This function returns undef on failure to fork and Child process ID to parent on success 0 to child on success.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$pid = fork();
if( $pid == 0 ) {
   print "This is child process\n";
   print "Child process is existing\n";
   exit 0;
}
print "This is parent process and child ID is $pid\n";
print "Parent process is existing\n";
exit 0;
When above code is executed, it produces the following result −
This is parent process and child ID is 18641
Parent process is existing
This is child process
Child process is existing


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Why do we get warning 'newdata' had 1 row but variables found have X rows while predicting a linear model in R?

The reason we get newdata had 1 row warning is the newdata is not correctly defined. We should give the name of the explanatory variable or independent variable to the newdata so that the model can identify that we are passing the mean of the explanatory variable, otherwise it considers all the values of the explanatory hence the result of the predict function yields the predicted values for the sample size.
 Live Demo
Consider the below data frame −
set.seed(123)
x<-rnorm(20,0.05)
y<-rpois(20,5)
df<-data.frame(x,y)
df   x        y
 1 -0.5104756 3
 2 -0.1801775 4
 3  1.6087083 4
 4  0.1205084 4
 5  0.1792877 3
 6  1.7650650 3
 7  0.5109162 3
 8 -1.2150612 5
 9 -0.6368529 4
10 -0.3956620 7
11  1.2740818 2
12  0.4098138 5
13  0.4507715 7
14  0.1606827 2
15 -0.5058411 5
16  1.8369131 3
17  0.5478505 3
18 -1.9166172 6
19  0.7513559 8
20 -0.4227914 4
Creating the linear model −
M<-lm(y~x,data=df)
Now let’s predict the value of y for the mean of x −
predict(M,newdata=data.frame(mean(df$x)),interval="confidence")
   fit      lwr       upr
 1 4.645695 3.690676 5.600715
 2 4.459543 3.635161 5.283925
 3 3.451347 2.071115 4.831579
 4 4.290080 3.520452 5.059707
 5 4.256952 3.489416 5.024489
 6 3.363226 1.876124 4.850329
 7 4.070050 3.260221 4.879880
 8 5.042792 3.669549 6.416034
 9 4.716920 3.697691 5.736149
10 4.580988 3.678189 5.483786
11 3.639939 2.475080 4.804798
12 4.127031 3.339496 4.914565
13 4.103947 3.308320 4.899575
14 4.267438 3.499558 5.035318
15 4.643083 3.690292 5.595875
16 3.322734 1.785518 4.859949
17 4.049235 3.229372 4.869097
18 5.438181 3.566862 7.309500
19 3.934541 3.043288 4.825795
20 4.596277 3.681723 5.510832
Warning message −
'newdata' had 1 row but variables found have 20 rows
To get rid of this warning we need to define the newdata for x variable as shown below −
predict(M,newdata=data.frame(x=mean(df$x)),interval="confidence")
   fit   lwr     upr
1 4.25 3.482529 5.017471
Same thing happens when we try to predict y for a fixed value −
predict(M,newdata=data.frame(1.2),interval="confidence")
    fit      lwr      upr
 1 4.645695 3.690676 5.600715
 2 4.459543 3.635161 5.283925
 3 3.451347 2.071115 4.831579
 4 4.290080 3.520452 5.059707
 5 4.256952 3.489416 5.024489
 6 3.363226 1.876124 4.850329
 7 4.070050 3.260221 4.879880
 8 5.042792 3.669549 6.416034
 9 4.716920 3.697691 5.736149
10 4.580988 3.678189 5.483786
11 3.639939 2.475080 4.804798
12 4.127031 3.339496 4.914565
13 4.103947 3.308320 4.899575
14 4.267438 3.499558 5.035318
15 4.643083 3.690292 5.595875
16 3.322734 1.785518 4.859949
17 4.049235 3.229372 4.869097
18 5.438181 3.566862 7.309500
19 3.934541 3.043288 4.825795
20 4.596277 3.681723 5.510832
Warning message −
'newdata' had 1 row but variables found have 20 rows
predict(M,newdata=data.frame(x=1.2),interval="confidence")
    fit     lwr     upr
1 3.681691 2.56125 4.802131
Armstrong numbers between a range - JavaScript

A number is called Armstrong number if the following equation holds true for that number −
xy..z = x^n + y^n+.....+ z^n
Where, n denotes the number of digits in the number
For example − 370 is an Armstrong number because −
3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370
We are required to write a JavaScript function that takes in two numbers, a range, and returns all the numbers between them that are Armstrong numbers (including them, if they are Armstrong).
Let’s write the code for this function −
const isArmstrong = number => {
   let num = number;
   const len = String(num).split("").length;
   let res = 0;
   while(num){
      const last = num % 10;
      res += Math.pow(last, len);
      num = Math.floor(num / 10);
   };
   return res === number;
};
const armstrongBetween = (lower, upper) => {
   const res = [];
   for(let i = lower; i <= upper; i++){
      if(isArmstrong(i)){
         res.push(i);
      };
   };
   return res;
};
console.log(armstrongBetween(1, 400));
The output in the console: −
[
   1,   2, 3, 4,   5,
   6,   7, 8, 9, 153,
   370, 371
]
How do I sort natural in MongoDB?

Use $natural to sort natural in MongoDB. Let us create a collection with documents −
> db.demo684.insertOne({Value:10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530cea7e81adc6a0b3957")
}
> db.demo684.insertOne({Value:50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530d1a7e81adc6a0b3958")
}
> db.demo684.insertOne({Value:60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530d4a7e81adc6a0b3959")
}
> db.demo684.insertOne({Value:40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530d8a7e81adc6a0b395a")
}
Display all documents from a collection with the help of find() method −
> db.demo684.find();
This will produce the following output −
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
Following is the query to sort on the basis of _id −
> db.demo684.find(). sort({'_id': 1});
This will produce the following output −
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
You can also use $natural −
> db.demo684.find().sort({$natural: 1});
This will produce the following output −
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
What is Debouncing in JavaScript?

Debouncing is nothing but reducing unnecessary time consuming computations so as to increase browser performance. There are some scenarios in which some functionalities take more time to execute a certain operation. For instance, take an example of a search bar in an e-commerce website.
For suppose a user wants to get "Tutorix study kit". He types every character of the product in the search bar. After typing each character, there is an Api calling takes place from browser to server so as to get the required product. Since he wants "Tutorix study kit", the user has to make 17 Api calls from browser to server. Think of a scenario that when millions of people making the same search there by calling billions of Api's. So calling billions of Api's at a time will definitely leads to a slower browser performance. To reduce this drawback, Debouncing comes in to picture.
In this scenario, Debouncing will set a time interval, for suppose 2 secs, between two keystrokes. If the time between two keystrokes exceeds 2 secs, then only Api calling will takes place. In those 2 secs the user may type at least some characters, reducing those characters Api calling. Since the Api calling has reduced, the browser performance will be increased. One must heed that the Debouncing function updates for every key stroke.
In the following example a button is attached to a event listener that calls a debounce function. Debounce function is provided with 2 parameters, one is a function and the other a number(time). A Timer is declared, which as the name suggests calls debounce function after a specific time.
Once the debounce button clicked, an alert box opens up and displays a message. The function updates every time which means if the button clicked prior to the delay time(2 secs), initial timer will be cleared and fresh timer will be started. To achieve this task clearTimeOut() function is used.
Live Demo
<html>
<body>
<input type = "button" id="debounce" value = "Debounce">
<script>
   var button = document.getElementById("debounce");
   var debounce = (func, delay) => {
      let Timer
      return function() {
         const context = this
         const args = arguments
         clearTimeout(Timer)Timer= setTimeout(() =>
            func.apply(context, args), delay)
      }
   }
   button.addEventListener('click', debounce(function() {
      alert("Hello\nNo matter how many times you" +
      "click the debounce button, I get " +"executed once every 2 seconds!!")}, 2000));
</script>
</body>
</html>
After executing the above function the following button will be displayed
After clicking the button and waiting for 2 secs the following alert box will be displayed as the output.
Tryit Editor v3.7

CSS Color Keywords
Tryit: Using the transparent keyword
Guava - CaseFormat Class

CaseFormat is a utility class to provide conversion between various ASCII char formats.
Following is the declaration for com.google.common.base.CaseFormat class −
@GwtCompatible
public enum CaseFormat
   extends Enum<CaseFormat>
LOWER_CAMEL
Java variable naming convention, e.g., "lowerCamel".
LOWER_HYPHEN
Hyphenated variable naming convention, e.g., "lower-hyphen".
LOWER_UNDERSCORE
C++ variable naming convention, e.g., "lower_underscore".
UPPER_CAMEL
Java and C++ class naming convention, e.g., "UpperCamel".
UPPER_UNDERSCORE
Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".
Converter<String,String> converterTo(CaseFormat targetFormat)
Returns a Converter that converts strings from this format to targetFormat.
String to(CaseFormat format, String str)
Converts the specified String str from this format to the specified format.
static CaseFormat	valueOf(String name)
Returns the enum constant of this type with the specified name.
static CaseFormat[] values()
Returns an array containing the constants of this enum type, in the order they are declared.
This class inherits methods from the following classes −
java.lang.Enum
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import com.google.common.base.CaseFormat;

public class GuavaTester {
   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();
      tester.testCaseFormat();
   }

   private void testCaseFormat() {
      String data = "test_data";
      System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, "test-data"));
      System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "test_data"));
      System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "test_data"));
   }
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java

Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester

See the result.
testData
testData
TestData

 Print
 Add Notes
 Bookmark this page
Matcher find() method in Java with Examples - GeeksforGeeks

26 Nov, 2018
The find() method of Matcher Class attempts to find the next subsequence of the input sequence that find the pattern. It returns a boolean value showing the same.
Syntax:
public boolean find()

Parameters: This method do not takes any parameter.
Return Value: This method returns a boolean value showing whether a subsequence of the input sequence find this matcher’s pattern
Below examples illustrate the Matcher.find() method:
Example 1:
// Java code to illustrate find() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "Geeks";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GeeksForGeeks";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the subsequence        // using find() method        System.out.println(matcher.find());    }}
true

Example 2:
// Java code to illustrate find() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "GFG";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GFGFGFGFGFGFGFGFGFG";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the subsequence        // using find() method        System.out.println(matcher.find());    }}
true

Reference: Oracle Doc
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
Can a Java array be declared as a static field, local variable or a method parameter?

We can declare an array as a local variable or method parameter but, an array cannot be static.
public class Test{
   public void sample(){
      static int[] myArray = {20, 30};
      System.out.println();
   }
   public static void main(String args[]){
      Test t = new Test();
      t.sample();
   }
}
C:\Sample>javac Test.java
Test.java:3: error: illegal start of expression
   static int[] myArray = {20, 30};
   ^
1 error
C library function - mktime()

The C library function time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into a time_t value according to the local time zone.
Following is the declaration for mktime() function.
time_t mktime(struct tm *timeptr)
timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components. Below is the detail of timeptr structure
timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components. Below is the detail of timeptr structure
struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */	
};
This function returns a time_t value corresponding to the calendar time passed as argument. On error, a -1 value is returned.
The following example shows the usage of mktime() function.
#include 
#include 

int main () {
   int ret;
   struct tm info;
   char buffer[80];

   info.tm_year = 2001 - 1900;
   info.tm_mon = 7 - 1;
   info.tm_mday = 4;
   info.tm_hour = 0;
   info.tm_min = 0;
   info.tm_sec = 1;
   info.tm_isdst = -1;

   ret = mktime(&info);
   if( ret == -1 ) {
      printf("Error: unable to make time using mktime\n");
   } else {
      strftime(buffer, sizeof(buffer), "%c", &info );
      printf(buffer);
   }

   return(0);
}
Let us compile and run the above program that will produce the following result −
Wed Jul 4 00:00:01 2001


    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
Convert a NumPy array to a Pandas series - GeeksforGeeks

18 Aug, 2020
Let us see how to convert a NumPy array to a Pandas series. A NumPy array can be converted into a Pandas series by passing it in the pandas.Series() function.
Example 1 :
# importing the modulesimport numpy as npimport pandas as pd  # creating an NumPy arrayarray = np.array([10, 20, 1, 2,                    3, 4, 5, 6, 7])  # displaying the NumPy arrayprint("Numpy array is :")display(array)  # converting the NumPy array # to a Pandas seriesseries = pd.Series(array)   # displaying the Pandas seriesprint("Pandas Series : ")display(series)
Output :
Example 2 :
# importing the modulesimport numpy as npimport pandas as pd  # creating an NumPy arrayarray = np.random.rand(5)   # displaying the NumPy arrayprint("Numpy array is :")display(array)  # converting the NumPy array # to a Pandas seriesseries = pd.Series(array)   # displaying the Pandas seriesprint("Pandas Series : ")display(series)
Output :
Python pandas-series
Python-pandas
Python
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
GATE | GATE CS 2011 | Question 65

28 Jun, 2021
Let the page fault service time be 10ms in a computer with average memory access time being 20ns. If one page fault is generated for every 10^6 memory accesses, what is the effective access time for the memory?(A) 21ns(B) 30ns(C) 23ns(D) 35nsAnswer: (B)Explanation:
Let P be the page fault rate
Effective Memory Access Time = p * (page fault service time) + 
                               (1 - p) * (Memory access time)
                             = ( 1/(10^6) )* 10 * (10^6) ns +
                               (1 - 1/(10^6)) * 20 ns
                             = 30 ns (approx)   
Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set the matplotlib figure default size in ipython notebook?

To set the matplotlib figure default size in iPython, use the following steps −
To check the default figure size, use plt.rcParams["figure.figsize"] over the ipython
shell.
To check the default figure size, use plt.rcParams["figure.figsize"] over the ipython
shell.
Now to set the figure size, override the plt.rcParams["figure.figsize"] variable with a tuple i.e., (20, 10).
Now to set the figure size, override the plt.rcParams["figure.figsize"] variable with a tuple i.e., (20, 10).
After overriding the plt.rcParams["figure.figsize"] variable, you can use it to get changed figure size.
After overriding the plt.rcParams["figure.figsize"] variable, you can use it to get changed figure size.
import matplotlib.pyplot as plt

print("Before, figure default size is: ", plt.rcParams["figure.figsize"])
plt.rcParams["figure.figsize"] = (20, 10)
print("After, figure default size is: ", plt.rcParams["figure.figsize"])
Before, figure default size is: [6.4, 4.8]
After, figure default size is: [20.0, 10.0]
Python regex to find sequences of one upper case letter followed by lower case letters

When it is required to find sequences of an upper case letter followed by lower case using regular expression, a method named ‘match_string’ is defined that uses the ‘search’ method to match a regular expression. Outside the method, the string is defined, and the method is called on it by passing the string.
Below is a demonstration of the same
import re

def match_string(my_string):

   pattern = '[A-Z]+[a-z]+$'

   if re.search(pattern, my_string):
      return('The string meets the required condition \n')
   else:
      return('The string doesnot meet the required condition \n')

print("The string is :")
string_1 = "Python"
print(string_1)
print(match_string(string_1))

print("The string is :")
string_2 = "python"
print(string_2)
print(match_string(string_2))

print("The string is :")
string_3 = "PythonInterpreter"
print(string_3)
print(match_string(string_3))
The string is :
Python
The string meets the required condition
The string is :
python
The string doesn’t meet the required condition
The string is :
PythonInterpreter
The string meets the required condition
The required packages are imported.
The required packages are imported.
A method named ‘match_string’ is defined, that takes a string as a parameter.
A method named ‘match_string’ is defined, that takes a string as a parameter.
It uses the ‘search’ method to check if the specific regular expression was found in the string or not.
It uses the ‘search’ method to check if the specific regular expression was found in the string or not.
Outside the method, a string is defined, and is displayed on the console.
Outside the method, a string is defined, and is displayed on the console.
The method is called by passing this string as a parameter.
The method is called by passing this string as a parameter.
The output is displayed on the console.
The output is displayed on the console.
fabs() in C++

09 Apr, 2018
The fabs() function returns the absolute value of the argument.Mathematically |a|. If a is value given in the argument.
Syntax:
double fabs(double a);
float fabs(float a);
int fabs(int a);

Parameter:
The fabs() function takes a single argument, a whose absolute value has to be returned.
Return:
The fabs() function returns the absolute value of the argument.
Error:
It is mandatory to give both the arguments otherwise it will give errorno matching function for call to ‘fabs()’ like this.
# CODE 1
// CPP code to illustrate// fabs() function#include <cmath>#include <iostream>  using namespace std;  int main(){    int a = -10, answer;      answer = fabs(a);    cout << "fabs of " << a          << " is " << answer << endl;      return 0;}
OUTPUT :
fabs of -10 is 10

# CODE 2
// CPP code to illustrate// fabs() function#include <cmath>#include <iostream>  using namespace std;  int main(){    long int a = -35;    double answer;      answer = fabs(a);    cout << "fabs of " << a << " is "          << answer << endl;      return 0;}
OUTPUT :
fabs of -35 is 35

CPP-Library
cpp-math
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
Ruby | StringScanner scan function

12 Dec, 2019
StringScanner#scan() : scan() is a StringScanner class method which tries to match with pattern at the current position.
Syntax: StringScanner.scan()
Parameter: StringScanner values
Return: matched string otherwise return false
Example #1 :
# Ruby code for StringScanner.scan() method  # loading StringScannerrequire 'strscan'  # declaring StringScanner c = StringScanner.new("Mon Sep 12 2018 14:39")   # scan() methodc.scan(/\w+/)  puts "String Scanner result of c.scan() form : #{c.pos()}\n\n"  # scan() methodc.scan(/\s+/)  puts "String Scanner result of c.scan() form : #{c.pos()}\n\n"
Output :
String Scanner result of c.scan() form : 3

String Scanner result of c.scan() form : 4


Example #2 :
# Ruby code for StringScanner.scan() method  # loading StringScannerrequire 'strscan'  # declaring StringScanner c = StringScanner.new("h ello geeks")   # scan() methodc.scan(/\w+/)  puts "String Scanner result of c.scan() form : #{c.pos()}\n\n"  # scan() methodc.scan(/\s+/)  puts "String Scanner result of c.scan() form : #{c.pos()}\n\n"
Output :
String Scanner result of c.scan() form : 1

String Scanner result of c.scan() form : 2

Ruby String Scanner-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Data Types
Ruby | Case Statement
Ruby | Enumerator each_with_index function
Ruby | Hash delete() function
AWT ContainerEvent Class

The Class ContainerEvent represents that a container's contents changed because a component was added or removed.
Following is the declaration for java.awt.event.ContainerEvent class:
public class ContainerEvent
   extends ComponentEvent
Following are the fields for java.awt.Component class:
static int COMPONENT_ADDED  -- This event indicates that a component was added to the container.
static int COMPONENT_ADDED  -- This event indicates that a component was added to the container.
static int COMPONENT_REMOVED  -- This event indicates that a component was removed from the container.
static int COMPONENT_REMOVED  -- This event indicates that a component was removed from the container.
static int CONTAINER_FIRST  -- The first number in the range of ids used for container events.
static int CONTAINER_FIRST  -- The first number in the range of ids used for container events.
static int CONTAINER_LAST  -- The last number in the range of ids used for container events.
static int CONTAINER_LAST  -- The last number in the range of ids used for container events.
ContainerEvent(Component source, int id, Component child) 
Constructs a ContainerEvent object.
This class inherits methods from the following classes:
java.awt.ComponentEvent
java.awt.ComponentEvent
java.awt.AWTEvent
java.awt.AWTEvent
java.util.EventObject
java.util.EventObject
java.lang.Object
java.lang.Object

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page
How to take backup of a single table in a MySQL database?

The backup of a table can be made with the help of backup table as well as mysqldump utility.
The backup table concept was used in MySQL version 5.0 and its earlier version.
Here, I am performing backup with the help of mysqldump. Firstly, we will open cmd with the
help of shortcut key. The mysqldump will run at the cmd. Therefore, firstly open cmd with the
help of shortcut key −
windowskey+R;

Here is the snapshot −
Now, cmd will open −
In this, the MySQL bin folder is present at the following location −
C:\Program Files\MySQL\MySQL Server 8.0\bin

Type the above path to reach the “bin” folder.
Now, we are in “bin” folder. The query to take backup is as follows −
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysqldump -u Manish -p business student <
E:\student.sql
Enter password: ***********

The following is the output −
-- MySQL dump 10.13 Distrib 8.0.12, for Win64 (x86_64)
--
-- Host: localhost Database: business
-- ------------------------------------------------------
-- Server version 8.0.12

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
SET NAMES utf8mb4 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,
FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE,
SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `student`
--

DROP TABLE IF EXISTS `student`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;

CREATE TABLE `student` (
   `id` int(11) DEFAULT NULL,
   `Name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
    KEY `NameStuIndex` (`Name`),
    KEY `idIndex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `student`
--

LOCK TABLES `student` WRITE;
/*!40000 ALTER TABLE `student` DISABLE KEYS */;
INSERT into `student` VALUES (1,'John'),(2,'Bob');
/*!40000 ALTER TABLE `student` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-10-03 10:30:58
How to insert into two tables using a single MySQL query?

You can use stored procedure to insert into two tables in a single query. Let us first create a table −
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20)
);
Query OK, 0 rows affected (0.56 sec)
Here is the query to create second table −
mysql> create table DemoTable2
(
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(20),
   ClientAge int
);
Query OK, 0 rows affected (0.76 sec)
Following is the query to create stored procedure to insert into two tables created above −
mysql> DELIMITER //
   mysql> CREATE PROCEDURE insert_into_twoTables(name varchar(100),age int)
      BEGIN
         INSERT INTO DemoTable(StudentFirstName) VALUES(name);
         INSERT INTO DemoTable2(ClientName,ClientAge) VALUES(name,age);
      END
      //
   Query OK, 0 rows affected (0.14 sec)
mysql> DELIMITER ;
Now call the stored procedure with the help of CALL command −
mysql> call insert_into_twoTables('Tom',38);
Query OK, 1 row affected, 1 warning (0.41 sec)
Check the record is inserted into both tables or not.
The query to display all records from the first table is as follows −
mysql> select * from DemoTable;
This will produce the following output −
+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
| 1         | Tom              |
+-----------+------------------+
1 row in set (0.00 sec)
Following is the query to display all records from the second table −
mysql> select * from DemoTable2;
This will produce the following output −
+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
| 1        | Tom        | 38        |
+----------+------------+-----------+
1 row in set (0.00 sec)
HTML - <fieldset> Tag

The HTML <fieldset> tag is used for grouping related form elements. By using the fieldset tag and the legend tag, you can make your forms much easier to understand for your users.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML fieldset Tag</title>
   </head>

   <body>
      <form>
         
         <fieldset>
            <legend>Details</legend>
            Student Name: <input type = "text"><br />
            MCA Subjects:<input type = "text"><br />
            Course Link:<input type = "url" name = "websitelink">
         </fieldset>
         
      </form>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <fieldset> tag also supports the following  additional attributes −
This tag supports all the event attributes described in HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
DateTime.ToLongDateString() Method in C#

The DateTime.ToLongDateString() method in C# is used to convert the value of the current DateTime object to its equivalent long date string representation.
Following is the syntax −
public string ToLongDateString ();
Let us now see an example to implement the DateTime.ToLongDateString() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 10, 11, 9, 10, 45);
      Console.WriteLine("Date = {0}", d);
      string str = d.ToLongDateString();
      Console.WriteLine("Long date string representation = {0}", str);
   }
}
This will produce the following output −
Date = 10/11/2019 9:10:45 AM
Long date string representation = Friday, October 11, 2019
Let us now see another example to implement the DateTime.ToLongDateString() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name);
      var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
      string str = d.ToLongDateString();
      Console.WriteLine("Long date string = {0}", pattern.LongDatePattern);
      Console.WriteLine("Long date string representation = {0}", str);
   }
}
This will produce the following output −
Date = 10/16/2019 8:39:08 AM
Current culture = en-US
Long date string = dddd, MMMM d, yyyy
Long date string representation = Wednesday, October 16, 2019
PostgreSQL - TRUNCATE TABLE Command

The PostgreSQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure from the database and you would need to re-create this table once again if you wish to store some data.
It has the same effect as DELETE on each table, but since it does not actually scan the tables, it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables.
The basic syntax of TRUNCATE TABLE is as follows −
TRUNCATE TABLE  table_name;

Consider the COMPANY table has the following records −
 id | name  | age | address    | salary
----+-------+-----+------------+--------
  1 | Paul  |  32 | California |  20000
  2 | Allen |  25 | Texas      |  15000
  3 | Teddy |  23 | Norway     |  20000
  4 | Mark  |  25 | Rich-Mond  |  65000
  5 | David |  27 | Texas      |  85000
  6 | Kim   |  22 | South-Hall |  45000
  7 | James |  24 | Houston    |  10000
(7 rows)
The following is the example to truncate −
testdb=# TRUNCATE TABLE COMPANY;
Now, COMPANY table is truncated and the following would be the output of SELECT statement −
testdb=# SELECT * FROM CUSTOMERS;
 id | name | age | address | salary
----+------+-----+---------+--------
(0 rows)

    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page