code-rag-bench/online-tutorials huggingface dataset:
Boost.Lexical_Cast in C++ - GeeksforGeeks

18 Apr, 2022
Boost.LexicalCast which is defined in the Library “boost/lexical_cast.hpp” provides a cast operator, boost::lexical_cast, that can convert numbers from strings to numeric types like int or double and vice versa. boost::lexical_cast is an alternative to functions like std::stoi(), std::stod(), and std::to_string(), which were added to the standard library in C++11. Now let see the Implementation of this function in a program. Examples:
Conversion
integer -> string
string- > integer
integer -> char
float- > string
Associated exceptions : If a conversion fails, an exception of type bad_lexical_cast, which is derived from bad_cast, is thrown. It throws an exception because the float 52.50 and the string “GeeksforGeeks” cannot be converted to a number of type int. 
CPP
// CPP program to illustrate// Boost.Lexical_Cast in C++#include "boost/lexical_cast.hpp"#include <bits/stdc++.h>using namespace std;using boost::lexical_cast;using boost::bad_lexical_cast;int main() {   // integer to string conversion  int s = 23;  string s1 = lexical_cast<string>(s);  cout << s1 << endl;   // integer to char conversion  array<char, 64> msg = lexical_cast<array<char, 64>>(45);  cout << msg[0] << msg[1] << endl;   // string to integer conversion in integer value  int num = lexical_cast<int>("1234");  cout << num << endl;   // bad conversion float to int  // using try and catch we display the error  try {    int num2 = lexical_cast<int>("52.20");  }   // To catch exception  catch (bad_lexical_cast &e) {    cout << "Exception caught : " << e.what() << endl;  }   // bad conversion string to integer character  // using try and catch we display the error  try {    int i = lexical_cast<int>("GeeksforGeeks");  }   // catching Exception  catch (bad_lexical_cast &e) {    cout << "Exception caught :" << e.what() << endl;  }   return 0;}
Output:-
23
45
1234
Exception caught : bad lexical cast: source type value could not be interpreted as target
Exception caught :bad lexical cast: source type value could not be interpreted as target
Reference :- http://www.boost.org/
C-Library
cpp-boost
CPP-Library
C++
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Destructors in C++
Polymorphism in C++
Sorting a vector in C++
INT_MAX and INT_MIN in C/C++ and Applications
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
List in C++ Standard Template Library (STL)
JavaFX - Layout Stackpane

If we use the Stack Pane, the nodes are arranged on top of another, just like in stack. The node added first is placed at the bottom of the stack and the next node is placed on top of it.
The class named StackPane of the package javafx.scene.layout represents the StackPane. This class contains a single property named alignment. This property represents the alignment of the nodes within the stack pane.
In addition to these, this class also provides a method named setMargin(). This method is used to set margin for the node within the stack pane.
The following program is an example of the StackPane layout. In this, we are inserting a Circle, Sphere and a Text in the same order.
Save this code in a file with the name StackPaneExample.java.
import javafx.application.Application; 
import javafx.collections.ObservableList; 
import javafx.geometry.Insets; 

import javafx.scene.Scene; 
import javafx.scene.layout.StackPane; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Circle; 
import javafx.scene.shape.Sphere;
 
import javafx.scene.text.Font; 
import javafx.scene.text.FontWeight; 
import javafx.scene.text.Text; 
import javafx.stage.Stage; 
         
public class StackPaneExample extends Application { 
   @Override 
   public void start(Stage stage) {                     
      //Drawing a Circle 
      Circle circle = new Circle(300, 135, 100); 
      circle.setFill(Color.DARKSLATEBLUE); 
      circle.setStroke(Color.BLACK);
      
      //Drawing Sphere 
      Sphere sphere = new Sphere(50); 
       
      //Creating a text 
      Text text = new Text("Hello how are you"); 
      
      //Setting the font of the text 
      text.setFont(Font.font(null, FontWeight.BOLD, 15));     
      
      //Setting the color of the text 
      text.setFill(Color.CRIMSON); 
      
      //setting the position of the text 
      text.setX(20); 
      text.setY(50);       
       
      //Creating a Stackpane 
      StackPane stackPane = new StackPane(); 
      
      //Setting the margin for the circle 
      stackPane.setMargin(circle, new Insets(50, 50, 50, 50));       
       
      //Retrieving the observable list of the Stack Pane 
      ObservableList list = stackPane.getChildren(); 
      
      //Adding all the nodes to the pane 
      list.addAll(circle, sphere, text); 
        
      //Creating a scene object 
      Scene scene = new Scene(stackPane);  
      
      //Setting title to the Stage 
      stage.setTitle("Stack Pane Example"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show();  
   }
   public static void main(String args[]){ 
      launch(args); 
   } 
} 
Compile and execute the saved java file from the command prompt using the following commands.
javac StackPaneExample.java 
java StackPaneExample

On executing, the above program generates a JavaFX window as shown below.

    33 Lectures 
     7.5 hours 

 Syed Raza

    64 Lectures 
     12.5 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    20 Lectures 
     4 hours 

