code-rag-bench/online-tutorials huggingface dataset:
How to create a new local user in windows using PowerShell?

To create a new local user in the Windows operating system using PowerShell, we can use the New-LocalUser cmdlet. The below command will create the TestUser with no password.
New-LocalUser -Name TestUser -NoPassword
Name Enabled Description
---- ------- -----------
TestUser True
TestUser account has been enabled here. To provide the password for the user, the password should be in the secure string format. We can pass the password as shown below.
$pass = "Admin@123" | ConvertTo-SecureString -AsPlainText
-Force
New-LocalUser -Name TestUser -Password $pass
The above commands will create the TestUser with the password. To add the password and account-related settings we can directly provide parameters but for ease, we will use the splatting method as shown below.
$Localuseraccount = @{
   Name = 'TestUser'
   Password = ("Admin#123" | ConvertTo-SecureString -AsPlainText -Force)
   AccountNeverExpires = $true
   PasswordNeverExpires = $true
   Verbose = $true
}

New-LocalUser @Localuseraccount
The above command will create testuser with a password and set its property to Account Never Expires and Password Never Expires.
How to wait until an element is present in Selenium?

We can wait until an element is present in Selenium webdriver. This can be done with the help of synchronization concept. We have an explicit wait condition where we can pause or wait for an element before proceeding to the next step.
The explicit wait waits for a specific amount of time before throwing an exception. To verify if an element is present, we can use the expected condition presenceOfElementLocated.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementPresenceWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/about/about_careers.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element and click()
      WebElement l=driver.findElement(By.linkText("Terms of Use"));
      l.click();
      // explicit wait condition
      WebDriverWait w = new WebDriverWait(driver,3);
      // presenceOfElementLocated condition
      w.until(ExpectedConditions.presenceOfElementLocated (By.cssSelector("h1")));
      // get text of element and print
      System.out.println("Element present having text:" + l.getText());
      driver.quit()
   }
}
C++ iomanip Library - setfill Function

The C++ function  std::setfill behaves as if member fill were called with c as argument on the stream on which it is inserted as a manipulator (it can be inserted on output streams).
It is used to sets c as the stream's fill character.
Following is the declaration for std::setfill function.
setfill (char_type c);
c − The new fill character for the stream. char_type is the type of characters used by the stream (i.e., its first class template parameter, charT).
It returns unspecified. This function should only be used as a stream manipulator.
Basic guarantee − if an exception is thrown, the stream is in a valid state.
The stream object on which it inserted is modified. Concurrent access to the same stream object may introduce data races.
In below example explains about setfill function.
#include <iostream>
#include <iomanip>

int main () {
   std::cout << std::setfill ('x') << std::setw (10);
   std::cout << 77 << std::endl;
   return 0;
}
Let us compile and run the above program, this will produce the following result −
xxxxxxxx77

 Print
 Add Notes
 Bookmark this page
Find all divisors of a natural number - Set 1 in C++

In this tutorial, we are going to write a program that finds all the divisors of a natural number. It's a straightforward problem. Let's see the steps to solve it.
Initialize the number.
Initialize the number.
Write a loop that iterates from 1 to the given number.Check whether the given number is divisible by the current number or not.If the above condition satisfies, then print the current number.
Write a loop that iterates from 1 to the given number.
Check whether the given number is divisible by the current number or not.
Check whether the given number is divisible by the current number or not.
If the above condition satisfies, then print the current number.
If the above condition satisfies, then print the current number.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void findDivisors(int n) {
   for (int i = 1; i <= n; i++) {
      if (n % i == 0) {
         cout << i << " ";
      }
   }
   cout << endl;
}
int main() {
   findDivisors(65);
   return 0;
}
If you run the above code, then you will get the following result.
1 5 13 65
If you have any queries in the tutorial, mention them in the comment section.
JavaScript String - localeCompare() Method

This method returns a number indicating whether a reference string comes before or after or is the same as the given string in sorted order.
The syntax of localeCompare() method is −
string.localeCompare( param )

