code-rag-bench/online-tutorials huggingface dataset:
How to set the local user account settings using PowerShell?

To set the local user account settings related to the account or the password expiration, we can use the Set-LocalUser command.
The below command will change the local user Testuser account and password set to never expire.
Set-LocalUser -Name Testuser -AccountNeverExpires -PasswordNeverExpires $true -Verbose
The below command will set the account expiry,
Set-LocalUser -Name Testuser -AccountExpires 05/11/2022 -Verbose
To run the above commands on the remote computers, use the Invoke-Command.
Invoke-Command -ComputerName Computer1, computer2 -ScriptBlock{
   Set-LocalUser -Name Testuser -AccountNeverExpires -PasswordNeverExpires $true -Verbose
}
Invoke-Command -ComputerName Computer1, computer2 -ScriptBlock{
   Set-LocalUser -Name Testuser -AccountExpires 05/11/2022 -Verbose
}
fill() function in C++ STL with examples - GeeksforGeeks

11 Oct, 2019
The fill() function in C++ STL is used to fill some default value in a container. The fill() function can also be used to fill values in a range in the container. It accepts two iterators begin and end and fills a value in the container starting from position pointed by begin and just before the position pointed by end.
Syntax:
void fill(iterator begin, iterator end, type value);

Parameters:
begin: The function will start filling values from the position pointed by the iterator begin.
end: The function will fill values upto the position just before the position pointed by the iterator end.
value: This parameter denotes the value to be filled by the function in the container.
NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included.
Return Value: This function does not returns any value.
Below program illustrate the fill() function in C++ STL:
// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std;  int main(){    vector<int> vect(8);      // calling fill to initialize values in the    // range to 4    fill(vect.begin() + 2, vect.end() - 1, 4);      for (int i = 0; i < vect.size(); i++)        cout << vect[i] << " ";      // Filling the complete vector with value 10    fill(vect.begin(), vect.end(), 10);      cout << endl;      for (int i = 0; i < vect.size(); i++)        cout << vect[i] << " ";      return 0;}
0 0 4 4 4 4 4 0 
10 10 10 10 10 10 10 10

Reference: http://www.cplusplus.com/reference/algorithm/fill/
CPP-Functions
C++
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++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
std::string class in C++
new and delete operators in C++ for dynamic memory
Count occurrences of a character in string in Python

We are given a string and a character. We want to find out how many times the given character is repeated in a given string.
We design a for loop to match the character with every character present in the string which are accessed using index. The range and len function helps us determine how many times the matching has to be done when moving from left to right of the string.
 Live Demo
Astr = "How do you do"
char = 'o'
# Given String and Character
print("Given String:\n", Astr)
print("Given Character:\n",char)
res = 0
for i in range(len(Astr)):
   # Checking character in string
   if (Astr[i] == char):
      res = res + 1
print("Number of time character is present in string:\n",res)
Running the above code gives us the following result −
Given String:
How do you do
Given Character:
o
Number of time character is present in string:
4
We apply the Counter function from the collections module to get the count of each character in the string. And then choose only those counts where the index matches with the value of the character we are searching for.
 Live Demo
from collections import Counter
Astr = "How do you do"
char = 'o'
# Given String and Character
print("Given String:\n", Astr)
print("Given Character:\n",char)
count = Counter(Astr)
print("Number of time character is present in string:\n",count['o'])
Running the above code gives us the following result −
Given String:
How do you do
Given Character:
o
Number of time character is present in string:
4
replace() Function Of Datetime.date Class In Python

23 Aug, 2021
replace() function is used to manipulate the object of DateTime class of module of DateTime. Generally, it replaces the date( Year, Month, Day) and returns a new DateTime object.
Syntax: replace(year=self.year, month=self.month, day=self.day)
Parameters:
Year: New year value (range: 1 <= year <= 9999)
month: New month value(range: 1 <= month <= 12)
day: New day value(range: 1<= day <= 31)
Returns: New datetime object.
Example 1: Replace the year with datetime object.
Python3
# import modulefrom datetime import date  # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date)  # Using replace() methodNew_date = Date.replace(year=2021)print("After Modify the year:", New_date)
Original date :  2010-02-12
After Modify the year: 2021-02-12