 Emenwa Global, Ejike IfeanyiChukwu
 Print
 Add Notes
 Bookmark this page
What is the difference between Monitor and Lock in C#?

Both Monitor and lock provides a mechanism that synchronizes access to objects.
lock is the shortcut for Monitor.Enter with try and finally.
Lock is a shortcut and it's the option for the basic usage. If we need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), &
PulseAll() methods, then the Montior class is your option.
Example for Lock −
class Program{
static object _lock = new object();
static int Total;
public static void Main(){
   AddOneHundredLock();
   Console.ReadLine();
}
public static void AddOneHundredLock(){
   for (int i = 1; i <= 100; i++){
      lock (_lock){
         Total++;
      }
   }
}
Example for Monitor −
class Program{
   static object _lock = new object();
   static int Total;
   public static void Main(){
      AddOneHundredMonitor();
      Console.ReadLine();
   }
   public static void AddOneHundredMonitor(){
      for (int i = 1; i <= 100; i++){
         Monitor.Enter(_lock);
         try{
            Total++;
         }
         finally{
            Monitor.Exit(_lock);
         }
      }
   }
}
How do I change a MongoDB user's password?

You need to use changeUserPassword() to change a user’s password. Let us first create a user with some roles. Following is the query to create a user in MongoDB −
> use admin
switched to db admin
> db.createUser(
...    {
...       user: "Chris",
...       pwd: "chris",
...       roles: [ { role: "readWrite", db: "test" } ]
...    }
... );
Successfully added user: {
   "user" : "Chris",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      }
   ]
}
Let us display the user from test database −
> db.getUser("Chris");
This will produce the following output −
{
   "_id" : "admin.Chris",
   "user" : "Chris",
   "db" : "admin",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
   ]
}
Following is the query to change a MongoDB user's password.
> db.changeUserPassword("Chris", "123456");
The password has been changed.
SLF4J - Migrator

If you have a project in Jakarta Commons Logging (JCL) or, log4j or, java.util.logging (JUL) and you want to convert these projects to SLF4J, you can do so using the migrator tool provided in the SLF4J distribution.
SLF4J is a simple single jar file (slf4j-migrator.jar) and you can run it using the java –jar command.
To run it, in command prompt, browse through the directory where you have this jar file and execute the following command.
java -jar slf4j-migrator-1.8.0-beta2.jar
Starting SLF4J Migrator

This starts the migrator and you can see a standalone java application as −
As specified in the window, you need to check the type of migration you want to do and select the project directory and click on the button Migrate Project to SLF4J.
This tool goes to the source files you provide and performs simple modifications like changing the import lines and logger declarations from the current logging framework to SLF4j.
For example, let us suppose we have a sample log4j(2) project in eclipse with a single file as follows −
import org.apache.log4j.Logger;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class Sample {
   /* Get actual class name to be printed on */
   static Logger log = Logger.getLogger(Sample.class.getName());

   public static void main(String[] args)throws IOException,SQLException {
      log.debug("Hello this is a debug message");
      log.info("Hello this is an info message");
   }
}
To migrate the sample log4j(2) project to slf4j, we need to check the radio button from log4j to slf4j and select the directory of the project and click Exit to migrate.
The migrator changed the above code as follows. Here if you observe the import and logger statements have been modified.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class Sample {
   static Logger log = LoggerFactory.getLogger(Sample.class.getName());
   public static void main(String[] args)throws IOException,SQLException {
      log.debug("Hello this is a debug message");
      log.info("Hello this is an info message");
   }
}
Since you already have log4j.jar in your project, you need to add slf4j-api.jar and slf4jlog12.jar files to the project to execute it.
Following are the limitations of the SLF4J migrator.
Migrator will not modify build scripts like ant, maven and, ivy you need to do it yourself.
Migrator will not modify build scripts like ant, maven and, ivy you need to do it yourself.
Migrator does not support messages other than the String type.
Migrator does not support messages other than the String type.
Migrator does not support the FATAL level.
Migrator does not support the FATAL level.
While working with log4j, migrator will not migrate calls to PropertyConfigurator or DomConfigurator.
While working with log4j, migrator will not migrate calls to PropertyConfigurator or DomConfigurator.
 Print
 Add Notes
 Bookmark this page
What is the difference between $.closest() and $.parents() methods in jQuery?

The jQuery closest and parents method is used to set or get the first or all ancestor element, matching the selector. Let's see the difference below:
The closest() method begins with the current element and returns only the first ancestors matching the passed expression. This returned jQuery object has zero or one element.
You can try to run the following code to learn how to work with jQuery closest method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid blue;
    color: red;
    padding: 5px;
    margin:10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
    $("span").closest("ol").css({"color": "gray", "border": "5px solid maroon"});
 });
</script>
</head>

<body class="myclass">body
  <div style="width:500px;">div
    <ol>ol - This is the third ancestor
    <ol>ol - This is the second ancestor
    <ol>ol - This is the first ancestor
      <li>li - This is the direct parent element
        <span>demo</span>
      </li>
      </ol>
      </ol>
    </ol>  
  </div>
</body>
The parents() method begins with the parent element and returns all ancestors matching the passed expression. This method is different from closest(), since in this the returned jQuery object has zero or more than one element.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
 .myclass * {
    display: block;
    border: 5px solid blue;
    color: red;
    padding: 9px;
    margin: 14px;
 }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $("span").parents().css({"color": "green", "border": "4px solid green"});
  });
