code-rag-bench/online-tutorials huggingface dataset:
How to delete all files and folders from a path in C#?

For deleting all the folders and its respective directories we can make us System.IO namespace available in C#. The DirectoryInfo() class provides the details of all sub directories and file in a directory.
Let us consider a directory Demo having two sub directories and has some files like below.
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         DirectoryInfo di = new DirectoryInfo(@"D:\Demo");
         foreach (DirectoryInfo dir in di.GetDirectories()) {
            foreach (FileInfo file in dir.GetFiles()) {
               file.Delete();
            }
            dir.Delete(true);
         }
      }
   }
}
output of the above code is
We could see that all the folders and its related files are deleted from the demo directory completely. Here GetDirectories() will fetch all the directories of the root directory (Demo) and GetFiles() will fetch all the files (Demo File 1, Demo File 2) present in that directory.
How to set a property having different datatype with a string value using reflection in C#?

Reflection is when managed code can read its own metadata to find assemblies.
Essentially, it allows code to inspect other code within the same system. With
reflection in C#, we can dynamically create an instance of a type and bind that type to
an existing object. Moreover, we can get the type from an existing object and access
its properties. When we use attributes in our code, reflection gives us access as it
provides objects of Type that describe modules, assemblies, and types.
Let us say we have a property of type double and in the runtime we actually have the value as string and assign it to the property after changing the type. We can use Convert.ChangeType() - It allows us to use runtime information on any IConvertible type to change representation formats.
 Live Demo
using System;
using System.Reflection;
namespace DemoApplication{
   class Program{
      static void Main(){
         Circle circle = new Circle();
         string value = "6.5";
         PropertyInfo propertyInfo = circle.GetType().GetProperty("Radius");
         propertyInfo.SetValue(circle, Convert.ChangeType(value,
         propertyInfo.PropertyType), null);
         var radius = circle.GetType().GetProperty("Radius").GetValue(circle, null);
         Console.WriteLine($"Radius: {radius}");
         Console.ReadLine();
      }
   }
   class Circle{
      public double Radius { get; set; }
   }
}
Radius: 6.5
In the above example we could see that string value "6.5" is converted to actual type
double using Convert.ChangeType and assigned to Radius property using reflection in
runtime.
Creating a prompt dialog box using Tkinter?

Dialog Boxes are handy for informing users to perform certain operations. We are already familiar with the dialog boxes and interacted with them many times. In a particular Tkinter application, we can create any type of dialog boxes, such as Message, User Interaction Dialogs, Single Value Entry Dialogs, File chooser, etc. To create dialog boxes, Tkinter has several built-in packages like a messagebox, simpledialog, filedialog, and colorchooser.
In this example, we will create a message box to inform the user to choose an option.
#Import the tkinter library
from tkinter import *
from tkinter import messagebox
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry of the function
win.geometry("750x250")
answer = messagebox.askyesno("Question","Do you like Python Tkinter?")
#Create a Label
Label(win, text=answer, font= ('Georgia 20 bold')).pack()
win.mainloop()
Running the above code will display a prompt dialog box. Once we choose an option, it will display the Boolean value based on Yes (1) or No (0).
Once we click on Yes or No, it will update the Tkinter window with 1 or 0 values.
Date.getMonth() function in JavaScript

The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The getMonth() function of the Date object returns the moth (0 represents January and so on...) of its current date.
Its syntax is as follows
dateObj.getMonth();
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25:96');
      document.write("Month of the year: "+dateObj.getMonth());
   </script>
</body>
</html>
Month of the year: 8
Incase if you haven’t mentioned the month of the year while creating the date object, this function returns 0.
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('89 12:4:25:96');
      document.write("Month of the year: "+dateObj.getmonth());
   </script>
</body>
</html>
Month of the year: 0
In the same way if you haven’t passed anything while creating the date object, this function returns the Current month of the current year.
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      document.write("Month of the year:+ "dateObj.getMonth());
   </script>
</body>
</html>
Month of the year: 9
Exploratory Data Analysis with Pandas Profiling | by Albert Sanchez Lafuente | Towards Data Science