Example 2: Replace the month with datetime object.
Python3
# import modulefrom datetime import date  # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date)  # Using replace() methodNew_date = Date.replace(month=5)print("After Modify the month:", New_date)
Original date :  2010-02-12
After Modify the month: 2010-05-12

Example 3: Replace the day with datetime object.
Python3
# import modulefrom datetime import date  # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date)  # Using replace() methodNew_date = Date.replace(day=21)print("After Modify the day:", New_date)
Original date :  2010-02-12
After Modify the day: 2010-02-21

Example 4: Replace the time with datetime object.
Python3
from datetime import datetime  Date = datetime(2010, 2, 12, 8, 50, 23)print("Original date and time : ", Date)  New_date = Date.replace(hour=1,                        minute=3,                        second=12)print("After modify date and time : ", New_date)
Original date and time :  2010-02-12 08:50:23
After modify date and time :  2010-02-12 01:03:12

Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to delete default values in text field using Selenium?

We can delete default values in the text field with Selenium webdriver. There are multiple ways to do this. We can use the clear() method which resets value present already in edit box or text area field.
We can use the Keys.chord() method along with sendKeys(). The Keys.chord() method helps to press multiple keys simultaneously. It accepts the sequence of keys or strings as a parameter to the method.
To delete default values, it takes, Keys.CONTROL, "a" as parameters. This string is then sent as a parameter to the sendKeys() method. Finally, we have to pass Keys.DELETE to the sendKeys() method.
Let us consider the below edit field where we will delete the input values.
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;

public class DelDefaultVal{
   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/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // input text
      l.sendKeys("Selenium");
      // delete default value with clear()
      l.clear();
      driver.quit()
   }
}
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class DelDefaultValue{
   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/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // input text
      l.sendKeys("Selenium");
      // sending Ctrl+a by Keys.Chord()
      String s = Keys.chord(Keys.CONTROL, "a");
      l.sendKeys(s);
      // sending DELETE key
      l.sendKeys(Keys.DELETE);
      driver.quit()
   }
}
How to add custom filter in search Box in ReactJS?

09 Sep, 2021
The custom filter means adding our own business login to filter the options shown in searchbox or any dropdown menu. Material UI for React has this component available for us and it is very easy to integrate. We can create our own custom filter for options in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete'; const App = () => {   const filterOptions = createFilterOptions({    matchFrom: 'start',    stringify: option => option,  });   // Sample options for search box  const myOptions = ['One Number', 'Two Number', 'Five Number',    'This is a sample text', 'Dummy text', 'Dropdown option teet',    'Hello text', 'Welcome to text field'];   return (    <div style={{ marginLeft: '40%', marginTop: '60px' }}>      <h3>Greetings from GeeksforGeeks!</h3>      <Autocomplete        style={{ width: 500 }}        freeSolo        filterOptions={filterOptions}        options={myOptions}        renderInput={(params) => (          <TextField {...params}            variant="outlined"            label="Search Box"          />        )}      />    </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:
The following would have been the output without adding our custom filter function:
 
sweetyty
JavaScript
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exponential Distribution in R Programming – dexp(), pexp(), qexp(), and rexp() Functions

08 Jul, 2020
The exponential distribution in R Language is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution.
In R, there are 4 built-in functions to generate exponential distribution:
dexp()dexp(x_dexp, rate) 
dexp(x_dexp, rate) 
pexp()pexp(x_pexp, rate )
pexp(x_pexp, rate )
qexp()qexp(x_qexp, rate)
qexp(x_qexp, rate)
rexp()rexp(N, rate )
rexp(N, rate )
where,
x: represents x-values for exp function .rate: represents the shapex.N: Specify sample size
dexp() function returns the corresponding values of the exponential density for an input vector of quantiles.
Syntax:
dexp(x_dexp, rate)
Example:
# R program to illustrate# exponential distribution# Specify x-valuesx_dexp <- seq(1, 10, by = 0.1)        # Apply dexp() function               y_dexp <- dexp(x_dexp, rate = 5)                     # Plot dexp values plot(y_dexp)
Output:
pexp() function returns the corresponding values of the exponential cumulative distribution function for an input vector of quantiles.
Syntax:
pexp(x_pexp, rate )
Example:
# R program to illustrate# exponential distribution  # Specify x-valuesx_pexp <- seq(1, 10, by = 0.2)                                       # Apply pexp() functiony_pexp <- pexp(x_pexp, rate = 1)   # Plot values                  plot(y_pexp)                                                    
Output :
qexp() function gives the possibility, we can use the qexp function to return the corresponding values of the quantile function.
Syntax:
qexp(x_qexp, rate)
Example:
# R program to illustrate# exponential distribution  # Specify x-values x_qexp <- seq(0, 1, by = 0.2)                        # Apply qexp() functiony_qexp <- qexp(x_qexp, rate = 1)   # Plot values                   plot(y_qexp)                                       
Output:
rexp() function is used to simulate a set of random numbers drawn from the exponential distribution.
Syntax:
rexp(N, rate )
Example:
# R program to illustrate# exponential distribution  # Set seed for reproducibilityset.seed(500)   # Specify size         N <- 100  # Draw exp distributed valuesy_rexp <- rexp(N, rate = 1)   # Plot exp density  hist(y_rexp, breaks = 50, main = "")
Output :
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
How to use Collapse Component in ReactJS ?