param − A string to be compared with string object.
0 − If the string matches 100%.
0 − If the string matches 100%.
1 − no match, and the parameter value comes before the string object's value in the locale sort order
1 − no match, and the parameter value comes before the string object's value in the locale sort order
-1 −no match, and the parameter value comes after the string object's value in the local sort order
-1 −no match, and the parameter value comes after the string object's value in the local sort order
Try the following example.
<html>
   <head>
      <title>JavaScript String localeCompare() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str1 = new String( "This is beautiful string" );
         var index = str1.localeCompare( "XYZ" );
         document.write("localeCompare first :" + index ); 
         
         document.write("<br />" );          
         var index = str1.localeCompare( "AbCD ?" );
         document.write("localeCompare second :" + index ); 
      </script>      
   </body>
</html>
localeCompare first :-1
localeCompare second :1  


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
C/C++ program for calling main() in main() - GeeksforGeeks

28 Jul, 2021
Given a number N, the task is to write C/C++ program to print the number from N to 1 by calling the main() function using recursion.Examples:  
Input: N = 10 Output: 10 9 8 7 6 5 4 3 2 1Input: N = 5 Output: 5 4 3 2 1  
 
Approach:
Use static variable to initialise the given number N.Print the number N and decrement it.Call the main() function recusrsively after above step.
Use static variable to initialise the given number N.
Print the number N and decrement it.
Call the main() function recusrsively after above step.
Below is the implementation of the above approach: 
C
C++
// C program to illustrate calling// main() function in main() itself#include "stdio.h" // Driver Codeint main(){     // Declare a static variable    static int N = 10;     // Condition for calling main()    // recursively    if (N > 0) {        printf("%d ", N);        N--;        main();    }}
// C++ program to illustrate calling// main() function in main() itself#include "iostream"using namespace std; // Driver Codeint main(){    // Declare a static variable    static int N = 10;     // Condition for calling main()    // recursively until N is 0    if (N > 0) {        cout << N << ' ';        N--;        main();    }}
10 9 8 7 6 5 4 3 2 1
 
Time Complexity: O(N), where N is the given number. 
akshaysingh98088
C Language
C Programs
C++
C++ Programs
GATE
Recursion
Stack
Recursion
Stack
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
HTTP headers | Content-Range - GeeksforGeeks