</script>
</head>

<body class="myclass">body
  <div style="width:600px;">div
    <ol>ol
      <li>li - This is the direct parent element
        <span>demo</span>
      </li>
    </ol>  
  </div>
</body>

</html>
vector insert() function in C++ STL

vector insert() function in C++ STL helps to increase the size of a container by inserting the new elements before the elements at the specified position.
It is a predefined function in C++ STL.
We can insert values with three types of syntaxes
1. Insert values by mentioning only the position and value:
vector_name.insert(pos,value);
2. Insert values by mentioning the position, value and the size:
vector_name.insert(pos,size,value);
3. Insert values in another empty vector form a filled vector by mentioning the position, where the values are to be inserted and iterators of filled vector:
empty_eector_name.insert(pos,iterator1,iterator2);
Begin
   Declare a vector v with values.
   Declare another empty vector v1.
   Declare another vector iter as iterator.
   Insert a value in v vector before the beginning.
   Insert another value with mentioning its size before the beginning.
   Print the values of v vector.
   Insert all values of v vector in v1 vector with mentioning the iterator of v vector.
   Print the values of v1 vector.
End.
 Live Demo
#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
   vector<int> v = { 50,60,70,80,90},v1;        //declaring v(with values), v1 as vector.
   vector<int>::iterator iter;                  //declaring an iterator
   iter = v.insert(v.begin(), 40);              //inserting a value in v vector before the beginning.
   iter = v.insert(v.begin(), 1, 30);           //inserting a value with its size in v vector before the beginning.
   cout << "The vector1 elements are: \n";
   for (iter = v.begin(); iter != v.end(); ++iter)
      cout << *iter << " "<<endl;             // printing the values of v vector
   v1.insert(v1.begin(), v.begin(), v.end()); //inserting all values of v in v1 vector.
   cout << "The vector2 elements are: \n";
   for (iter = v1.begin(); iter != v1.end(); ++iter)
      cout << *iter << " "<<endl;            // printing the values of v1 vector
   return 0;
}
The vector1 elements are:
30
40
50
60
70
80
90
The vector2 elements are:
30
40
50
60
70
80
90
Add given timestamps by overloading + operator in C++ Time Class - GeeksforGeeks

30 Aug, 2021
In C++, we can make operators to work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.
In this article, we will overload an operator ‘+’ in the Time class so that we can concatenate two timestamps by just using +.
Example: 
Input: T1 = 5:50:30, T2 = 7:20:34 Output: 13:11:4  
Approach: To achieve the + operator overloading, below steps/functions are made:
Class Time is defined in which there are 3 variables to store the value of hours, minutes and seconds respectively.
int HR, MIN, SEC;
where HR is for hours, 
      MIN is for minutes, and 
      SEC is for seconds
setTime() function to set values of HR, MIN and SEC.
void setTime(int x, int y, int z)
{
    x = HR;
    y = MIN;
    z = SEC;
}
showTime() function to display the time in a specific format (HH:MM:SS).
void showTime()
{
    cout << HR << ":" << MIN << ":" << SEC;
}
normalize() function to convert the resultant time into standard form.
Overloading of + operator to add time T1 and T2 using operator overloading.
Below is the C++ program implementing + overloading to add two timestamps:
C++
// C++ program to implement + operator// overloading to add two timestamps #include <iostream>using namespace std; // Time class templateclass Time {private:    int HR, MIN, SEC;     // Defining functionspublic:    // Functions to set the time    // in the Time class template    void setTime(int x, int y, int z)    {        HR = x;        MIN = y;        SEC = z;    }     // Function to print the time    // in HH:MM:SS format    void showTime()    {        cout << endl             << HR << ":" << MIN << ":" << SEC;    }     // Function to normalize the resultant    // time in standard form    void normalize()    {        MIN = MIN + SEC / 60;        SEC = SEC % 60;        HR = HR + MIN / 60;        MIN = MIN % 60;    }     // + Operator overloading    // to add the time t1 and t2    Time operator+(Time t)    {        Time temp;        temp.SEC = SEC + t.SEC;        temp.MIN = MIN + t.MIN;        temp.HR = HR + t.HR;        temp.normalize();        return (temp);    }}; // Driver codeint main(){    Time t1, t2, t3;    t1.setTime(5, 50, 30);    t2.setTime(7, 20, 34);     // Operator overloading    t3 = t1 + t2;     // Printing results    t1.showTime();    t2.showTime();    t3.showTime();     return 0;}
5:50:30
7:20:34
13:11:4
 
adnanirshad158
C++-Operator Overloading
CBSE - Class 12
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Pi(π) in C++ with Examples
Const keyword in C++
Handling the Divide by Zero Exception in C++
Why it is important to write "using namespace std" in C++ program?
isdigit() function in C/C++ with Examples
Dynamic _Cast in C++
Setting up Sublime Text for C++ Competitive Programming Environment
Java - String getChars() Method

This method copies characters from this string into the destination character array.
Here is the syntax of this method −
public void getChars(int srcBegin, int srcEnd, char[] dst,  int dstBegin)