22 Feb, 2021
Collapse Component adds a Collapse animation to a child element or component in which it vertically expands from the top of the child element. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Collapse Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: 
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. 
App.js
import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Collapse from '@material-ui/core/Collapse';  export default function App() {    const [isChecked, setIsChecked] = React.useState(false);    return (    <div style={{ display: 'block', padding: 30 }}>      <h4>How to use Collapse Component in ReactJS?</h4>      <FormControlLabel        control={<Switch checked={isChecked} onChange={() => {          setIsChecked((prev) => !prev);        }} />}        label="Toggle me to see Collapse Effect"      />      <div style={{ display: 'flex' }}>        <Collapse in={isChecked}>          <Paper            elevation={5}            style={{ margin: 5 }} >            <svg style={{ width: 100, height: 100 }}>              <polygon points="0,80 45,00, 80,70"                style={{                  fill: 'orange',                  stroke: 'dimgrey',                  strokeWidth: 1,                }} />            </svg>          </Paper>        </Collapse>      </div>    </div>  );}
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.
Reference: https://material-ui.com/components/transitions/#collapse
Material-UI
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 do crud operations in ReactJS ?
How to install bootstrap in React.js ?
How to Use Bootstrap with React?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
How to check multiple variables against a value in Python?

19 May, 2021
Given some variables, the task is to write a Python program to check multiple variables against a value.  There are three possible known ways to achieve this in Python:
Method #1: Using or operator
This is pretty simple and straightforward. The following code snippets illustrate this method.
Example 1:
Python3
# assigning variablesa = 100b = 0c = -1 # checking multiple variables against a valueif a == -1 or b == 100 or c == -1:    print('Value Found!')else:    print('Not Found!')
Output:
Value Found!
Method #2: Using in keyword
It is usually used to search through a sequence but can very well replace the code above.
Python3
# assigning variablesa = 100b = 0c = -1 # checking multiple variables against a valueif a in [100, 0, -1]:    print('Value Found!')else:    print('Not Found!')
Output:
Value Found!
You can use it for inverse statements also:
Example 2: 
Python3
# assigning variablesa = 90 # checking multiple variables against a valueif a not in [0, -1, 100]:    print('Value Found!')else:    print('Not Found!')
Output:
Value Found!
Method #2: Using == operator
This approach is only applicable to multiple variables when checked with a single value.
Example 1: 
Python3
# assigning variablesa = 9b = 9c = 9 # checking multiple variables against a valueif a == b == c == 9:    print('Value Found!')else:    print('Not Found!')
Output:
Value Found!
gabaa406
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Find the list elements starting with specific letter