Pandas profiling is an open source Python module with which we can quickly do an exploratory data analysis with just a few lines of code. Besides, if this is not enough to convince us to use this tool, it also generates interactive reports in web format that can be presented to any person, even if they don’t know programming.
In short, what pandas profiling does is save us all the work of visualizing and understanding the distribution of each variable. It generates a report with all the information easily available.
To show you clearly how it works, this is an example of a report generated by pandas profiling:
You can also check an interactive report clicking this link.
One of the strong points of the generated report are the warnings that appear at the beginning. It tells us the variables that contain NaN values, variables with many zeros, categorical variables with high cardinality, etc.
First step is to install it with this command:
pip install pandas-profiling
Then we generate the report using these commands:
from pandas_profiling import ProfileReportprof = ProfileReport(df)prof.to_file(output_file='output.html')
Here we are, it’s been that simple. We can see the report generated in the output.html file.
The main disadvantage of pandas profiling is its use with large datasets. With the increase in the size of the data the time to generate the report also increases a lot.
One way to solve this problem is to generate the report from only a part of all the data we have. It is important to make sure that the data selected to generate the report is representative of all the data we have, for example it could be the case that the first X rows of data contain only data from one category. In this example we would like to randomize the order of the data and select a representative sample.
An example with code:
from pandas_profiling import ProfileReport#We only use the first 10000 data pointsprof = ProfileReport(df.sample(n=10000)) prof.to_file(output_file='output.html')
Another alternative is to use the minimum mode that was introduced in version 2.4 of pandas profiling. You can check which version you have installed with this command:
pandas_profiling.version.__version__
With the minimum mode a simplified report will be generated with less information than the full one but it can be generated relatively quickly for a large dataset. This is the code to be used:
profile = ProfileReport(df, minimal=True)profile.to_file(output_file="output_min.html")
Python Program to merge two files into a third file

29 Dec, 2020
Prerequisite: Reading and writing to a file.
Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge.
Open file1.txt and file2.txt in read mode.Open file3.txt in write mode.Read the data from file1 and add it in a string.Read the data from file2 and concatenate the data of this file to the previous string.Write the data from string to file3Close all the files
Open file1.txt and file2.txt in read mode.
Open file3.txt in write mode.
Read the data from file1 and add it in a string.
Read the data from file2 and concatenate the data of this file to the previous string.
Write the data from string to file3
Close all the files
Note: To successfully run the below program file1.txt and file2.txt must exist in the same folder.
Suppose the text files file1.txt and file2.txt contain the following data.
file1.txt
file2.txt
Below is the implementation.
# Python program to# demonstrate merging# of two files  data = data2 = ""  # Reading data from file1with open('file1.txt') as fp:    data = fp.read()  # Reading data from file2with open('file2.txt') as fp:    data2 = fp.read()  # Merging 2 files# To add the data of file2# from next linedata += "\n"data += data2  with open ('file3.txt', 'w') as fp:    fp.write(data)
Output:
The above approach can be shortened using for loop. The following are steps to merge.
Create a list containing filenames.Open the file3 in write mode.Iterate through the list and open each file in read mode.Read the data from files and simultaneously write the data in file3.Close all the files
Create a list containing filenames.
Open the file3 in write mode.
Iterate through the list and open each file in read mode.
Read the data from files and simultaneously write the data in file3.
Close all the files
Below is the implementation.
# Python program to# demonstrate merging of# two files  # Creating a list of filenamesfilenames = ['file1.txt', 'file2.txt']  # Open file3 in write modewith open('file3.txt', 'w') as outfile:      # Iterate through list    for names in filenames:          # Open each file in read mode        with open(names) as infile:              # read the data from file1 and            # file2 and write it in file3            outfile.write(infile.read())          # Add '\n' to enter data of file2        # from next line        outfile.write("\n")
Output:
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Svelte | Introduction and Installation