Here is the detail of parameters −
srcBegin − index of the first character in the string to copy.
srcBegin − index of the first character in the string to copy.
srcEnd − index after the last character in the string to copy.
srcEnd − index after the last character in the string to copy.
dst − the destination array.
dst − the destination array.
dstBegin − the start offset in the destination array.
dstBegin − the start offset in the destination array.
It does not return any value but throws IndexOutOfBoundsException.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialspoint.com");
      char[] Str2 = new char[7];
      try {
         Str1.getChars(2, 9, Str2, 0);
         System.out.print("Copied Value = " );
         System.out.println(Str2 );
      } catch ( Exception ex) {
         System.out.println("Raised exception...");
      }
   }
}
This will produce the following result −
Copied Value = lcome t


    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
Matplotlib.axis.Axis.set_units() function in Python - GeeksforGeeks

08 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_units() function in axis module of matplotlib library is used to set the units for axis.  
Syntax: Axis.set_units(self, u) 
Parameters: This method accepts the following parameters. 
u: This parameter is the units tag.
Return value: This method does not return any value. 
Below examples illustrate the matplotlib.axis.Axis.set_units() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport randomimport matplotlib.lines as linesimport matplotlib.patches as patchesimport matplotlib.text as textimport matplotlib.collections as collections  from basic_units import cm, inchimport numpy as npimport matplotlib.pyplot as plt  fig, ax = plt.subplots()ax.xaxis.set_units(cm)ax.yaxis.set_units(cm)  np.random.seed(19680801)  line = lines.Line2D([2*cm, 8*cm], [0*cm, 2.5*cm],                    lw=2, color='green', axes=ax)ax.add_line(line)  t = text.Text(3*cm, 2.5*cm,              'Line 1',              ha='left',              va='bottom',              axes=ax,              color='red')ax.add_artist(t)  ax.set_xlim(-1*cm, 10*cm)ax.set_ylim(-1*cm, 10*cm)  ax.grid(True)  fig.suptitle("""matplotlib.axis.Axis.set_units()function Example\n""", fontweight ="bold")        plt.show()
Output: 
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport numpy as npimport matplotlib.pyplot as pltfrom basic_units import secs  # create masked arraydata = (1, 2, 3, 4, 5, 6, 7, 8)mask = (1, 0, 1, 0, 0, 0, 1, 0)xsecs = secs * np.ma.MaskedArray(data, mask, float)  fig, ax1 = plt.subplots()  ax1.scatter(xsecs, xsecs)ax1.yaxis.set_units(secs)  ax1.grid()  fig.suptitle("""matplotlib.axis.Axis.set_units()function Example\n""", fontweight ="bold")        plt.show()
Output: 
 
Matplotlib-Axis Class
Python-matplotlib
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 Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Is it possible to assign a numeric value to an enum in Java?

Yes, it's possible to assign a numeric value to an enum.
Enum in Java is used to represent a list of predefined values. Most of the time, we probably not care about the associated value of an enum. However, there might be some times when we need to assign specific values to an enum.
import java.util.Enumeration;
import java.util.Vector;

public class EnumerationExample {
   public static void main(String[] args) {
      Vector vec = new Vector(4);
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(1);
      Enumeration<Integer> e = vec.elements();
      System.out.println("Numbers in the enumeration are :- ");
      while (e.hasMoreElements()) {
          System.out.println("Number = " + e.nextElement());
      }
   }
}
Numbers in the enumeration are :-
Number = 4
Number = 3
Number = 2
Number = 1
Java Examples - Create directories recursively

How to create directories recursively ?
Following example shows how to create directories recursively with the help of file.mkdirs() methods of File class.
import java.io.File;

public class Main {
   public static void main(String[] args) {
      String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
      File file = new File(directories);
      boolean result = file.mkdirs();
      System.out.println("Status = " + result);
   }
}
The above code sample will produce the following result.
Status = true

 Print
 Add Notes
 Bookmark this page
Java Program to calculate Compound Interest

Following is the program to calculate Compound Interest in Java −
 Live Demo
import java.io.*;
public class Demo{
   public static void main(String args[]){
      double princ = 456000, rt = 9.75, tm = 7;
      double comp_int = princ *(Math.pow((1 + rt / 100), tm));
      System.out.println("The compound interest for the given principle amount, rate and time is "+          comp_int);
   }
}
The compound interest for the given principle amount, rate and time is 874573.9655622267
A class named Demo contains the main function wherein a principal value, a rate and a time are initialized. The formula for compound interest, principal * ((1 + rate/100) power time) is initialized to a value and the output is calculated. This is displayed on the console.
Style every disabled <input> element with CSS

To style every disabled <input> element, use the CSS :disabled selector. You can try to run the following code to style disabled element −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         input:enabled {
            background: blue;
         }
         input:disabled {
            background: red;
         }
      </style>
   </head>
   <body>
      <form action = "">
         Subject <input type = "text" name = "subject"><br>
         Student: <input type = "text" name = "student"><br>
         Age: <input type = "number" name = "age" disabled><br>
      </form>
   </body>
</html>
Count Derangements (Permutation such that no element appears in its original position) in C++