25 Apr, 2019
Sometimes, we require to get the words that start with the specific letter. This kind of use case is quiet common in the places of common programming projects or competitive programming. Let’s discuss certain shorthands to deal with this problem in Python.
Method #1 : Using list comprehension + lower()
This problem can be solved using the combination of above two functions, list comprehension performs the task of extending the logic to whole list and lower function checks for case insensitivity with the target word of argument letter.
# Python3 code to demonstrate# Words starting with specific letter# using list comprehension + lower()  # initializing listtest_list = ['Akash', 'Nikhil', 'Manjeet', 'akshat']  # initializing check lettercheck = 'A'  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + lower()# Words starting with specific letterres = [idx for idx in test_list if idx[0].lower() == check.lower()]  # print resultprint("The list of matching first letter : " + str(res))
The original list : ['Akash', 'Nikhil', 'Manjeet', 'akshat']
The list of matching first letter : ['Akash', 'akshat']

 
Method #2 : Using list comprehension + startswith() + lower()
This method is similar to the above method but rather than checking for equality with operator, it checks using the startswith function which is inbuilt provided by python inbuilt library.
# Python3 code to demonstrate# Words starting with specific letter# using list comprehension + startswith() + lower()  # initializing listtest_list = ['Akash', 'Nikhil', 'Manjeet', 'akshat']  # initializing check lettercheck = 'A'  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + startswith() + lower()# Words starting with specific letterres = [idx for idx in test_list if idx.lower().startswith(check.lower())]  # print resultprint("The list of matching first letter : " + str(res))
The original list : ['Akash', 'Nikhil', 'Manjeet', 'akshat']
The list of matching first letter : ['Akash', 'akshat']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript promise reject() Method