23 Oct, 2019
The Content-Range HTTP header is a response header that indicates where a partial message belongs in a full body massage. This header is sent with a partial entity-body to specify where in the full entity-body the partial body should be applied.
Syntax:
Content-Range: <unit> <range-start>-<range-end>/<size>
Content-Range: <unit> <range-start>-<range-end>/*
Content-Range: <unit> */<size>
Directives:
<unit>: This specifies the unit of content range. This value is usually in bytes.
<range-start>: An integer that specifies the beginning of the requested range in a given unit.
<range-end>: An integer that specifies the ending of the requested range in a given unit.
<size>: This specifies the total size of the document. The ‘*’ is used when the value is unknown.
Examples:
Content-Range: bytes 500-1000/65989
It specifies the unit of the range as bytes and states the range-start as 500 bytes while the range-end as 1000 bytes. The total size of the document is 65989 bytes.
Content-Range: bytes 50-1000/*
It specifies the unit of the range as bytes and states the range-start as 50 bytes while the range-end as 1000 bytes. The total size of the document is unknown.
Supported Browsers The following browsers are compatible with HTTP Content-Range:
Google Chrome
Internet Explorer
Opera
Firefox
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
Node.js fs.readFileSync() Method
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
Python | Pandas Series.dt.weekofyear

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.weekofyear attribute return a numpy array containing the week ordinal of the year in the underlying data of the given series object.
Syntax: Series.dt.weekofyear
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.weekofyear attribute to return the week ordinal of the year in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',               '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.weekofyear attribute to return the week ordinal of the year in the underlying data of the given Series object.
# return the week ordinal# of the yearresult = sr.dt.weekofyear  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.weekofyear attribute has successfully accessed and returned the week ordinal of the year in the underlying data of the given series object. Example #2 : Use Series.dt.weekofyear attribute to return the week ordinal of the year in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                        periods = 5, freq = 'M'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.weekofyear attribute to return the week ordinal of the year in the underlying data of the given Series object.
# return the week ordinal# of the yearresult = sr.dt.weekofyear  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.weekofyear attribute has successfully accessed and returned the week ordinal of the year in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program for DNA transcription problem

28 Jul, 2020
 Let’s discuss the DNA  transcription problem in Python. First, let’s understand about the basics of DNA and RNA that are going to be used in this problem.
The four nucleotides found in DNA: Adenine (A), Cytosine (C), Guanine (G), and Thymine (T).
The four nucleotides found in RNA: Adenine (A), Cytosine (C), Guanine (G), and Uracil (U).
Given a DNA strand, its transcribed RNA strand is formed by replacing each nucleotide with its complement nucleotide:
G –> C
C –> G
T –> A
A –> U
Example : 
Input: GCTAA
Output: CGAUU
 
Input: GC
Output: CG 

Approach: 
Take input as a string and then convert it into the list of characters. Then traverse each character present in the list. check if the character is ‘G’ or ‘C’ or ‘T’ or ‘A’ then convert it into ‘C’,’G’, ‘A’ and ‘U’ respectively. Else print ‘Invalid Input’.
Below is the implementation:
Python3
# define a function# for transcriptiondef transcript(x) :      # convert string into list  l = list(x)      for i in range(len(x)):        if(l[i]=='G'):          l[i]='C'        elif(l[i]=='C'):          l[i]='G'        elif (l[i] == 'T'):          l[i] = 'A'        elif (l[i] == 'A'):          l[i] = 'U'        else:          print('Invalid Input')                                    print("Translated DNA : ",end="")        for char in l:      print(char,end="")  # Driver codeif __name__ == "__main__":      x = "GCTAA"  # function calling  transcript(x)
Output:
Translated DNA : CGAUU

python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Ways to Convert Double to Integer in C#

17 May, 2020
Given a Double real number, the task is to convert it into Integer in C#.  There are mainly 3 ways to convert Double to Integer as follows:
Using Type Casting
Using Math.round()
Using Decimal.ToInt32()
Examples: 
Input: double = 3452.234
Output: 3452 
 
Input: double = 98.23
Output: 98 
1. Using Typecasting: This technique is a very simple and user friendly. 
Example:  
C#
// C# program for type conversion from double to intusing System;using System.IO;using System.Text;namespace GFG {class Geeks {  // Main Method  static void Main(string[] args) {    double a = 3452.345;    int b = 0;      // type conversion    b = (int)a;      Console.WriteLine(b);  }}}
Output:  
3452

2. Using Math.round(): This method returns the nearest integer.  
C#
// C# program to demonstrate the// Math.Round(Double) methodusing System;  class Geeks {    // Main method  static void Main(string[] args) {    Double dx1 = 3452.645;      // Output value will be 12    Console.WriteLine(Math.Round(dx1));  }}
Output:  
3452

3. UsingDecimal.ToInt32(): This method is used to convert the value of the specified Decimal to the equivalent 32-bit signed integer. 
C#
// C# program to convert Double to Integerusing System;publicclass Demo {public  static void Main() {    double val = 3452.345;    int res = Convert.ToInt32(val);    Console.WriteLine(res);  }}
Output:  
3452

C#
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.LastIndex() Function in Golang With Examples

19 Apr, 2020
strings.LastIndex() function in the Golang returns the starting index of the occurrence of the last instance of a substring in a given string. If the substring is not found then it returns -1. Thus, this function returns an integer value. The index is counted taking zero as the starting index of the string.
Syntax:
func LastIndex(str, substring string) int
Here, str is the original string and substring is a string, whose we want to find the last index value.
Example 1:
// Golang program to illustrate the// strings.LastIndex() Functionpackage main  import (    "fmt"    "strings")  func main() {      // taking a string    str := "GeeksforGeeks"    substr := "Geeks"    fmt.Println(strings.LastIndex(str, substr))  }
Output:
8
The string is “GeeksforGeeks” and the substring is “Geeks” so the compiler finds the substring present in the original string and displays the starting index of the last instance of substring which is 8.
Example 2:
// Golang program to illustrate the// strings.LastIndex() Functionpackage main  import (    "fmt"    "strings")  func main() {      // taking strings    str := "My favorite sport is football"    substr1 := "f"    substr2 := "ll"    substr3 := "SPORT"      // using the function    fmt.Println(strings.LastIndex(str, substr1))    fmt.Println(strings.LastIndex(str, substr2))    fmt.Println(strings.LastIndex(str, substr3))}
Output:
21
27
-1

The string is “My favorite sport is football” and the substrings are “f”, “ll” and “SPORT” so the compiler displays the output as 21 and 27 in the first two cases respectively and since the third substring is “SPORT” which is considered as not present in the string as the function is case sensitive so it will give the result as -1.
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
Golang Maps
Interfaces in Golang
Slices in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
How to compare times in Golang?
Python | Find overlapping tuples from list

03 Nov, 2019
Sometimes, while working with tuple data, we can have a problem in which we may need to get the tuples which overlap a certain tuple. This kind of problem can occur in Mathematics domain while working with Geometry. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loopIn this method, we extract the pairs with overlap using conditional statements and append the suitable match into list keeping records.
# Python3 code to demonstrate working of# Find overlapping tuples from list# using loop   # initialize listtest_list = [(4, 6), (3, 7), (7, 10), (5, 6)]  # initialize test tuple test_tup = (1, 5)  # printing original listprint("The original list : " + str(test_list))  # Find overlapping tuples from list# using loop res = []for tup in test_list:    if(tup[1]>= test_tup[0] and tup[0]<= test_tup[1]):        res.append(tup)  # printing resultprint("The tuple elements that overlap the argument tuple is : "                                                     + str(res))
The original list : [(4, 6), (3, 7), (7, 10), (5, 6)]The tuple elements that overlap the argument tuple is : [(4, 6), (3, 7), (5, 6)]
 
Method #2 : Using list comprehensionThis task can also be achieved using list comprehension functionality. This method is similar to the above one, just packed in one-liner for use as a shorthand.
# Python3 code to demonstrate working of# Find overlapping tuples from list# Using list comprehension  # initialize listtest_list = [(4, 6), (3, 7), (7, 10), (5, 6)]  # initialize test tuple test_tup = (1, 5)  # printing original listprint("The original list : " + str(test_list))  # Find overlapping tuples from list# Using list comprehensionres = [(idx[0], idx[1]) for idx in test_list\      if idx[0] >= test_tup[0] and idx[0] <= test_tup[1]\      or idx[1] >= test_tup[0] and idx[1] <= test_tup[1]]  # printing resultprint("The tuple elements that overlap the argument tuple is : "                                                     + str(res))
The original list : [(4, 6), (3, 7), (7, 10), (5, 6)]The tuple elements that overlap the argument tuple is : [(4, 6), (3, 7), (5, 6)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert dataframe column to vector in R

21 Apr, 2021
In this article, we will discuss how to convert a DataFrame column to vector in R Programming Language. To extract a single vector from a data frame in R Programming language, as.vector() function can be used.
Syntax: as.vector( data_frame$column_name ) 
Here, 
data_frame is the name of the data frame
column_name is the column to be extracted
Given below are some implementations for this.
Example 1: 
R
# creating dataframe std.data <- data.frame(std_id = c (1:5),                        std_name = c("Ram","Shayam","Mohan",                                    "Kailash","Aditya"),                       marks = c(95,96,95,85,80)                      )  # extracting vector from# dataframe column std_namename.vec <- as.vector(std.data$std_name)print(name.vec) 
Output:
[1] “Ram”     “Shayam”  “Mohan”   “Kailash” “Aditya” 
We can now examine whether the returned column is a vector or not, by passing it to the function is.vector() which returns a Boolean value i.e. either true or false.
Example 2: 
We will extract the Species column from the well-known data frame Iris using as.vector( ) function and print it. We will also check whether the returned column is a vector or not.
R
df <- iris  # print the data framehead(df)  # extracting vector from# dataframe column Speciesname.vec <- as.vector(df$Species)  print(name.vec)  # returns Boolean valueis.vector(name.vec) 
Output:
Picked
R DataFrame-Programs
R Vector-Programs
R-DataFrame
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.statvfs() method

21 Jun, 2022
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.statvfs() method in Python is used to get the information about the mounted file system containing the given path. To get file system information the method performs statvfs() system call on the given path. Note: os.statvfs() method is available on Unix platforms only.
Syntax: os.statvfs(path) Parameter: path: A path-like object for which file system information is required. Return Type: This method returns an object of class ‘os.statvfs_result’ whose attributes represents the information about the file system containing the given path. The returned os.statvfs_result object has following attributes:
f_bsize: It represents the file system block size
f_frsize: It represents the fragment size
f_blocks It represents the size of fs in f_frsize units
f_bfree: It represents the number of free blocks
f_bavail: It represents the number of free blocks for unprivileged users
f_files: It represents the number of inodes
f_ffree: It represents the number of free inodes
f_favail: It represents the number of free inodes for unprivileged users
f_fsid: It represents the file system ID
f_flag: It represents the mount flags
f_namemax: It represents the maximum filename length
Code: Use of os.statvfs() method to get information about the file system containing the given path. 
Python3
# Python program to explain os.statvfs() method   # importing os moduleimport os # File pathpath = "/home / ihritik / Desktop / file.txt" # Get the information about the# filesystem containing the# given path using os.statvfs() methodinfo = os.statvfs(path) # Print the information# about the file systemprint(info) # Print the file system block sizeprint("File system block size:", info.f_bsize) # Print the number of free blocks# in the file systemprint("Number of free blocks:", info.f_bfree)
os.statvfs_result(f_bsize=4096, f_frsize=4096, f_blocks=59798433, f_bfree=56521834,
f_bavail=53466807, f_files=15261696, f_ffree=14933520, f_favail=14933520, f_flag=4096,
f_namemax=255)
File system block size: 4096
Number of free blocks: 56517297
surinderdawra388
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
How to convert int to string in Python?

Type conversion is at times needed when the user wants to convert one data type into another data type according to requirement.
Python has in-built function str() to convert an integer to a string. We will be discussing various other methods in addition to this to convert int into string in Python.
This is the most commonly used method to convert int into string in Python.The str() takes integer variable as a parameter and converts it into a string.
str(integer variable)
 Live Demo
num=2
print("Datatype before conversion",type(num))
num=str(num)
print(num)
print("Datatype after conversion",type(num))
Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>
The type() function gives the datatype of the variable which is passed as parameter.
In the above code, before conversion, the datatype of num is int and after the conversion, the datatype of num is str(i.e. string in python).
f ’{integer variable}’
 Live Demo
num=2
print("Datatype before conversion",type(num))
num=f'{num}'
print(num)
print("Datatype after conversion",type(num))
Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>
“%s” % integer variable
 Live Demo
num=2
print("Datatype before conversion",type(num))
num="%s" %num
print(num)
print("Datatype after conversion",type(num))
Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>
‘{}’.format(integer variable)
 Live Demo
num=2
print("Datatype before conversion",type(num))
num='{}'.format(num)
print(num)
print("Datatype after conversion",type(num))
Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>
These were some of the methods to convert int into string in Python. We may require to convert int into string in certain scenarios such as appending value retained in a int into some string variable. One common scenario is to reverse an integer. We may convert it into string and then reverse which is easier than implementing mathematical logic to reverse an integer.
PHP Program to print all permutations of a given string

10 Dec, 2021
A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one
A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. 
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB
Here is a solution that is used as a basis in backtracking.
PHP
<?php // PHP program to print all // permutations of a given string.   /* Permutation function @param    str string to calculate permutation    for @param l starting index @param    r end index */function permute($str, $l, $r) {     if ($l == $r)         echo $str. "\n";     else    {         for ($i = $l; $i <= $r; $i++)         {             $str = swap($str, $l, $i);             permute($str, $l + 1, $r);             $str = swap($str, $l, $i);         }     } }   /* Swap Characters at position @param    a string value @param i position 1    @param j position 2 @return swapped    string */function swap($a, $i, $j) {     $temp;     $charArray = str_split($a);     $temp = $charArray[$i] ;     $charArray[$i] = $charArray[$j];     $charArray[$j] = $temp;     return implode($charArray); }   // Driver Code $str = "ABC"; $n = strlen($str); permute($str, 0, $n - 1);   // This code is contributed by mits. ?> 
Output: 
ABC
ACB
BAC
BCA
CBA
CAB
Algorithm Paradigm: Backtracking 
Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation.
Auxiliary Space: O(r – l)
Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL
PHP Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create sticky footer in ReactJS ?