Derangement is permutation of N numbers such that no number appears at original position. For
example one possible derangement of { 1,2,3 } is { 2,1,3 }. No element in this is at its original
position. The goal here is to count the possible derangements for N numbers.
We will do this using a recursive solution. For following no. of elements −
N=0, no derangement, return 1
N=1, only one number, return 0
N=2, only one swap of position possible, { 1,2 } → { 2,1 }, return 1
N=3, 2 possible permutations eg, { 1,2,3 } → { 2,3,1 }, { 3,1,2 } count 2
N=4, 9 possible permutations
.......................
N, (N-1)*( permutation(N-1) + permutation(N-2) )
For all elements in an array,
Element at index 0 has n-1 positions that it can take,
Element at index 0 has n-1 positions that it can take,
If any element at index i is placed at index 0 then, arr[i] and arr[0] are swapped. Now n-2
elements are there for calculation.
If any element at index i is placed at index 0 then, arr[i] and arr[0] are swapped. Now n-2
elements are there for calculation.
If element at index i is not placed at index 0 then for n-1 elements there are n-2 choices.
If element at index i is not placed at index 0 then for n-1 elements there are n-2 choices.
Diagram
Arr[] = { 1, 2 }
No. of derangements : 1
Explanation − Positions of 1 and 2 are index 0 and 1. Only position they can get is swapping original positions. { 2,1 }
Arr[] = { 1, 2, 3 }
No. of derangements : 2
Explanation − Positions of 1,2 and 3 are index 0,1,2.
1 can be placed at index 1 and 2, 2 can be placed at index 0 and 3 and 3 can be placed at index
0 and 1.
{ 2,3,1 } and { 3,1,2 } are 2 derangements.
Integer Num stores the count of numbers present.
Integer Num stores the count of numbers present.
Recursive function derangements(int N) takes the count of numbers as input and
returns the no. of derangements.
Recursive function derangements(int N) takes the count of numbers as input and
returns the no. of derangements.
The return statements for N=0,1,2 are handling the base cases for which permutations
are already calculated as 1,0 and 1.
The return statements for N=0,1,2 are handling the base cases for which permutations
are already calculated as 1,0 and 1.
When N>2 then recursive calls to derangements() is done using the formula,(N-1)* ( derangements ( N-1) + derangements ( N-2) ).
When N>2 then recursive calls to derangements() is done using the formula,
(N-1)* ( derangements ( N-1) + derangements ( N-2) ).
When backtracking starts, the count is computed and returned.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int derangements(int N){
   if (N == 0)
      return 1;
   if (N == 1)
      return 0;
   if (N == 2)
      return 1;
   return (N - 1) * (derangements(N - 1) + derangements(N - 2));
}
int main(){
   int Numbers=5;
   cout<<"Number of Derangements :"<<derangements(Numbers);
}
Number of Derangements :44
Cast string to date in specific format in SAP HANA

I think you just need to use ‘TO_VARCHAR’ and ‘TO_DATE’ functions.
SELECT TO_VARCHAR(TO_DATE(<your field>, 'YYYYMMDD'), 'YYYY-MM-DD') FROM <Table>
The Queue Class in Javascript

Here is the complete implementation of the Queue class −
class Queue {
   constructor(maxSize) {
      // Set default max size if not provided
      if (isNaN(maxSize)) {
         maxSize = 10;
      }
      this.maxSize = maxSize;
      // Init an array that'll contain the queue values.
      this.container = [];
    }
   // Helper function to display all values while developing
   display() {
      console.log(this.container);
   }
   // Checks if queue is empty
   isEmpty() {
      return this.container.length === 0;
   }
   // checks if queue is full
   isFull() {
      return this.container.length >= this.maxSize;
   }
   enqueue(element) {
      // Check if Queue is full
      if (this.isFull()) {
         console.log("Queue Overflow!"); return;
      }
      // Since we want to add elements to end, we'll just push them.
      this.container.push(element);
   }
   dequeue() {
      // Check if empty
      if (this.isEmpty()) {
         console.log("Queue Underflow!");
         return;
      }
      return this.container.shift();
   }
   peek() {
      if (this.isEmpty()) {
         console.log("Queue Underflow!");
         return;
      }
      return this.container[0];
   }
   clear() {
      this.container = [];
   }
}
How to create a combination of pairs from a vector in R?

To create a combination of pairs, we can use the combn function. This function will be helpful to use the vector length and the value 2 that represents a pair to create the combinations. Although, this is enough but we can transpose the output to get a better−looking output.
 Live Demo
x1<−rpois(6,5)
x1
[1] 5 3 7 4 8 2
Creating pair combinations for values of x1 −
t(combn(x1,2))
[,1] [,2]
[1,] 5 3
[2,] 5 7
[3,] 5 4
[4,] 5 8
[5,] 5 2
[6,] 3 7
[7,] 3 4
[8,] 3 8
[9,] 3 2
[10,] 7 4
[11,] 7 8
[12,] 7 2
[13,] 4 8
[14,] 4 2
[15,] 8 2
 Live Demo