11 Feb, 2022
Svelte is the new methodology for creating web apps. It can be used in a small part of a code or in an entire single page application. It is a compiler not a framework, which is faster than other JavaScript libraries like ReactJS, AngularJS, VueJS. It is used to create reactive web apps. If any change occurs in the data that change will reflect on the page instantly. It is also used in rapid application development (RAD) means quickly produce minimally coded software application. It is used in Web Optimization. But it does not use virtual DOM which makes it different from others. It is free and open source written by Rich Harris. Svelte Compiles your Code for production at execution time into vanilla JavaScript bundle. If you deploy your application over the internet then you don’t need to deploy Svelte like we did other library. That’s why it results in a fast execution. 
Prerequisite: Before installing or start working on Svelte, we have to make sure few things are available in our system. 
Any Text Editor(e.g vs code, Atom etc.)
NodeJS installed in your system: Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on Windows
Installation of Node.js on Linux
Installation of Svelte: Now we are ready to install the Svelte.  
Step 1: Open the command prompt or terminal and install a package named degit, which allows us to easily clone the latest commit from a github repository. 
npm install -g degit
 
Step 2: Now create a directory on the desktop and run the below command. The degit go to the repository(sveltejs) find the template and download it locally for us in the project named myproject. 
degit sveltejs/template myproject
 
Step 3: The project is created, now open this in text editor. In the src folder we have main.js file which is used to execute our svelte app The App.svelte is the root component of our application and the package.json file contains all the dependencies which needs to be installed. 
Step 4: Now install all the dependencies make sure you are inside of the “myproject” directory. 
npm install
Step 5: Now create a local development server to run our application. 
npm run dev
Step 6: Now follow the above link and application will open in the browser.
sagar0719kumar
kk9826225
siddharthdedhia11
how-to-install
JavaScript-Misc
Installation Guide
JavaScript
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 1996 | Question 8

21 May, 2020
Which two of the following four regular expressions are equivalent? (ε is the empty string).(i). (00)*(ε+0)(ii). (00)*(iii). 0*(iv). 0(00)*(A) (i) and (ii)(B) (ii) and (iii)(C) (i) and (iii)(D) (iii) and (iv)Answer: (C)Explanation: Here,
(00)*(ε+0)
= (00)*.ε+ (00)*.0 
= (00)* + (00)*0 
= 0* 
It is equal to (iii) [ using regular expression properties ].
Here,we see that (00)* generates strings of even length and (00)*0 generated the strings of odd length.
Option (C) is correct.Quiz of this Question
vivekkumarmth0077
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Check whether Element Exists in Java ArrayList?

04 Dec, 2020
Java ArrayList is a resizable array, which can be found in java.util package. We can add or delete elements from an ArrayList whenever we want, unlike a built-in array.
We can check whether an element exists in ArrayList in java in two ways:
Using contains() methodUsing indexOf() method
Using contains() method
Using indexOf() method
Method 1: Using contains() method
The contains() method of the java.util.ArrayList class can be used to check whether an element exists in Java ArrayList.
Syntax:
public boolean contains(Object)
Parameter:
object – element whose presence in this list is to be tested
Returns: It returns true if the specified element is found in the list else it returns false.
Java
// Java program to check// whether element exists// in Java ArrayList  import java.io.*;import java.util.ArrayList;  class GFG {    public static void main(String[] args)    {        ArrayList<Integer> list = new ArrayList<>();          // use add() method to add elements in the list        list.add(1);        list.add(2);        list.add(3);        list.add(4);          // passing 5 as as as        // parameter to contains()        // function        if (list.contains(5))            System.out.println("5 exists in the ArrayList");          else            System.out.println("5 does not exist in the ArrayList");          if (list.contains(2))            System.out.println("2 exists in the ArrayList");          else            System.out.println("2 does not exist in the ArrayList");            }}
5 does not exist in the ArrayList
2 exists in the ArrayList
Method 2: Using indexOf() method
Contains() method uses indexOf() method to determine if a specified element is present in the list or not. 
So we can also directly use the indexOf() method to check the existence of any supplied element value.
Java
// Java program to check // whether element exists // in Java ArrayList  import java.io.*;import java.util.ArrayList;  class GFG {    public static void main (String[] args) {        ArrayList<Integer> list = new ArrayList<>();        // use add() method to add elements in the list      list.add(2);      list.add(5);      list.add(1);      list.add(6);              // passing 5 as as as      // parameter to contains()      // function      if(list.indexOf(5)>=0)        System.out.println("5 exists in the ArrayList");              else        System.out.println("5 does not exist in the ArrayList");              if(list.indexOf(8)>=0)         System.out.println("8 exists in the ArrayList");              else        System.out.println("8 does not exist in the ArrayList");            }}
5 exists in the ArrayList
8 does not exist in the ArrayList
Java-ArrayList
Java-Collections
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Find Sum of Array Elements