25 May, 2021
In this article, we will see how to create a sticky footer in ReactJS. A footer is an important element of a website’s design. A sticky footer sticks to the bottom of the website and signals to the user that they have reached the end of the webpage. For working with react, we have to set up the project first.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app react-footer
Step 1: Create a React application using the following command:
npx create-react-app react-footer
Step 2: After creating your project folder i.e. react-footer, move to it using the following command:cd react-footer
Step 2: After creating your project folder i.e. react-footer, move to it using the following command:
cd react-footer
Project Structure: It will look like the following.
Example: In this example, we will design a footer, for that we will need to manipulate the App.js file and App.css as well as the Footer.js file.
Footer.js
import React from 'react';  const Footer = () => (  <footer className="footer">    <p>This is react sticky footer!!</p>    </footer>);  export default Footer;
App.css
body { margin: 0; padding: 0; height:1000px;}.App{ color: #228b22; text-align: center;}.footer { background-color: green; border-top:2px solid red; position: fixed; width: 100%; bottom: 0; color: white; font-size: 25px;}
App.js
import React from "react";  // Importing the footer componentimport Footer from "./Footer";  // Importing the styling of App componentimport "./App.css";  const App = () => (  <div className="App">    <h3>GeeksforGeeks</h3>    <h2>Sticky Footer using Reactjs!</h2>    <Footer />  </div>);  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
CSS-Properties
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
How to access array Elements in Ruby

24 Oct, 2019
In this article, we will learn how to access array elements in Ruby.
In Ruby, there are several ways to retrieve the elements from the array. Ruby arrays provide a lot of different methods to access the array element. But the most used way is to use the index of an array.
# Ruby program to demonstrate the  # accessing the elements of the array     # creating string using [] str = ["GFG", "G4G", "Sudo", "Geeks"]     # accessing array elements # using index puts str[1]     # using the negative index puts str[-1] 
Output:
G4G
Geeks
Sometimes, we need to access the multiple elements from the array. So to access the multiple elements, pass the two specified array index into the [].
# Ruby program to demonstrate the  # accessing the multiple elements  # from  array     # creating string using [] str = ["GFG", "G4G", "Sudo", "Geeks"]     # accessing multiple array elements puts str[2, 3] 
Output:
Sudo
Geeks
# Ruby program to demonstrate the  # accessing the multiple elements  # from  array     # creating string using [] str = [["GFG", "G4G", "Sudo"],        [ "Geeks", "for", "portal"] ]    # accessing item from multi-arrayputs str[1][2] 
Output:
portal
Ruby Array
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.numinput() function in Python

15 Sep, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to pop up a dialog window for the input of a number. The number input must be in the range minval to maxval if these are given. If not, a hint is issued and the dialog remains open for correction.
Syntax :
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtleturtle.numinput("title","prompt")
Output : 
Example 2 : 
Python3
# import packageimport turtle  # taking inputnum = int(turtle.numinput("Contact Detail",                          "Phone no.",                          default=9999999999,                          minval=6000000000,                          maxval=9999999999                          ))print(num)
Output : 
9897347846
 
anikakapoor
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
std::string::push_back() in C++

06 Jul, 2017
The push_back() member function is provided to append characters. Appends character c to the end of the string, increasing its length by one.Syntax :
void string:: push_back (char c)
Parameters:  Character which to be appended. 
Return value: None
Error: throws length_error if the 
resulting size exceeds the maximum number of characters(max_size).

// CPP code for to illustrate // std::string::push_back()   #include <iostream>#include <string>using namespace std;   // Function to demonstrate push_back()void push_backDemo(string str1, string str2){    // Appends character by character str2    // at the end of str1    for(int i = 0; str2[i] != '\0'; i++)    {        str1.push_back(str2[i]);    }    cout << "After push_back : ";    cout << str1;}          // Driver codeint main(){    string str1("Geeksfor");    string str2("Geeks");      cout << "Original String : " << str1 << endl;    push_backDemo(str1, str2);       return 0;}
Output:
Original String : Geeksfor
After push_back : GeeksforGeeks

This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) 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.
cpp-string
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
spawn - Unix, Linux Command