x2<−LETTERS[1:5]
Creating pair combinations for values of x2 −
t(combn(x2,2))
[,1] [,2]
[1,] "A" "B"
[2,] "A" "C"
[3,] "A" "D"
[4,] "A" "E"
[5,] "B" "C"
[6,] "B" "D"
[7,] "B" "E"
[8,] "C" "D"
[9,] "C" "E"
[10,] "D" "E"
 Live Demo
x3<−c("F1","F2","F3","F4","F5","F6")
Creating pair combinations for values of x3 −
t(combn(x3,2))
[,1] [,2]
[1,] "F1" "F2"
[2,] "F1" "F3"
[3,] "F1" "F4"
[4,] "F1" "F5"
[5,] "F1" "F6"
[6,] "F2" "F3"
[7,] "F2" "F4"
[8,] "F2" "F5"
[9,] "F2" "F6"
[10,] "F3" "F4"
[11,] "F3" "F5"
[12,] "F3" "F6"
[13,] "F4" "F5"
[14,] "F4" "F6"
[15,] "F5" "F6"
 Live Demo
x4<−sample(0:9,5)
x4
[1] 5 6 2 7 4
Creating pair combinations for values of x4 −
t(combn(x4,2))
[,1] [,2]
[1,] 5 6
[2,] 5 2
[3,] 5 7
[4,] 5 4
[5,] 6 2
[6,] 6 7
[7,] 6 4
[8,] 2 7
[9,] 2 4
[10,] 7 4
 Live Demo
x5<−round(rnorm(5),0)
x5
[1] 0 1 −1 1 0
Creating pair combinations for values of x5 −
t(combn(x5,2))
[,1] [,2]
[1,] 0 1
[2,] 0 −1
[3,] 0 1
[4,] 0 0
[5,] 1 −1
[6,] 1 1
[7,] 1 0
[8,] −1 1
[9,] −1 0
[10,] 1 0
ES6 - Array Method every()

every method tests whether all the elements in an array passes the test implemented by the provided function.
array.every(callback[, thisObject]); 

callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns true if every element in this array satisfies the provided testing function.
function isBigEnough(element, index, array) { 
   return (element >= 10); 
} 
var passed = [12, 5, 8, 130, 44].every(isBigEnough); 
console.log("Test Value : " + passed );  
Test Value : false


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
Convert a Character Object to Integer in R Programming - as.integer() Function - GeeksforGeeks

16 Jun, 2020
as.integer() function in R Language is used to convert a character object to integer object.
Syntax: as.integer(x)
Parameters:x: Character Object
Example 1:
# R program to convert a character object# to an integer object  # Calling as.integer() functionas.integer("4")as.integer("1.6")as.integer("-3.2")as.integer("0x400")
Output:
[1] 4
[1] 1
[1] -3
[1] 1024

Example 2:
# R program to convert a character object# to an integer object  # Creating a vectorx <- c(1, 2, 3, 4, 5)  # Check if the vector is an integeris.integer(x)  # Convert to integerx1 <- as.integer(x)x1  # Calling is.integer() functionis.integer(x1)
Output:
[1] FALSE
[1] 1 2 3 4 5
[1] TRUE

R Math-Function
R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Adding Text to Plots in R programming - text() and mtext () Function
Calculate Standard Error in R
Compute Cumulative Log Normal Probability Density in R Programming - plnorm() Function
Identify and Remove Duplicate Data in R
Specify Reference Factor Level in Linear Regression in R
Add Titles to a Graph in R Programming - title() Function
Filter multiple values on a string column in R using Dplyr
Display the internal Structure of an Object in R Programming - str() Function
Export List to CSV or text File in R
How To Reorder Boxplots in R with ggplot2?
How to display star for significance in base R boxplot?

To display the star for significance in a base R boxplot, we can use text function. The text function will be helpful in defining the star sign (that is asterisk or *). If the significance is high then three stars are used and the significance is low then a single star is used. We need to use the appropriate position using x and y values.
 Live Demo
Consider the below data frame −
x<−sample(1:3,20,replace=TRUE)
y<−c(rpois(10,10),rpois(10,2))
df<−data.frame(x,y)
df
x y
1 1 7
2 3 13
3 1 11
4 1 8
5 2 8
6 2 12
7 2 9
8 1 10
9 1 7
10 3 9
11 1 2
12 3 0
13 3 1
14 2 1
15 3 2
16 3 3
17 2 2
18 2 1
19 2 4
20 2 2
Creating the boxplot of y for categories in x −
boxplot(y~x)
Adding star to category 1 in the above plot −
text(x=1,y=max(df$y[df$x==1]),"***",pos=3,cex=1.5)
Generating a unique random 10 character string using MySQL?

In order to generate a 10 character string, we can use inbuilt functions ‘rand()’ and ‘char()’. The following is the query to generate random 10 character string.
mysql>  SELECT concat(
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97),
   - > char(round(rand()*25)+97)
   - > )AS Random10CharacterString;
Here is the output showing random 10 character string.
+-------------------------+
| Random10CharacterString |
+-------------------------+
| duscikyspy              |
+-------------------------+
1 row in set (0.00 sec)

The following is the query to generate random characters in upper case.
mysql> select concat(
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65),
   - > char(round(rand()*25)+65)
   - > )AS Random10CharacterString;