13 Jun, 2022
Given an array of integers. Write a Java Program to find the sum of the elements of the array.
Examples:
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50
15 + 12 + 13 + 10 = 50
An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations. 
Array Elements: Each item of an array is an Element. All the elements in an array must be of the same type.
Initialize an array arr and a variable sum.Set the value of sum=0. Start a for loop from index 0 to the length of the array – 1.In every iteration, perform sum = sum + arr[i].After the termination of the loop, print the value of the sum.
Initialize an array arr and a variable sum.
Set the value of sum=0.
 Start a for loop from index 0 to the length of the array – 1.
In every iteration, perform sum = sum + arr[i].
After the termination of the loop, print the value of the sum.
Java
// Java Program to find sum of elements in a given arrayclass Test {    static int arr[] = { 12, 3, 4, 15 };     // method for sum of elements in an array    static int sum()    {        int sum = 0; // initialize sum        int i;         // Iterate through all elements and add them to sum        for (i = 0; i < arr.length; i++)            sum += arr[i];         return sum;    }     // Driver method    public static void main(String[] args)    {        System.out.println("Sum of given array is "                           + sum());    }}
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
nishkarshgandhi
chandramauliguptach
Java-Array-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2008 | Question 66

05 Apr, 2019
A process executes the following code
for (i = 0; i < n; i++) fork();
The total number of child processes created is(A) n(B) 2n - 1(C) 2n(D) 2(n+1) - 1Answer: (B)Explanation:
         F0       // There will be 1 child process created by first fork
      /     \
    F1      F1    // There will be 2 child processes created by second fork
   /  \    /  \
 F2   F2  F2   F2  // There will be 4 child processes created by third fork
/ \   / \ / \  / \
 ...............   // and so on
If we sum all levels of above tree for i = 0 to n-1, we get 2n - 1. So there will be 2n – 1 child processes. On the other hand, the total number of process created are (number of child processes)+1.
Note:The maximum number of process is 2n and may vary due to fork failures.Also see this post for more details.
Quiz of this Question
kalpaj_12
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IntStream rangeClosed() in Java

06 Dec, 2018
IntStream rangeClosed(int startInclusive, int endInclusive) returns an IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.
Syntax :
static IntStream rangeClosed(int startInclusive,   int endInclusive)

Parameters :
IntStream : A sequence of primitive int-valued elements.startInclusive : The inclusive initial value.endInclusive : The inclusive upper bound.
IntStream : A sequence of primitive int-valued elements.
startInclusive : The inclusive initial value.
endInclusive : The inclusive upper bound.
Return Value : A sequential IntStream for the range of int elements.
Example :
// Implementation of IntStream rangeClosed// (int startInclusive, int endInclusive)import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.rangeClosed(-4, 3);          // Displaying the elements in range        // including the lower and upper bound        stream.forEach(System.out::println);    }}
-4
-3
-2
-1
0
1
2
3

Note : IntStream rangeClosed(int startInclusive, int endInclusive) basically works like a for loop. An equivalent sequence of increasing values can be produced sequentially as :
for (int i = startInclusive; i <= endInclusive ; i++) 
{
 ...
 ...
 ...
}

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Parbegin/Parend Concurrent Statement