spawn [generic Postfix daemon options] command_attributes...


This daemon expects to be run from the master(8) process
manager.






The text below provides only a parameter summary. See
postconf(5) for more details including examples.


In the text below, transport is the first field of the entry
in the master.cf file.





postconf(5), configuration parameters
master(8), process manager
syslogd(8), system logging



Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA
howdoi in Python

17 May, 2021
howdoi is a command-line tool written in Python. It gives the answers to do basic programming tasks, while working still in the console, directly from the command line. It scrapes code from the top answers on StackOverflow. You need an internet connection for using howdoi. 
howdoi will answer all sorts of queries related to programming and coding. Like getting help in syntax, searching for libraries for a specific purpose, resolving errors, using pre-defined functions and their applications, etc. 
Command to Install:  
pip install howdoi
Usage:  
howdoi QUERY
Other optional arguments are:  
-h : show this help message and exit
-p POS : select answer in specified position (default: 1)
-al : display the full text of the answer
-l : display only the answer link
-c : enable colorized output
-n NUM_ANSWERS : number of answers to return
-C : clear the cache
-v : displays the current version of howdoi
Examples:  
howdoi tells us that in C, a comment can be given by using “//”.  
howdoi tells that python can be exited by using quit()  
howdoi tells us how to check if a list in python is empty or not.  
howdoi tells us that the most recent commit on git can be undone by the following the steps  
howdoi tells us how to redirect into an another webpage.  
-l optional argument displays the link of the StackOverflow article from which the answer is taken.  
 