The following is the output.
+-------------------------+
| Random10CharacterString |
+-------------------------+
| WMWWVOIXPF              |
+-------------------------+
1 row in set (0.00 sec)

The above output displays random characters in upper case.
Design and Analysis Spanning Tree

A spanning tree is a subset of an undirected Graph that has all the vertices connected by minimum number of edges.
If all the vertices are connected in a graph, then there exists at least one spanning tree. In a graph, there may exist more than one spanning tree.
A spanning tree does not have any cycle.
Any vertex can be reached from any other vertex.
In the following graph, the highlighted edges form a spanning tree.
A Minimum Spanning Tree (MST) is a subset of edges of a connected weighted undirected graph that connects all the vertices together with the minimum possible total edge weight. To derive an MST, Prim’s algorithm or Kruskal’s algorithm can be used. Hence, we will discuss Prim’s algorithm in this chapter.
As we have discussed, one graph may have more than one spanning tree. If there are n number of vertices, the spanning tree should have n - 1 number of edges. In this context, if each edge of the graph is associated with a weight and there exists more than one spanning tree, we need to find the minimum spanning tree of the graph.
Moreover, if there exist any duplicate weighted edges, the graph may have multiple minimum spanning tree.
In the above graph, we have shown a spanning tree though it’s not the minimum spanning tree. The cost of this spanning tree is (5 + 7 + 3 + 3 + 5 + 8 + 3 + 4) = 38.
We will use Prim’s algorithm to find the minimum spanning tree.
Prim’s algorithm is a greedy approach to find the minimum spanning tree. In this algorithm, to form a MST we can start from an arbitrary vertex.
Algorithm: MST-Prim’s (G, w, r) 
for each u є G.V 
   u.key = ∞ 
   u.∏ = NIL 
r.key = 0 
Q = G.V 
while Q ≠ Ф 
   u = Extract-Min (Q) 
   for each v є G.adj[u] 
      if each v є Q and w(u, v) < v.key 
         v.∏ = u 
         v.key = w(u, v) 

The function Extract-Min returns the vertex with minimum edge cost. This function works on min-heap.
Using Prim’s algorithm, we can start from any vertex, let us start from vertex 1.
Vertex 3 is connected to vertex 1 with minimum edge cost, hence edge (1, 2) is added to the spanning tree.
Next, edge (2, 3) is considered as this is the minimum among edges {(1, 2), (2, 3), (3, 4), (3, 7)}.
In the next step, we get edge (3, 4) and (2, 4) with minimum cost. Edge (3, 4) is selected at random.
In a similar way, edges (4, 5), (5, 7), (7, 8), (6, 8) and (6, 9) are selected. As all the vertices are visited, now the algorithm stops.
The cost of the spanning tree is (2 + 2 + 3 + 2 + 5 + 2 + 3 + 4) = 23. There is no more spanning tree in this graph with cost less than 23.

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
C Program to check if a number belongs to a particular base or not

Given a number as a string and a base; the task is to check whether the given number of is of that given base or not.
We have to check the number and the base according to the number system in which there are bases like 2 for a binary number, 8 for an octal number, 10 for decimal number and 16 for a Hexadecimal number. According to this we have to find whether the given number in a string belongs to a particular base or not, If it belongs to a particular base then we have to print “Yes” on the output screen; else “No” on an output screen.
Like we know that, the number/expression “1A6” is of the base 16 and “1010” is of base 2, but this can be judged by just visually analysis now we have to find a way to solve the problem with help of a program.
Input: str = “1010”, base =2
Output: yes
Input: str = “1AA4”, base = 16
Output: yes
Input: str = “1610”, base = 2
Output: No
Approach we will be using to solve the given problem −
Check if the base lies between 2 to 16.
Then will check each digit of a strig belongs to the particular base or not.
If it belongs to then return true, else false.
Start
Step 1 -> In function bool isInGivenBase(char str[], int base)
   If base > 16 then,
      Return false
   Else If base <= 10 then,
   Loop For i = 0 and i < strlen(str) and i++
      If !(str[i] >= '0' and str[i] < ('0' + base)) then,
         Return false
      Else
      Loop For i = 0 and i < strlen(str) and i++
         If NOT ((str[i] >= '0' && str[i] < ('0' + base)) ||
            (str[i] >= 'A' && str[i] < ('A' + base – 10) ) then,
            Return false
            Return true
   Step 2 -> In function int main()
      Set str[] = {"AF87"}
      If isInGivenBase(str, 16) then,
         Print "yes "
      Else
         Print "No "
Stop
#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
   // Allowed bases are till 16 (Hexadecimal)
   if (base > 16)
      return false;
      // If base is below or equal to 10, then all
      // digits should be from 0 to 9.
   else if (base <= 10) {
      for (int i = 0; i < strlen(str); i++)
      if (!(str[i] >= '0' and
         str[i] < ('0' + base)))
         return false;
   }
   // If base is below or equal to 16, then all
   // digits should be from 0 to 9 or from 'A'
   else {
      for (int i = 0; i < strlen(str); i++)
      if (! ((str[i] >= '0' &&
         str[i] < ('0' + base)) ||
         (str[i] >= 'A' &&
         str[i] < ('A' + base - 10))
      ))
      return false;
   }
   return true;
}
// Driver code
int main() {
   char str[] = {"AF87"};
   if (isInGivenBase(str, 16))
      printf("yes\n");
   else
      printf("No\n");
   return 0;
}
yes
How can I represent an infinite number in Python?