31 May, 2022
A promise is a JavaScript object which is responsible for handling callbacks and other asynchronous events or data with 2 different possible states, it either resolves or rejects.
The Promise.reject() method is used to return a rejected Promise object with a given reason for rejection. It is used for debugging purposes and selective error catching. The catch() method can be used for logging the output of the reject() method to the console that is catch() method acts as a career which carries the rejected message from Promise.reject() method and displays that in user’s console.
Syntax:
Promise.reject(reason)
Parameter: This method accepts a single parameter as mentioned above and described below:
reason: It is the reason for which the promise is rejected.
Return value: It returns the rejected promise with the given reason, either specified by user or via the backend.
The examples below illustrate the reject() method in very much simplified and accurate manner:
Example 1:
JavaScript
<script>  // Initialize a promise variable and  // use the reject() method with a  // reason as a parameter  var promise = Promise.reject("I am a reason of error");   // Catch the promise and pass the  // function for logging the error in console  promise.catch(function (error) {    console.log(error);  });</script> // This code is contributed by Aman Singla
Output:
I am a reason of error
Example 2:
JavaScript
<script>  function main() {    return new Promise(function (resolve, reject) {      setTimeout(() => {        // This is the error which is handled        // according to network requests        const error = true;        reject();      }, 2000);    });  }  main().catch(function () {    // Only executed if rejects the promise    console.log("rejected the promise, something wrong happened");  });</script>
Output:
rejected the promise, something wrong happened
Example 3: 
JavaScript
<script>  function main() {    return new Promise(function (resolve, reject) {      num = 100;      if (num > 50) {        reject();      }    });  }  main().catch(function () {    // Only executed if rejects the promise    console.log("Not greater than 100");  });</script>
Output:
Not greater than 100
Supported Browsers:
Google Chrome 32 and above
Edge 12 and above
Firefox 29 and above
Opera 19 and above
Safari 8 and above
Internet Explorer not supported
amansingla
kumargaurav97520
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Text Decoration in CSS

For text decoration in CSS, use the text-decoration property as a shorthand property for the following properties −
text-decoration-line
text-decoration-color
text-decoration-style
Let us see an example for text decoration in CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
   text-decoration: overline underline;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near ABC College.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>
Let us now see another example wherein we are using separate values −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
p {
   writing-mode: vertical-rl;
   text-decoration-line: overline;
   text-decoration-color: red;
   text-decoration-style: wavy;
}
</style>
</head>
<body>
<h1>Demo Heading</h1>
<p>This is demo text.</p>
</body>
</html>
Python – Check if string contains any number

06 Jul, 2022
In this article, we will check How to check if a string contains a number in Python. 
Input : test_str = ‘geeks4g2eeks’ 
Output : True 
Explanation : Contains 4 and 2. 
Input : test_str = ‘geeksforgeeks’ 
Output : False 
Explanation : Contains no number.
The combination of the above functions can be used to solve this problem. In this, we check for numbers using isdigit() and check for any occurrence using any().
Python3
# Python3 code to demonstrate working of# Check if string contains any number# Using isdigit() + any() # initializing stringtest_str = 'geeks4geeks' # printing original stringprint("The original string is : " + str(test_str)) # using any() to check for any occurrenceres = any(chr.isdigit() for chr in test_str)     # printing resultprint("Does string contain any digit ? : " + str(res))
Output
The original string is : geeks4geeks
Does string contain any digit ? : Tru
This is yet another way in which this task can be performed. This is recommended in cases of larger strings, the iteration in the generator is cheap, but construction is usually inefficient.
Python3
# Python3 code to demonstrate working of# Check if string contains any number# Using isdigit() + next() + generator expression # initializing stringtest_str = 'geeks4geeks' # printing original stringprint("The original string is : " + str(test_str)) # next() checking for each element, reaches end, if no element found as digitres = True if next((chr for chr in test_str if chr.isdigit()), None) else False     # printing resultprint("Does string contain any digit ? : " + str(res))
Output
The original string is : geeks4geeks
Does string contain any digit ? : True
In this example, we will see if the string contains any number or not using the map function. The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable.
Python3
str1 = "Geeks"str2 = "for345"str3 = "Geeks" print(any(map(str.isdigit, str1)))print(any(map(str.isdigit, str2)))print(any(map(str.isdigit, str3)))
Output:
False
True
False
In this example, we will use the regular expression to check if the string contains the digit or not. A regular expression is a powerful tool for matching text, based on a pre-defined pattern. To check the digit, regular expression use \d which matches the digit character.
Python3
import re str1 = "Geek3s"str2 = "for345"str3 = "Geeks" print(bool(re.search(r'\d', str1)))print(bool(re.search(r'\d', str2)))print(bool(re.search(r'\d', str3)))
Output:
True
True
False
surajkumarguptaintern
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Get only the date in timestamp in MySQL?

In order to get the date from the timestamp, you can use DATE() function from MySQL.
The syntax is as follows −
SELECT DATE(yourTimestampColumnName) as anyVariableName from yourTableName;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table DateFromTimestamp
-> (
-> ShippingDateTime timestamp
-> );
Query OK, 0 rows affected (0.60 sec)
Insert date and time for the column ShippingDateTime we created above.
The query to insert record is as follows −
mysql> insert into DateFromTimestamp values('2012-12-26 13:24:35');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DateFromTimestamp values('2013-11-26 14:36:40');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DateFromTimestamp values('2016-07-22 15:20:10');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DateFromTimestamp values('2017-11-04 04:25:30');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select command. The query is as follows −
mysql> select *from DateFromTimestamp;
+---------------------+
| ShippingDateTime    |
+---------------------+
| 2012-12-26 13:24:35 |
| 2013-11-26 14:36:40 |
| 2016-07-22 15:20:10 |
| 2017-11-04 04:25:30 |
+---------------------+
4 rows in set (0.00 sec)
The following is the query to display only date from a timestamp using date() function −
mysql> select date(ShippingDateTime) as OnlyDatePartFromTimestamp from
DateFromTimestamp;
+---------------------------+
| OnlyDatePartFromTimestamp |
+---------------------------+
| 2012-12-26                |
| 2013-11-26                |
| 2016-07-22                |
| 2017-11-04                |
+---------------------------+
4 rows in set (0.00 sec)
Python Program to find largest element in an array

04 Jan, 2018
Given an array, find the largest element in it.
Input : arr[] = {10, 20, 4}
Output : 20

Input : arr[] = {20, 10, 20, 4, 100}
Output : 100

# Python3 program to find maximum# in arr[] of size n   # python function to find maximum# in arr[] of size ndef largest(arr,n):      # Initialize maximum element    max = arr[0]      # Traverse array elements from second    # and compare every element with     # current max    for i in range(1, n):        if arr[i] > max:            max = arr[i]    return max  # Driver Codearr = [10, 324, 45, 90, 9808]n = len(arr)Ans = largest(arr,n)print ("Largest in given array is",Ans)  # This code is contributed by Smitha Dinesh Semwal
Please refer complete article on Program to find largest element in an array for more details!
ssaha3475
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to Implement Gauss Seidel Method

Gauss Seidel method is used to solve linear system of equations in iterative method. This is a C++ Program to Implement Gauss Seidel Method.
Begin
   Take the dimensions of the matrix p and its elements as input.
   Take the initials values of x and no of iteration q as input.
   While q>0
      Make a for loop i = 0 to p-1
         initialize n[i] = (b[i] / a[i][i]).
            Make a for loop i = 0 to p-1
            If (j == i)
               n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]).
               m[i] = n[i].
      Decrease q.
   /*
      Here, a[i][j] = input matrix.
      b[i] = this array takes values of the right side of equation.
      m[i] = stores initial values of x.
   */
   Return 0
End
#include<iostream>
#include<conio.h>
using namespace std;
int main(void) {
   float a[10][10], b[10], m[10], n[10];
   int p = 0, q = 0, i = 0, j = 0;
   cout << "Enter size of 2D array : ";
   cin >> p;
   for (i = 0; i < p; i++) {
      for (j = 0; j < p; j++) {
         cout << "a[" << i << ", " << j << " ]=";
         cin >> a[i][j];
      }
   }
   cout << "\nEnter values to the right side of equation\n";
   for (i = 0; i < p; i++) {
      cout << "b[" << i << ", " << j << " ]=";
      cin >> b[i];
   }
   cout << "Enter initial values of x\n";
   for (i = 0; i < p; i++) {
      cout << "x:[" << i<<"]=";
      cin >> m[i];
   }
   cout << "\nEnter the no. of iteration : ";
   cin >> q;
   while (q> 0) {
      for (i = 0; i < p; i++) {
         n[i] = (b[i] / a[i][i]);
         for (j = 0; j < p; j++) {
            if (j == i)
               continue;
            n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]);
            m[i] = n[i];
         }
         cout<<"x"<<i + 1 << "="<<n[i]<<" ";
      }
      cout << "\n";
      q--;
   }
   return 0;
}
Enter size of 2D array : 2
a[0, 0 ]=1
a[0, 1 ]=2
a[1, 0 ]=3
a[1, 1 ]=4

Enter values to the right side of equation
b[0, 2 ]=1
b[1, 2 ]=2
Enter initial values of x
x:[0]=0
x:[1]=0

Enter the no. of iteration : 3
x1 = 1. x2 = -0.25
x1 = 1.5 x2 = -0.625
x1 = 2.25 x2 = -1.1875
Phonia - Advanced Toolkits To Scan Phone Numbers - GeeksforGeeks

04 Jan, 2022
Phonia tool is an automated tool used in the process of OSINT for getting the information about the target with the help of a phone number. Phonia tools developed in the Python Language and its available on the GitHub platform. It’s free and open-source to use. This tool aims to get accurate results with good performance. This tool can gather information like country, area, carrier, and line type on any international number. 
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/coredamage/phonia.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd phonia
Step 3: You are in the directory of the phonia. Now you have to install a dependency of the phonia using the following command.
sudo pip install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 phonia.py -h
Example 1: Basic Scan
python3 phonia.py -n +9118002584458
In this example, we are performing a basic number scan on geeksforgeeks customer care number.
We have got the information about the number which we have provided as an input.
Example 2: List Scan
python3 phonia.py -i input.txt -o output.txt
In this example, we are performing multiple number scans from the input.txt file.
We have given the input file location and the results will be stored in the output.txt file.
Our search results are been saved in the output.txt file.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
mv command in Linux with examples
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux
How do I insert a special character such as ' (single quote) into MySQL?

To insert a special character such as “ ‘ “ (single quote) into MySQL, you need to use \’ escape character. The syntax is as follows −
insert into yourTableName(yourColumnName) values(' yourValue\’s ');
To understand the above syntax, let us create two tables. The query to create first table is as follows −
mysql> create table AvoidInsertErrorDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Sentence text
-> );
Query OK, 0 rows affected (0.53 sec)
Now you can insert special character such as ‘ in the table using insert command. The query is as follows −
mysql> insert into AvoidInsertErrorDemo(Sentence) values('a woman\'s hat');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AvoidInsertErrorDemo(Sentence) values('Mrs. Chang\'s house');
Query OK, 1 row affected (0.31 sec)
Display all records from the table using select statement:
mysql> select *from AvoidInsertErrorDemo;
The following is the output −
+----+--------------------+
| Id | Sentence           |
+----+--------------------+
|  1 | a woman's hat      |
|  2 | Mrs. Chang's house |
+----+--------------------+
2 rows in set (0.00 sec)
DATENAME() Function in SQL Server

18 Jan, 2021
DATENAME() function :
This function in SQL Server is used to find a given part of the specified date. Moreover, it returns the output value as a string.
Features :
This function is used to find a given part of the specified date.
This function comes under Date Functions.
This function accepts two parameters namely interval and date.
This function can also include time in the date section.
This function returns the output in string form.
Syntax :
DATENAME(interval, date)
Parameter :
This method accepts two parameters as given below.
interval –It is the specified part that is to be returned. Moreover, the values of the interval can be as given below.
year, yyyy, yy   = Year, which is the specified year.
quarter, qq, q   = Quarter, which is the specified quarter.
month, mm, m     = month, which is the specified month.
dayofyear, dy, y = Day of the year, which is the specified day of the year.
day, dd, d       = Day, which is the specified day.
week, ww, wk     = Week, which is the specified week.
weekday, dw, w   = Weekday, which is the specified week day.
hour, hh         = hour, which is the specified hour.
minute, mi, n    = Minute, which is the specified minute.
second, ss, s    = Second, which is the specified second.
millisecond, ms  = Millisecond, which is the specified millisecond.
date –It is the specified date which is to be used.
Returns :
It returns a given part of the specified date.
Example-1 :
Using DATENAME() function and getting the year part of the specified date.
SELECT DATENAME(year, '2021/01/06');
Output :
2021
Example-2 :
Using DATENAME() function and getting the month part of the specified date.
SELECT DATENAME(month, '2021/01/06');
Output :
January
Example-3 :
Using DATENAME() function and getting the day part of the specified date.
SELECT DATENAME(day, '2021/01/06');
Output :
6
Example-4 :
Using DATENAME() function and getting the hour part of the specified date which includes time as well.
SELECT DATENAME(hour, '2021/01/06 05:30');
Output :
5
Example-5 :
Using DATENAME() function and getting the second part of the specified date which includes time as well using a variable.
DECLARE @date VARCHAR(50);
SET @date = '2019/06/05 07:37:54';
SELECT DATENAME(second, @date);
Output :
54
Application :
This function is used to find the given part of the specified date.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
Plotting graph For IRIS Dataset Using Seaborn And Matplotlib

04 Mar, 2021
Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand and classify the dataset. 
Seaborn provides a beautiful with different styled graph plotting that make our dataset more distinguishable and attractive. 
To install the package write the below code in terminal of ubuntu/Linux or Window Command prompt. 
pip install matplotlib
pip install seaborn
Attribute Information about data set: 
Attribute Information:
   -> sepal length in cm
   -> sepal width in cm
   -> petal length in cm
   -> petal width in cm
   -> class: 
              Iris Setosa
              Iris Versicolour
              Iris Virginica

Number of Instances: 150 

Summary Statistics:
             Min  Max   Mean    SD   Class Correlation
   sepal length: 4.3  7.9   5.84  0.83    0.7826   
    sepal width: 2.0  4.4   3.05  0.43   -0.4194
   petal length: 1.0  6.9   3.76  1.76    0.9490  (high!)
    petal width: 0.1  2.5   1.20  0.76    0.9565  (high!)

Class Distribution: 33.3% for each of 3 classes.
To get the Iris Data click here. 
Loading data 
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv("Iris.csv")   print (data.head(10))
Output: 
Plotting Using Matplotlib 
Python3
import pandas as pdimport matplotlib.pyplot as pltiris = pd.read_csv("Iris.csv") plt.plot(iris.Id, iris["SepalLengthCm"], "r--")plt.show
Scatter Plot 
Python3
iris.plot(kind ="scatter",          x ='SepalLengthCm',          y ='PetalLengthCm')plt.grid()
Plotting using Seaborn 
Python3
import seaborn as sns iris = sns.load_dataset('iris') # style used as a theme of graph# for example if we want black# graph with grid then write "darkgrid"sns.set_style("whitegrid") # sepal_length, petal_length are iris# feature data height used to define# Height of graph whereas hue store the# class of iris dataset.sns.FacetGrid(iris, hue ="species",              height = 6).map(plt.scatter,                              'sepal_length',                              'petal_length').add_legend()
ced18i039
Python-matplotlib
python-modules
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2005 | Question 73

28 Jun, 2021
In a packet switching network, packets are routed from source to destination along a single path having two intermediate nodes. If the message size is 24 bytes and each packet contains a header of 3 bytes, then the optimum packet size is:(A) 4(B) 6(C) 7(D) 9Answer: (D)Explanation: Dividing a message into packets may decrease the transmission time due to parallelism as shown in the following figure.
But after a certain limit reducing the packet size may increase the transmission time also.
Following figure shows the situation given in question.
Let transmission time to transfer 1 byte for all nodes be t. The first packet will take time = (packet size)*3*t. After the first packet reaches the destination, remaining packets will take time equal to (packet size)*t due to parallelism.
If we use 4 bytes as packet size, there will be 24 packets
Total Transmission time = Time taken by first packet + 
                          Time taken by remaining packets 
                       = 3*4*t + 23*4*t = 104t

If we use 6 bytes as packet size, there will be 8 packets
Total Transmission time = 3*6*t + 7*6*t = 60t

If we use 7 bytes as packet size, there will be 6 packets
Total Transmission time = 3*7*t + 5*7*t = 56t

If we use 9 bytes as packet size, there will be 4 packets
Total Transmission time = 3*9*t + 3*9*t = 54t

Source: question 2 of https://www.geeksforgeeks.org/computer-networks-set-6/
Related Articles:
Circuit Switching Vs Packet SwitchingQuiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE IT 2006 | Question 20
GATE | GATE-CS-2016 (Set 1) | Question 45
Scala Set contains() method with example

18 Oct, 2019
The contains() method is utilized to check if an element is present in the set of not.
Method Definition: def contains(elem: A): Boolean
Return Type: It returns true if the element is present in the set else it returns false.
Example #1:
// Scala program of contains() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(41, 12, 23, 43, 1, 72)                   // Applying contains() method         val result = s1.contains(1)                      // Display output        print(result)                 } } 
true

Example #2:
// Scala program of contains() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(41, 12, 23, 43, 1, 72)                   // Applying contains() method         val result = s1.contains(10)                      // Display output        print(result)                 } } 
false

Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Lambda Expression in Scala
How to Install Scala with VSCode?
Inheritance in Scala
Enumeration in Scala
Scala Singleton and Companion Objects
Progressbar widget in Tkinter | Python

01 May, 2019
The purpose of this widget is to reassure the user that something is happening. It can operate in one of two modes –In determinate mode, the widget shows an indicator that moves from beginning to end under program control.In indeterminate mode, the widget is animated so the user will believe that something is in progress. In this mode, the indicator bounces back and forth between the ends of the widget.
Syntax:
widget_object = Progressbar(parent, **options)

 Code #1 In determinate mode
# importing tkinter modulefrom tkinter import * from tkinter.ttk import *  # creating tkinter windowroot = Tk()  # Progress bar widgetprogress = Progressbar(root, orient = HORIZONTAL,              length = 100, mode = 'determinate')  # Function responsible for the updation# of the progress bar valuedef bar():    import time    progress['value'] = 20    root.update_idletasks()    time.sleep(1)      progress['value'] = 40    root.update_idletasks()    time.sleep(1)      progress['value'] = 50    root.update_idletasks()    time.sleep(1)      progress['value'] = 60    root.update_idletasks()    time.sleep(1)      progress['value'] = 80    root.update_idletasks()    time.sleep(1)    progress['value'] = 100  progress.pack(pady = 10)  # This button will initialize# the progress barButton(root, text = 'Start', command = bar).pack(pady = 10)  # infinite loopmainloop()
Output:
# importing tkinter modulefrom tkinter import * from tkinter.ttk import *  # creating tkinter windowroot = Tk()  # Progress bar widgetprogress = Progressbar(root, orient = HORIZONTAL,            length = 100, mode = 'indeterminate')  # Function responsible for the updation# of the progress bar valuedef bar():    import time    progress['value'] = 20    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 40    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 50    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 60    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 80    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 100    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 80    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 60    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 50    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 40    root.update_idletasks()    time.sleep(0.5)      progress['value'] = 20    root.update_idletasks()    time.sleep(0.5)    progress['value'] = 0        progress.pack(pady = 10)  # This button will initialize# the progress barButton(root, text = 'Start', command = bar).pack(pady = 10)  # infinite loopmainloop()
Output:
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.