Shivam_k
Akanksha_Rai
sumitgumber28
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
Measuring script execution time in PHP

04 Nov, 2018
Script execution time in PHP is the time required to execute the PHP script. To calculate script execution time use clock time rather than the CPU execution time. Knowing clock time before script execution and after script execution will help to know the script execution time.
Example: Sample script
<?phpfor($i = 1; $i <=1000; $i++){    echo "Hello Geeks!";} ?>
Clock time can get using microtime() function. First use it before starts the script and then at the end of the script. Then using formula (End_time – Start_time). The mirotime() function returns time in seconds. Execution time is not fixed, it depends upon the processor.
Example:
<?php  // Starting clock time in seconds$start_time = microtime(true);$a=1;  // Start loopfor($i = 1; $i <=1000; $i++){    $a++;}   // End clock time in seconds$end_time = microtime(true);  // Calculate script execution time$execution_time = ($end_time - $start_time);  echo " Execution time of script = ".$execution_time." sec";?>
Execution time of script = 1.6927719116211E-5 sec

PHP-basics
Picked
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dumping queue into list or array in Python

31 Dec, 2020
Prerequisite: Queue in Python
Here given a queue and our task is to dump the queue into list or array. We are to see two methods to achieve the objective of our solution.
Example 1: 
In this example, we will create a queue using the collection package and then cast it into the list
Python3
# Python program to# demonstrate queue implementation# using collections.dequeue   from collections import deque   # Initializing a queueq = deque()   # Adding elements to a queueq.append('a')q.append('b')q.append('c')  # display the queueprint("Initial queue")print(q,"\n")  # display the typeprint(type(q))
Output:
Initial queue
deque(['a', 'b', 'c']) 