26 Feb, 2021
Prerequisite – Introduction of Process Synchronization PARBEGIN/PAREND statement is a higher-level language construct for specifying concurrency. All statements can be executed concurrently those are enclosed between PARBEGIN and PAREND. It is used in modelling precedence graph. It is used as an alternative for the FORK/JOIN statement. 
Note – PARBEGIN/PAREND is also called COBEGIN/COEND. 
Consider the following program:  
S0;
PARBEGIN;
   S1;
   S2;
   ...
   Sn-1;
PAREND;
Sn;
The above program is equivalent to the following precedence graph. 
 
Example – Construct the precedence graph for the following parbegin/parend program.  
begin
S1;
      parbegin
      S3;
      begin
      S2;
            parbegin
            S4;
            S5;
            parend;
            S6;
      end;
      parend;
S7;
end;
Explanation : 
 
We can also Parbegin two process –
Void P( )                     Void Q( )
{                              {
A;                                   D;
B;                                    E;
C;                           }
}
The relative order among the statements of P & Q is always maintained
Advantages of Parbegin/Parend – 
It is a high-level language block-structure.
It has the advantage of structured control statements.
Semaphores mechanism is also one of the advantages.
Disadvantages of Parbegin/Parend – 
It is not powerful enough to model all possible precedence graph.
It is less powerful than the FORK/JOIN construct in modelling precedence graph.
pawanchoure
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert records with double quotes in MySQL?

To insert records with double quotes, use the backslash (\) as in the below syntax −
insert into yourTableName values('\"yourValue\"');
Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('\"John\"');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('\"Chris\"');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('\"Adam Smith\"');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('\"Carol\"');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output. The double quotes around the records can be easily seen −
+--------------+
| Name         |
+--------------+
| "John"       |
| "Chris"      |
| "Adam Smith" |
| "Carol"      |
+--------------+
4 rows in set (0.00 sec)
C++ Program that will fill whole memory - GeeksforGeeks

15 Aug, 2017
NOTE:We strongly recommend to try this code in virtual machine because it may hang your computer within 5 second
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack
new KeywordThe new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax is
pointer-variable = new data-type;

delete Keyworddelete that perform the task of allocating and freeing the memory in a better and easier way.
Syntax to use delete operator: To allocate memory of any data type, the syntax is
delete pointer-variable; 

Following is C++ Program that will fill whole memory
#include<bits/stdc++.h>  int main(){    while (true)      int *a = new int;  // allocating }  
Output & ExplanationIt hung my computer while the task manager was open and showed that it took 890 Mb of memory in 1 second then it also hung. It keeps on giving memory to a variable.To explore more of this code, added a statement delete a and every thing was fine while testing (no hanging) So, I think that the chunk of memory is given (due to new int) and then taken back (due to delete a) to the free space in the new code below.
Mitigated Code
#include<bits/stdc++.h>int main(){    while (true)    {         int *a = new int;   // allocating         delete a;           // deallocating    }}  
Referenceshttps://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Constructors in C++
Socket Programming in C/C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++
Ruby | Matrix inverse() function - GeeksforGeeks

07 Jan, 2020
The inverse() is an inbuilt method in Ruby returns the inverse of the given matrix.
Syntax: mat1.inverse()
Parameters: The function does not takes any parameter.
Return Value: It returns the inverse of a matrix.
Example 1:
#Ruby program for inverse() method in Matrix  #Include matrixrequire "matrix"  #Initialize a matrix    mat1    = Matrix[[ Complex(1, 2), 21 ], [ 31, Complex(9, 12) ]]  #prints the inverse matrix      puts mat1.inverse()
Output:
Matrix[[-313/24692-459/24692i, 777/24692+35/24692i], [1147/24692+155/74076i, -101/74076-227/74076i]]

Example 2:
#Ruby program for inverse() method in Matrix  #Include matrixrequire "matrix"  #Initialize a matrix    mat1    = Matrix[[ 1, -8 ], [ -2, -8 ]]  #prints the inverse matrix      puts mat1.inverse()
Output:
Matrix[[1/3, -1/3], [-1/12, -1/24]]
Ruby Matrix-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Ruby | Numeric round() function
C++ Vector Library - end() Function