A number equivalent to infinity can be assigned to a float variable by putting 'inf' as argument to float() function
>>> a=float('inf')
>>> a
inf
It is also possible to achieve same effect by assigning inf constant in math module
>>> import math
>>> a=math.inf
>>> a
inf
How to get all the Get-Process properties using PowerShell?

Get-Process shows the default properties only. To get all the properties of Get-Process, we need to pipeline Format-List * (fl *).
Get-Process | Format-List *
Name                       : AcroRd32
Id                         : 8052
PriorityClass              : Normal
FileVersion                : 11.0.23.22
HandleCount                : 616
WorkingSet                 : 17453056
PagedMemorySize            : 114597888
PrivateMemorySize          : 114597888
VirtualMemorySize          : 374849536
TotalProcessorTime         : 00:00:39.6562500
SI                         : 1
Handles                    : 616
VM                         : 374849536
WS                         : 17453056
PM                         : 114597888
NPM                        : 51344
Path                       : C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe
Company                    : Adobe Systems Incorporated
CPU                        : 39.65625
ProductVersion             : 11.0.23.22
Description                : Adobe Reader
Product                    : Adobe Reader
__NounName                 : Process
BasePriority               : 8
ExitCode                   :
HasExited                  : False
ExitTime                   :
Handle                     : 3908
SafeHandle                 : Microsoft.Win32.SafeHandles.SafeProcessHandle
MachineName                : .
MainWindowHandle           : 330506
MainWindowTitle            : TC Nutanix Trainer Notes drn 1_7.pdf - Adobe Reader
MainModule                 : System.Diagnostics.ProcessModule (AcroRd32.exe)
MaxWorkingSet              : 1413120
MinWorkingSet              : 204800
Modules                    : {System.Diagnostics.ProcessModule (AcroRd32.exe), System.Diagnostics.ProcessModule
                             (ntdll.dll), System.Diagnostics.ProcessModule (wow64.dll),
                             System.Diagnostics.ProcessModule (wow64win.dll)...}
NonpagedSystemMemorySize   : 51344
NonpagedSystemMemorySize64 : 51344
PagedMemorySize64          : 114597888
PagedSystemMemorySize      : 493472
PagedSystemMemorySize64    : 493472
PeakPagedMemorySize        : 120074240
PeakPagedMemorySize64      : 120074240
PeakWorkingSet             : 147730432
PeakWorkingSet64           : 147730432
PeakVirtualMemorySize      : 388337664
PeakVirtualMemorySize64    : 388337664
PriorityBoostEnabled       : True
PrivateMemorySize64        : 114597888
PrivilegedProcessorTime    : 00:00:18.0781250
ProcessName                : AcroRd32
ProcessorAffinity          : 15
Responding                 : True
SessionId                  : 1
StartInfo                  : System.Diagnostics.ProcessStartInfo
StartTime                  : 27-12-2019 06:54:09
SynchronizingObject        :
Threads                    : {1388, 16120, 15236, 18948...}
UserProcessorTime          : 00:00:21.5781250
VirtualMemorySize64        : 374849536
EnableRaisingEvents        : False
StandardInput              :
StandardOutput             :
StandardError              :
WorkingSet64               : 17453056
Site                       :
Container                  :
How to Shift Inline Elements When Text Bold on Hover using CSS ?

08 Feb, 2022
When we will use a:hover pseudo-class to add a bold effect to the inline elements then we observe that whenever we hover over elements with the mouse, the elements to the right side of the mouse gets shifted to the right. This is not a good user experience thus needs to be removed. We can use the letter-spacing CSS property to fix this issue and make non-shifting inline elements. The letter-spacing is a CSS property that is used to increase or decrease the space between characters in a text. This CSS property can be used to prevent the shifting of the inline elements which get bold when we hover over them. Below is the working example of the problem and solution to it. 
Syntax:  
 .class_name { letter-spacing: value }
Example:  
html
<!DOCTYPE html><html> <head>    <style>        li {            list-style: none;            display: inline;        }                 .nav a {            letter-spacing: 0.36px;        }                 li a:link,        li a:visited {            text-decoration: none;            color: #000;        }                 li a:hover {            text-decoration: none;            font-weight: bold;        }                 .nav li a:hover {            text-decoration: none;            font-weight: bold;            letter-spacing: 0;        }    </style></head> <body>    <h3>Before:</h3>    <ul>        <li><a href="#">GeeksforGeeks 1</a></li>        <li><a href="#">GeeksforGeeks 2</a></li>        <li><a href="#">GeeksforGeeks 3</a></li>    </ul>    <h3>After:</h3>    <ul class="nav">        <li><a href="#">GeeksforGeeks 4</a></li>        <li><a href="#">GeeksforGeeks 5</a></li>        <li><a href="#">GeeksforGeeks 6</a></li>    </ul>     <body> </html>               
Output:  
 
blalverma92
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.