<class 'collections.deque'>
Let’s create a list and cast into it:
Python3
# convert into listli = list(q)  # displayprint("Convert into the list")print(li)print(type(li))
Output:
Convert into the list
['a', 'b', 'c']
<class 'list'>
Example 2:
In this example, we will create a queue using the queue module and then cast it into the list.
Python3
from queue import Queue  # Initializing a queueque = Queue()  # Adding elements to a queueque.put(1)que.put(2)que.put(3)que.put(4)que.put(5)  # display the queueprint("Initial queue")print(que.queue)  # casting into the listli = list(que.queue)print("\nConverted into the list")print(li)
Output:
Initial queue
deque([1, 2, 3, 4, 5])

Converted into the list
[1, 2, 3, 4, 5]
Python DSA-exercises
Python
Queue
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to vertically flip an Image using MATLAB - GeeksforGeeks

14 Jan, 2020
Prerequisite: Image representation in MATLAB
In MATLAB, Images are stored in matrices, in which each element of the matrix corresponds to a single discrete pixel of the image. We can flip the given image vertically (along the x-axis), if we reverse the order of the pixels (elements of the matrix) in each column as illustrated in the below image.
Code #1: Using MATLAB Library function
% Read the target image fileimg = imread('leaf.png');   % Reverse the order of the element in each columnvertFlip_img = flip(img, 1);   % Display the vertically flipped imageimshow(vertFlip_img); title('Vertically flipped image');
Code #2: Using matrix manipulation
% Read the target image fileimg = imread('leaf.png');   % Flip the columns vertically vertFlip_img = img(end : -1: 1, :, :);   % Display the vertically flipped imageimshow(vertFlip_img); title('Vertically flipped image');
Code #3: Using matrix manipulation (Using loops)
Approach:
Read the source image file in MATLAB environment
Get the Dimensions of the image matrix
Reverse the order of the elements of each column in every image plane
Display the water image (vertically flipped image).
Below is the implementation of the above approach:
% Read the target image fileimg = imread('leaf.png');   % Get the dimensions of the image[x, y, z] = size(img);      % Reverse elements of each column% in each image plane (dimension)for plane = 1 : z    len = x;    for i = 1 : x         for j = 1 : y               % To reverse the order of the element            % of a column we can swap the             % topmost element of the row with            % its bottom-most element                            if i < x/2                 temp = img(i, j, plane);                img(i, j, plane) = img(len, j, plane);                img(len, j, plane) = temp;                             end        end        len = len - 1;    endend      % Display the vertically flipped imageimshow(img); title('Vertically flipped image');
Input image: leaf.png
Output:
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
ML | Underfitting and Overfitting
Clustering in Machine Learning
Docker - COPY Instruction
How to view folder NTFS permission with PowerShell?