The C++ function std::vector::end() returns an iterator which points to past-the-end element in the vector container.
The past-the-end element is the theoretical element that would follow the last element in the vector.
Following is the declaration for std::vector::end() function form std::vector header.
iterator end();
const_iterator end() const;

iterator end() noexcept;
const_iterator end() const noexcept;

None
Returns an iterator which points to past-the-end element in the vector.
If vector object is constant qualified method returns constant random access iterator otherwise non-constatnt random access iterator.
This member function never throws an exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::end() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
Interthread Communication

If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −
public void wait()
Causes the current thread to wait until another thread invokes the notify().
public void notify()
Wakes up a single thread that is waiting on this object's monitor.
public void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.
class Chat {
   boolean flag = false;

   public synchronized void Question(String msg) {

      if (flag) {
         
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(msg);
      flag = true;
      notify();
   }

   public synchronized void Answer(String msg) {

      if (!flag) {
         
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(msg);
      flag = false;
      notify();
   }
}

class T1 implements Runnable {
   Chat m;
   String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };

   public T1(Chat m1) {
      this.m = m1;
      new Thread(this, "Question").start();
   }

   public void run() {
   
      for (int i = 0; i < s1.length; i++) {
         m.Question(s1[i]);
      }
   }
}

class T2 implements Runnable {
   Chat m;
   String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

   public T2(Chat m2) {
      this.m = m2;
      new Thread(this, "Answer").start();
   }

   public void run() {

      for (int i = 0; i < s2.length; i++) {
         m.Answer(s2[i]);
      }
   }
}

public class TestThread {

   public static void main(String[] args) {
      Chat m = new Chat();
      new T1(m);
      new T2(m);
   }
}
When the above program is complied and executed, it produces the following result −
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!

Above example has been taken and then modified from [https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Check if Object is of the Character Data type in R Programming - is.character() Function - GeeksforGeeks

03 Jun, 2020
is.character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type.
Syntax: is.character(Object)
Parameter:Object: It could be an array, list, vector, etc.
Example 1:
# R Program to illustrate # the use of is.character function  # Creating a vector of mixed datatypex1 <- c("Hello", "Geeks", 100)  # Creating a vector of Numeric datatypex2 <- c(10, 20, 30)  # Calling is.character() functionis.character(x1)is.character(x2)
Output:
[1] TRUE
[1] FALSE

Example 2:
# R Program to illustrate # the use of is.character function  # Create the vectors with different length vector1 <- c(1, 2, 3) vector2 <- c("GFG", "Geeks", "Hello")     # taking this vector as input result <- array(c(vector1, vector2), dim = c(3, 3, 2))   # Calling is.character() functionis.character(result)
Output:
[1] TRUE

R Data-types
R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Ruby - Command Line Options

Ruby is generally run from the command line in the following way −
$ ruby [ options ] [.] [ programfile ] [ arguments ... ]

The interpreter can be invoked with any of the following options to control the environment and behavior of the interpreter.
-a
Used with -n or -p to split each line. Check -n and -p options.
-c
Checks syntax only, without executing program.
-C dir
Changes directory before executing (equivalent to -X).
-d
Enables debug mode (equivalent to -debug).
-F pat
Specifies pat as the default separator pattern ($;) used by split.
-e prog
Specifies prog as the program from the command line. Specify multiple -e options for multiline programs.
-h
Displays an overview of command-line options.
-i [ ext]
Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file is deleted.
-I dir
Adds dir as the directory for loading libraries.
-K [ kcode]
Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF8; and a, A, n, or N for ASCII).
-l
Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.
-n
Places code within an input loop (as in while gets; ... end).
-0[ octal]
Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.
-p
Places code within an input loop. Writes $_ for each iteration.
-r lib
Uses require to load lib as a library before executing.
-s
Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines the corresponding variable.
-T [level]
Sets the level for tainting checks (1 if level not specified).
-v
Displays version and enables verbose mode.
-w
Enables verbose mode. If program file not specified, reads from STDIN.
-x [dir]
Strips text before #!ruby line. Changes directory to dir before executing if dir is specified.
-X dir
Changes directory before executing (equivalent to -C).
-y
Enables parser debug mode.
--copyright
Displays copyright notice.
--debug
Enables debug mode (equivalent to -d).
--help
Displays an overview of command-line options (equivalent to h).
--version
Displays version.
--verbose
Enables verbose mode (equivalent to -v). Sets $VERBOSE to true.
--yydebug
Enables parser debug mode (equivalent to -y).
Single character command-line options can be combined. The following two lines express the same meaning −
$ruby -ne 'print if /Ruby/' /usr/share/bin
   
$ruby -n -e 'print if /Ruby/' /usr/share/bin


    46 Lectures 
     9.5 hours 

 Eduonix Learning Solutions

    97 Lectures 
     7.5 hours 

 Skillbakerystudios

    227 Lectures 
     40 hours 

 YouAccel

    19 Lectures 
     10 hours 

 Programming Line

    51 Lectures 
     5 hours 

 Stone River ELearning

    39 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Java String endsWith() Method

❮ String Methods

Find out if the string ends with the specified characters:
String myStr = "Hello";
System.out.println(myStr.endsWith("Hel"));   // false
System.out.println(myStr.endsWith("llo"));   // true
System.out.println(myStr.endsWith("o"));     // true

Try it Yourself »

The endsWith() method checks whether a 
string ends with the specified character(s).
Tip: Use the startsWith() method to check whether a string 
starts with the specified character(s).
public boolean endsWith(String chars)

true - if the string ends with the specified character(s)
false - if the string does not end with the specified character(s)
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 to scan through a directory recursively in Python?


You can use the os.walk function to walk through the directory tree in python.
import os
for dirpath, dirs, files in os.walk("./my_directory/"):  
            for filename in files:
                        fname = os.path.join(dirpath,filename)
                        with open(fname) as myfile:
                                    print(myfile.read())
The above program recursively moves through the my_directory tree and prints contents of each file in the tree to the console output.
Python time localtime() Method

Pythom time method localtime() is similar to gmtime() but it converts number of seconds to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.
Following is the syntax for localtime() method −
time.localtime([ sec ])

sec − These are the number of seconds to be converted into structure struct_time representation. 
sec − These are the number of seconds to be converted into structure struct_time representation. 
This method does not return any value.
The following example shows the usage of localtime() method.
#!/usr/bin/python
import time

print "time.localtime() : %s" % time.localtime()
When we run above program, it produces following result −
time.localtime() : (2009, 2, 17, 17, 3, 38, 1, 48, 0)


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Arduino - switch case statement

Similar to the if statements, switch...case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in the case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.
The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.
switch (variable) { 
   case label:
   // statements
   break;
}

case label: { 
   // statements
   break;
}

default: { 
   // statements
   break;
}

Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a corresponding function (event) for each of these states. This is how we could switch the code to the appropriate routine −
switch (phase) {
   case 0: Lo(); break;
   case 1: Mid(); break;
   case 2: Hi(); break;
   default: Message("Invalid state!");
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
How can I pop-up a print dialog box using JavaScript?

To pop-up a print dialog box using JavaScript, use the print() method. With the dialog box, you can easily set the printing options like which printer to select for printing.
This is the dialog box −
You can try to run the following code to learn how to print a page −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button onclick="display()">Click to Print</button>
      <script>
         function display() {
            window.print();
         }
      </script>
   </body>
</html>
GATE | GATE CS 2020 | Question 52 - GeeksforGeeks

26 May, 2021
The number of permutations of the characters in LILAC so that no character appears in its original position, if the two L’s are indistinguishable, is ________ .
Note – This question was Numerical Type.(A) 12(B) 10(C) 8(D) 15Answer: (A)Explanation: There are 3 choices for the first slot, and then 2 for the third slot. That leaves one letter out of I,A,C unchosen and there are 2 slots that one might occupy. After that, the L′s must go in the 2 unfilled slots.
Hence the answer is,
3×2×1×2 = 12 
Option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
How to draw an ellipse in HTML5 SVG?

SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw an ellipse in HTML SVG, use the SVG <ellipse> element.
You can try to run the following code to learn how to draw an ellipse in HTML5 SVG −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
   position: relative;
   left: 10%;
   -webkit-transform: translateX(-20%);
   -ms-transform: translateX(-20%);
   transform: translateX(-20%);
}
</style>
<title>HTML5 SVG Ellipse</title>
</head>

<body>
<h2>HTML5 SVG Ellipse</h2>
<svg id = "svgelem" width = "300" height = "200" xmlns = "http://www.w3.org/2000/svg">
<ellipse cx = "120" cy = "50" rx = "100" ry = "50" fill = "blue" />
</svg>
</body>
</html>
math.Inf() Function in Golang With Examples

19 Oct, 2021
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find positive infinity (if sign >= 0) or negative infinity (if sign < 0) with the help of the Inf() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Inf() function. Syntax:  
func Inf(sign int) float64
Example 1: 
C
// Golang program to illustrate the// math.Inf() Functionpackage main import (    "fmt"    "math") // Main functionfunc main() {     // Finding positive infinity    // and negative infinity    // Using Inf() function    res_1 := math.Inf(-1)    res_2 := math.Inf(1)     // Displaying the result    fmt.Println("Result 1: ", res_1)    fmt.Println("Result 2: ", res_2) }
Output: 
Result 1: -Inf
Result 2: +Inf
Example 2: 
C
// Golang program to illustrate the// math.Inf() Functionpackage main import (    "fmt"    "math") // Main functionfunc main() {     // Finding positive infinity    // and negative infinity    // Using Inf() function    nvalue := math.Inf(2)    mvalue := math.Inf(-3)     fmt.Println("Positive infinity: ", nvalue)    fmt.Println("Negative infinity: ", mvalue) }
Output: 
Positive infinity:  +Inf
Negative infinity:  -Inf
 
sweetyty
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kotlin Grouping

17 Sep, 2019
The Kotlin standard library helps in grouping collection elements with the help of extension functions. Grouping means collecting items by category. Here, we have a groupBy() function which takes lambda function and returns a map. In this map, each key is the result of lambda and corresponding value is the list of elements.We can also use groupBy() function with second lambda expression, which is also called value transformation function. If we use two lambda functions then the produced key of keySelector mapped with the results of value transformation function instead of original elements.
Kotlin program to demonstrate using groupBy() function –
fun main(args: Array<String>) {    val fruits = listOf("apple", "apricot", "banana",        "cherries", "berries", "cucumber")    println(fruits.groupBy { it.first().toUpperCase() })    println(fruits.groupBy(keySelector = { it.first() },        valueTransform = { it.toUpperCase() }))}
Output:
{A=[apple, apricot], B=[banana, berries], C=[cherries, cucumber]}
{a=[APPLE, APRICOT], b=[BANANA, BERRIES], c=[CHERRIES, CUCUMBER]}

If we want to apply some operations to group elements then it can be done by applying the function to all group at a time with the help of groupingBy() function. An instance of grouping type will be returned.
We can perform these operations on groups:
eachcount(): it counts the items in each group.
fold() and reduce(): perform these operation on each group separately and return the result.
aggregate(): it is generic way of grouping means applying a specific operation subsequently to all the elements in each group and returns the result. So, it is used to implement custom operations.
Kotlin program to demonstrate groupingBy() function –
fun main(args: Array<String>) {    val fruits = listOf("apple", "apricot", "banana",        "cherries", "berries", "cucumber")    println(fruits.groupingBy { it.first() }.eachCount())}
Output:
{a=2, b=2, c=2}

Kotlin Collections
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Getting the list of all the matches Java regular expressions

Java does not provide any method to retrieve the list of all matches we need to use Lists and add the results to it in the while loop.
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ListOfMatches{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\\d+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      ArrayList list = new ArrayList();
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         list.add(matcher.group());
      }
      Iterator it = list.iterator();
      System.out.println("List of matches: ");
      while(it.hasNext()){
         System.out.println(it.next());
      }
   }
}
Enter input text:
sample 1432 text 53 with 363 numbers
List of matches:
1432
53
363