To view the NTFS permission with PowerShell, we use the Get-ACL command. This command is supported in PowerShell version 5.1 or later. Generally how we get the security permission of the folder in the Windows OS using GUI,
To get the same permissions shown above using PowerShell, use the below command.
Get-Acl C:\Shared
PS C:\> Get-Acl C:\Shared 
Directory: C:\ 
Path      Owner     Access 
----      -----     ------ 
Shared BUILTIN\Administrators NT AUTHORITY\SYSTEM Allow FullControl...
You can compare the first image with the above output. You can compare the Owner of the folder and it is Administrator, second part is the Access, to get all the users who have access on this folder by expanding property.
Get-Acl C:\Shared | Select -ExpandProperty Access
Let convert the above output in the table format to get a clear understanding of the output as shown in the first image.
Get-Acl C:\Shared | Select -ExpandProperty Access | ft -AutoSize
So you have everything that you can see in the first image of the folder security property like User rights, File System rights, Inherited or not, etc.
To view the specific user rights, you can filter with the username. For example,
Get-Acl C:\Shared | Select -ExpandProperty Access | where {$_.IdentityReference -like "*user*"} | ft -AutoSize
Similarly, you can also filter other properties like AccessControlType, IsInherited, etc.
How to change the size of dots in dotplot created by using ggplot2 in R?

To change the size of dots in dotplot created by using ggplot2, we can use binwidth argument inside geom_dotplot. For example, if we have a data frame called df that contains a column x for which we want to create the dotplot then the plot with different size of dots can be created by using the command ggplot(df,aes(x))+geom_dotplot(binwidth=2).
Consider the below data frame −
 Live Demo
x<-rpois(20,5)
df<-data.frame(x)
df
   x
1  1
2  3
3  6
4  3
5  5
6  11
7  2
8  3
9  2
10 6
11 5
12 4
13 4
14 6
15 8
16 6
17 8
18 9
19 4
20 7
Loading ggplot2 package and creating a dotpot for data in df with different size of dots −
library(ggplot2)
ggplot(df,aes(x))+geom_dotplot(binwidth=1)
ggplot(df,aes(x))+geom_dotplot(binwidth=0.5)
ggplot(df,aes(x))+geom_dotplot(binwidth=2)
How to return variable value from jQuery event function?

You cannot return variable value from jQuery event function. To understand the reason, let us see how data is passed, which was created in the event handler of a button click.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var a=document.getElementById('demo');
    a.addEventListener('click', function(){
       var s='Hello World!';
       var event = new CustomEvent('build', { 'detail': s });
       this.dispatchEvent(event);
     })

    document.getElementById('parent').addEventListener('build', getData, true);

    function getData(e){
       alert(e.detail);
    }
});
</script>
</head>
<body>

<div id='parent'>
<button id='demo'>Click me</button>
</div>

</body>
</html>
How to generate Prime Numbers in JavaScript?

To generate prime numbers in JavaScript, you can try to run the following code
Live Demo
<html>
   <head>
      <title>JavaScript Prime</title>
   </head>

   <body>
      <script>
         for (var limit = 1; limit <= 20; limit++) {
            var a = false;
            for (var i = 2; i <= limit; i++) {
               if (limit%i===0 &amp;&amp; i!==limit) {
                  a = true;
               }
            }
            if (a === false) {
               document.write("<br>"+limit);
            }
         }
      </script>
   </body>
</html>