code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Index.is_categorical() - GeeksforGeeks

17 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.is_categorical() function checks if the index holds categorical data. Categorical variables represent types of data which may be divided into groups. Examples of categorical variables are race, sex, age group, and educational level.
Syntax: Index.is_categorical()
Parameters : Doesn’t take any parameter.
Returns : True if the Index is categorical.
Example #1: Use Index.is_categorical() function to check if the input Index is categorical or not.
# importing pandas as pdimport pandas as pd  # Creating the categorical Indexidx = pd.Index(['Labrador', 'Beagle', 'Mastiff', 'Lhasa',                    'Husky', 'Beagle']).astype('category')  # Print the Indexidx
Output :
Now we find if idx labels are categorical or not.
# Find whether idx1 is categorical or not.idx.is_categorical()
Output :The function has returned true indicating that the values contained in the index are categorical. Example #2: Use Index.is_categorical() function to find if the values contained in the index is categorical or not.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03',                      '2016-02-08', '2017-05-05', '2014-02-11'])  # Print the Indexidx
Output :
Now we check if the labels in the idx are categorical or not.
# test whether idx is having categorical values.idx.is_categorical()
Output :
As we can see in the output, the function has returned False indicating that the values are not categorical in the idx Index.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Standard Input Stream (cin) in  C++

std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.
As an object of class istream, characters can be retrieved either as formatted data using the extraction operator (operator>>) or as unformatted data, using member functions such as read. The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.
You can use this object to read from standard input to a variable. For example, if you want to read an int value in a variable my_intand then print it to the screen, you'd write −
#include<iostream>
int main() {
   int my_int;
   std::cin >> my_int;
   std::cout << my_int;
   return 0;
}
Then save this program to the hello.cpp file. Finally, navigate to the saved location of this file in the terminal/cmd and compile it using −
$ g++ hello.cpp
Run it using −
$ ./a.out
If you give it the input: 15, this will give the output−
15
What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__ in C/C++?

Here we will see what are the differences between __FUNCTION__, __func__ and the __PRETTY_FUNCTION__ in C++.
Basically the __FUNCTION__ and __func__ are same. Some old versions of C and C++ supports __func__. This macro is used to get the name of the current function. The _PRETTY_FUNCTION__ is used to return the detail about the function. Using this we can get which function is used, and in which class it is belonging, etc.
#include<iostream>
using namespace std;
class MyClass{
   public:
      void Class_Function(){
         cout << "The result of __PRETTY_FUNCTION__: " << __PRETTY_FUNCTION__ << endl;
      }
};
void TestFunction(){
   cout << "Output of __func__ is: " << __func__ << endl;
}
main() {
   cout << "Output of __FUNCTION__ is: " << __FUNCTION__ << endl;
   TestFunction();
   MyClass myObj;
   myObj.Class_Function();
}
Output of __FUNCTION__ is: main
Output of __func__ is: TestFunction
The result of __PRETTY_FUNCTION__: void MyClass::Class_Function()
PyQt - QInputDialog Widget

This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter.
The user input can be a number, a string or an item from the list. A label prompting the user what he should do is also displayed.
The QInputDialog class has the following static methods to accept input from the user −
getInt()
Creates a spinner box for integer number
getDouble()
Spinner box with floating point number can be input
getText()
A simple line edit field to type text
getItem()
A combo box from which user can choose item
The following example implements the input dialog functionality. The top level window has three buttons. Their clicked() signal pops up InputDialog through connected slots.
items = ("C", "C++", "Java", "Python")

item, ok = QInputDialog.getItem(self, "select input dialog", 
   "list of languages", items, 0, False)
	
   if ok and item:
      self.le.setText(item)
		
   def gettext(self):
      text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
      if ok:
         self.le1.setText(str(text))
			
   def getint(self):
      num,ok = QInputDialog.getInt(self,"integer input dualog","enter a number")
		
      if ok:
         self.le2.setText(str(num))
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class inputdialogdemo(QWidget):
   def __init__(self, parent = None):
      super(inputdialogdemo, self).__init__(parent)
		
      layout = QFormLayout()
      self.btn = QPushButton("Choose from list")
      self.btn.clicked.connect(self.getItem)
		
      self.le = QLineEdit()
      layout.addRow(self.btn,self.le)
      self.btn1 = QPushButton("get name")
      self.btn1.clicked.connect(self.gettext)
		
      self.le1 = QLineEdit()
      layout.addRow(self.btn1,self.le1)
      self.btn2 = QPushButton("Enter an integer")
      self.btn2.clicked.connect(self.getint)
		
      self.le2 = QLineEdit()
      layout.addRow(self.btn2,self.le2)
      self.setLayout(layout)
      self.setWindowTitle("Input Dialog demo")
		
   def getItem(self):
      items = ("C", "C++", "Java", "Python")
		
      item, ok = QInputDialog.getItem(self, "select input dialog", 
         "list of languages", items, 0, False)
			
      if ok and item:
         self.le.setText(item)
			
   def gettext(self):
      text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
		
      if ok:
         self.le1.setText(str(text))
			
   def getint(self):
      num,ok = QInputDialog.getInt(self,"integer input dualog","enter a number")
		
      if ok:
         self.le2.setText(str(num))
			
def main(): 
   app = QApplication(sys.argv)
   ex = inputdialogdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Precision on a number format in Java

You can include a precision specifier to the following format specifiers −
%f
%e
%g
%s
On floating point, the number of decimal places is known.
Let’s say we declared a Formatter object −
Formatter f1 = new Formatter();
Now, we want 3 decimal places. For that, use 1.3f −
f1.format("%1.3f", 29292929.98765432);
The above will return the number with 3 decimal places −
29292929.988
The following is the final example −
 Live Demo
import java.util.Formatter;
public class Demo {
    public static void main(String args[]) {
       Formatter f1, f2, f3;
       f1 = new Formatter();
       f1.format("%1.3f", 29292929.98765432);
       System.out.println(f1);
       f2 = new Formatter();
       f2.format("%1.7f", 29292929.98765432);
       System.out.println(f2);
       f3 = new Formatter();
       f3.format("%1.9f", 29292929.98765432);
       System.out.println(f3);
    }
}
29292929.988
29292929.9876543
292929.987654320
Sorting Tricks in Node.js - GeeksforGeeks

26 Aug, 2020
Sorting an array using the timer class:
Approach: The sorting requires visiting each element and then performing some operations, which requires for loop to visit those elements.
Now here, we can use setInterval() method to visit all those elements, and perform those operations. And during the visit, we can use setTimer() method to visit all elements, and print the minimum of the array during that period of time.
The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() method of JavaScript API, however, a string of code can’t be passed to get it executed.
Syntax:
setInterval(timerFunction, millisecondsTime);
Parameters: It accepts two parameters which are mentioned above and described below:
timerFunction <function>: It is the function to be executed.
millisecondsTime <Time>: It indicates a period of time between each execution.
The setTimeout() method is used to schedule code execution after waiting for a specified number of milliseconds. It is somewhat like window.setTimeout() Method of JavaScript API, however a string of code can’t be passed to get it executed.
Syntax:
setTimeout(timerFunction, millisecondsTime);
Parameter: It accepts two parameters which are mentioned above and described below:
timerFunction <function>: It is the function to be executed.
millisecondsTime <Time>: It indicates a period of time between each execution.
Examples:
Input: Array = [ 46, 55, 2, 100, 0, 500 ]
Output: [0, 2, 46, 55, 100, 500]

Input: Array = [8, 9, 2, 7, 18, 5, 25]
Output: [ 2, 5, 7, 8, 9, 18, 25 ]
Example 1: File Name: Index.js
const arr = [10, 50, 100, 500, 0, 200];var arr1 = [];  function sortIt() {for (let i of arr) {   // setTimeout(()=> console.log(i), i)   setTimeout(()=> {        arr1.push(i);   arr.splice(arr.indexOf(i), 1);   if(arr.length === 0){     console.log(arr1);   } }, i)}}  sortIt();
Output:
[ 0, 10, 50, 100, 200, 500 ]
Example 2: File Name: Index.js
const arr = [10, 50, 100, 500, 0, 200];var arr1 = [];  function sortIt() {   for (let i of arr) {     // setTimeout(()=> console.log(i), i)     setTimeout(()=> {             arr1.push(i);        i = Math.max.apply(null, arr);                  // arr.splice(arr.indexOf(i), 1);        if(arr1.length === arr.length) {           console.log(arr1);        }     }, i)}}  sortIt();
Run Index.js File using the below command.
node index.js
Output:
[ 0, 10, 50, 100, 200, 500 ]
Node.js-Misc
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
JavaScript | console.log() with Examples
Installation of Node.js on Linux
Express.js express.Router() Function
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
sosreport - Unix, Linux Command

Navid Sheikhol-Eslami <navid@redhat.com>

Eva Schaller <eschalle@redhat.com> [Italian]
Imed Chihi <ichihi@redhat.com> [Arabic] [French]

Steve Conklin <sconklin@redhat.com>
John Berninger <jwb@redhat.com>
Navid Sheikhol-Eslami <navid@redhat.com>
Pierre Amadio <pamadio@redhat.com>


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
MySQL | AES_DECRYPT ( ) Function - GeeksforGeeks

14 Sep, 2021
The MySQL AES_DECRYPT function returns the original string after decrypting an encrypted string. It uses AES(Advanced Encryption Standard) algorithm to perform the decryption. The AES_DECRYPT function returns the decrypted string or NULL if it detects invalid data. 
The value returned by the AES_DECRYPT function is the original plaintext string encrypted using AES_ENCRYPT function. The AES_DECRYPT function accepts two parameters which are the encrypted string and a string used to decrypt the encrypted string. 
Syntax: 
AES_DECRYPT(encrypted_string, key_string)
Parameters Used:  
encrypted_string – It is used to specify the encrypted string.
key_string – It is used to specify the String which is used to decrypt encrypted_string.
Return Value: The AES_DECRYPT function in MySQL returns the original plaintext string encrypted using AES_ENCRYPT function. 
Supported Versions of MySQL: 
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing AES_DECRYPT function on a string. 
SELECT  
AES_DECRYPT(AES_ENCRYPT('ABC', 'key_string'), 'key_string'); 
Output:  
ABC 
Example-2: Implementing AES_DECRYPT function on a string with a combination of characters and integer values. 
SELECT  
AES_DECRYPT(AES_ENCRYPT('ABC123', 'key_string'), 'key_string'); 
Output:  
ABC123 
Example-3: Implementing AES_DECRYPT function on a bigger string. 
SELECT  
AES_DECRYPT(AES_ENCRYPT('geeksforgeeks', 'key_string'), 'key_string'); 
Output:  
geeksforgeeks 
Example-4: Implementing AES_DECRYPT function on a NULL string. 
SELECT  
AES_DECRYPT(AES_ENCRYPT(NULL, 'key_string'), 'key_string'); 
Output:  
NULL  
nnr223442
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
SQL Interview Questions
What is Temporary Table in SQL?
MySQL | Group_CONCAT() Function
Difference between Where and Having Clause in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | INSERT INTO Statement
Can I submit form with multiple submit buttons using jQuery?

Yes, you can submit form with multiple submit buttons. Attack a custom click handler to all the buttons and the check which button is clicked.
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(){
      $("#myform button").click(function (ev) {
      ev.preventDefault()
      if ($(this).attr("value") == "button1") {            
        alert("First Button is pressed - Form will submit")
        $("#myform").submit();
      }
      if ($(this).attr("value") == "button2") {
        alert("Second button is pressed - Form did not submit")
      }
    });
});
</script>
</head>
<body>

<form id="myform">
  <input type="email" name="email" placeholder="Enter email" /><br>
  <button type="submit" value="button1">First Button</button>
  <button type="submit" value="button2">Second Button</button>
</form>

</body>
</html>
How to convert data frame values to a vector by rows in R?

Data can be supplied to us in any form but it is possible that it is not the appropriate one that should be used for analysis. Sometimes data is recorded in a data frame but we might need it as a vector. In such type of situation, we have to change the values of our data frame in a vector. This can be done by reading the data frame values by reading them as.vector after transposing the data frame with t.
Consider the below data frame −
> x1<-rep(c(1,2,3,4,5),times=4)
> x2<-1:20
> x3<-rep(c(5,10,15,20),each=5)
> df<-data.frame(x1,x2,x3)
> df
  x1  x2 x3
 1 1  1  5
 2 2  2  5
 3 3  3  5
 4 4  4  5
 5 5  5  5
 6 1  6 10
 7 2  7 10
 8 3  8 10
 9 4  9 10
10 5 10 10
11 1 11 15
12 2 12 15
13 3 13 15
14 4 14 15
15 5 15 15
16 1 16 20
17 2 17 20
18 3 18 20
19 4 19 20
20 5 20 20
> as.vector(t(df))
[1] 1 1 5 2 2 5 3 3 5 4 4 5 5 5 5 1 6 10 2 7 10 3 8 10 4 9 10 5 10 10 1 11 15 2 12 15 3 13 15 4 14 15 5 15 15 1 16 20 2 17 20 3 18 20
[55] 4 19 20 5 20 20
> Vector_df<-as.vector(t(df))
> sum(Vector_df)
[1] 520
> mean(Vector_df)
[1] 8.666667
Let’s have a look at another example −
> y1<-20:1
> y2<-rep(c(2,4,6,8,10),times=4)
> y3<-c(22,25,27,21,18,19,28,24,29,15,27,24,16,18,28,17,18,26,23,22)
> df_y<-data.frame(y1,y2,y3)
> df_y
   y1 y2 y3
 1 20  2 22
 2 19  4 25
 3 18  6 27
 4 17  8 21
 5 16 10 18
 6 15  2 19
 7 14  4 28
 8 13  6 24
 9 12  8 29
10 11 10 15
11 10  2 27
12  9  4 24
13  8  6 16
14  7  8 18
15  6 10 28
16  5  2 17
17  4  4 18
18  3  6 26
19  2  8 23
20  1 10 22
> Vector_new<-as.vector(t(df_y))
> Vector_new
[1] 20 2 22 19 4 25 18 6 27 17 8 21 16 10 18 15 2 19 14 4 28 13 6 24 12 8 29 11 10 15 10 2 27 9 4 24 8 6 16 7 8 18 6 10 28 5 2 17 4 4 18 3 6 26
[55] 2 8 23 1 10 22
SQL Query to Get Distinct Records Without Using Distinct Keyword

02 Jun, 2021
Here we are going to see how to retrieve unique (distinct) records from a Microsoft SQL Server’s database table without using the DISTINCT clause.
We will be creating an Employee table in a database called “geeks”.
CREATE DATABASE geeks;
USE geeks;
We have the following dup_table table in our geeks database:
CREATE TABLE dup_table(
  dup_id int,
  dup_name varchar(20));
To view the table schema use the below command:
EXEC SP_COLUMNS dup_table;
Use the below query to add records to the table:
INSERT INTO dup_table
VALUES
(1, 'yogesh'),
(2, 'ashish'),
(3, 'ajit'),
(4, 'vishal'),
(3, 'ajit'),
(2, 'ashish'),
(1, 'yogesh');
Now we will retrieve all the data from dup_table Table:
SELECT * FROM dup_table;
Now let’s retrieve distinct rows without using the DISTINCT clause.
The GROUP BY clause can be used to query for distinct rows in a table:
SELECT dup_id, dup_name FROM dup_table
GROUP BY dup_id, dup_name;
 
The set UNION operator can also be used to query for distinct rows in a table:
SELECT dup_id, dup_name FROM dup_table
UNION
SELECT dup_id, dup_name FROM dup_table;
 
The INTERSECT operator can be used to query for distinct rows in a table:
SELECT dup_id, dup_name FROM dup_table
INTERSECT
SELECT dup_id, dup_name FROM dup_table;
CTE stands for Common Table Expressions. It can also be used to query for distinct rows in a table with the row_number() function as shown below:
WITH cte (dup_id, dup_name, dup_count)
AS
(SELECT dup_id, dup_name,
 row_number() over (partition BY dup_id,
 dup_name ORDER BY dup_id) AS dup_count
 FROM dup_table)
SELECT * FROM cte WHERE dup_count = 1;
akshaysingh98088
Picked
SQL-Query
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?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
iptables-save command in Linux with examples

22 May, 2019
The information transfer from a remote computer to your local computer and the vice-versa are viewed as the transfer of data packets by the firewall. The firewall has the control of data packets that are both incoming and outgoing. iptables is a utility to create a rule-based firewall that is pre-installed in most of the Linux computers. iptables command talks to the kernel and helps to control the data packets that use IPv4 protocol as the packet-switching protocol. Since firewall works in kernel level, to use the iptables command, root privilege is required. By default the firewall runs without any rules. The below example shows how to list the rules.
iptables -L -n -v
This example shows how to block all INPUT chain connections from the IP address 10.10.10.10.
iptables -A INPUT -s 10.10.10.10 -j DROP
Whenever the computer is rebooted or restarted, the iptables service and the existing rules are flushed out or reset. Hence, the above rule will be discarded by the computer if the computer gets restarted. To prevent such customized rules from getting scrapped, below command is used. It saves the rules automatically whereas it can also be manually stored in a user-specified file and can be reused later.
iptables-save
Now, even if the computer is restarted, the rules that you saved will be loaded automatically. The screenshot after rebooting the computer.
If the rules are not needed once the computer is restarted or if the purpose is to flush all the rules once the system is rebooted, iptables-save is of no use.
As discussed earlier, the user can use iptables-save command which will save the current iptables rules in a user specified file, that can be used later when the user wants. The following example saves the rules in /etc/iptablesRule.v4 .
iptables-save > /etc/iptablesRule.v4
Even after restarting the computer the following example helps to reload the rules from the saved file.
iptables-restore < /etc/iptablesRule.v4
The following holds the meaning for options.
iptables-save [-c] [-t table]
The -c argument tells iptables-save helps to keep track of the byte and packet counter values when the rule is issued. This helps in resuming the packet transfer from where the rule was previously established. Hence, it is useful in maintaining continuity. The default value is, of course, to not keep the counters intact when issuing this command.
The -t argument tells the iptables-save command which tables to save that contains specific rules and chains. By default, all the tables are saved.
linux-command
Linux-networking-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.product()

22 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.product() function return the value of the product for the requested axis. It multiplies all the element together on the requested axis. By default the index axis is selected.
Syntax: DataFrame.product(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.
Returns : prod : Series or DataFrame (if level specified)
Example #1: Use product() function to find product of all the elements over the column axis in the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2],                    "B":[3, 2, 4, 3, 4],                    "C":[2, 2, 7, 3, 4],                    "D":[4, 3, 6, 12, 7]})  # Print the dataframedf
Let’s use the dataframe.product() function to find the product of each element in the dataframe over the column axis.
# find the product over the column axisdf.product(axis = 1)
Output : Example #2: Use product() function to find the product of any axis in the dataframe. The dataframe contains NaN values.
# importing pandas as pdimport pandas as pd  # Creating the first dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2],                   "B":[3, None, 4, 3, 4],                    "C":[2, 2, 7, None, 4],                   "D":[None, 3, 6, 12, 7]})  # using prod() function to raise each element# in df1 to the power of corresponding element in df2df.product(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python 3 - String len() Method

The len() method returns the length of the string.
Following is the syntax for len() method −
len( str )

NA
This method returns the length of the string.
The following example shows the usage of len() method.
#!/usr/bin/python3

str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
When we run above program, it produces the following result −
Length of the string:  32
halt command in Linux with examples

21 May, 2019
This command in Linux is used to instruct the hardware to stop all the CPU functions. Basically, it reboots or stops the system. If the system is in runlevel 0 or 6 or using the command with –force option, it results in rebooting of the system otherwise it results in shutdown.
Syntax:
halt [OPTION]...
Options:
Files:
/var/log/wtmp : Consists a new runlevel record for the shutdown time.
/var/run/utmp : Gets updated by a shutdown time record when the current runlevel will be read.
Example 1: To cease all CPU function on the system.
$halt
Output:
Broadcast message from ubuntu@ubuntu
root@ubuntu:/var/log# (/dev/pts/0) at 10:15...
The system is going down for halt NOW.

Example 2: To power off the system using halt command.
$halt -p
Output:
Broadcast message from ubuntu@ubuntu
(/dev/pts/0) at 10:16...
The system is going down for power off NOW.

Example 3: halt command with -w option to write shutdown record.
$halt -w
Note: For this, there will be no output on the screen.
linux-command
Linux-system-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
scipy.fftfreq() in Python

29 Aug, 2020
With the help of scipy.fftfreq() method, we can compute the fast fourier transformation frequency and return the transformed array by using this method.
Syntax : scipy.fftfreq(n, freq)
Return : Return the transformed  array.
Example #1 :
In this example we can see that by using scipy.fftfreq() method, we are able to compute the fast fourier transformation frequency and return the transformed array.
Python3
# import scipy and numpyimport scipyimport numpy as np  # Using scipy.fftfreq() methodgfg = scipy.fft.fftfreq(5, 1.096)  print(gfg)
Output :
[ 0.          0.18248175  0.3649635  -0.3649635  -0.18248175]
Example #2 :
Python3
# import scipy and numpyimport scipyimport numpy as np  # Using scipy.fftfreq() methodgfg = scipy.fft.fftfreq(3, 2.4096)  print(gfg)
Output :
[ 0.          0.13833555 -0.13833555]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP Indexed Array

A comma separated sequence of values only instead of key=>value pairs. Each element in such collection has a unique positional index starting from 0. Hence, it is called Indexed array.
Indexed Array object can be initialized by array() function as well as assignment by putting elements inside square brackets [].
//Indexed array using array() function
$arr=array(val1, val2,val3,..);
//Indexed array using assignment method
$arr=[val1, val2, val3,..];
An element in the array can be of any PHP type. We can access an element from the array by its index with following syntax −
$arr[index];
Use of square brackets for assignment of array is available since PHP 5.4
Following example uses square brackets to create an indexed array
 Live Demo
<?php
$arr=[10, "ten",10.0, 1.0E1];
var_dump($arr);
?>
This will produce following result −
array(4) {
   [0]=>
   int(10)
   [1]=>
   string(3) "ten"
   [2]=>
   float(10)
   [3]=>
   float(10)
}
This Example uses array() function to create indexed array
 Live Demo
<?php
$arr=array(10, "ten",10.0, 1.0E1);
var_dump($arr);
?>
This will produce following result −
array(4) {
   [0]=>
   int(10)
   [1]=>
   string(3) "ten"
   [2]=>
   float(10)
   [3]=>
   float(10)
}
We can traverse the array elements using foreach loop as well as for loop as follows −
 Live Demo
<?php
$arr=array(10, "ten",10.0, 1.0E1);
//using for loop. Use count() function to determine array size.
for ($i=0;$i < count($arr); $i++){
   echo $arr[$i] . " ";
}
echo "\n";
//using foreach loop
foreach($arr as $i){
   echo $i . " ";
}
?>
This will produce following result −
10 ten 10 10
10 ten 10 10
This Example shows modify value at certain index using square brackets. To add new element, keep square brackets empty so that next available integer is used as index
 Live Demo
<?php
$arr=array(10, "ten",10.0, 1.0E1);
//modify existing element using index
$arr[3]="Hello";
//add new element using next index
$arr[]=100;
for ($i=0; $i< count($arr); $i++){
   echo $arr[$i];
}
?>
This will produce following result −
10 ten 10 Hello 100
How to get a string from a tkinter filedialog in Python 3?

To interact with the filesystem in a tkinter application, you can use the Tkinter filedialog module. It provides a way to deal with the files in the system. The filedialog module offers many built-in functions to help developers create a variety of file dialogs for the application. You can use any of the filedialog functions in order to implement a dialog in your application.
The most commonly used function is filedialog.askopenfilename() which generally creates a dialog asking the user to open a file in the given program interface.
Suppose we want to get a string or the filename which we open using the filedialog function. We can use the Label widget to display the filename we will open using the function. The following application can be used to open any type of file.
# Import required libraries
from tkinter import *
from tkinter import filedialog

# Create an instance of tkinter window
win = Tk()
win.geometry("700x300")

# Create a dialog using filedialog function
win.filename=filedialog.askopenfilename(initialdir="C:/", title="Select a file")

# Create a label widget
label=Label(win, text="The File you have selected is: " + win.filename, font='Courier 11 bold')
label.pack()

win.mainloop()
Running the above code will display a dialog asking the user to select a file from the C Drive.
Upon selecting a file, it will display the filepath on the window.
Hashing by Multiplication in Data Structure

Here we will discuss about the hashing with multiplication method. For this we use the hash function −
h(x) = ⌊mxA⌋ mod m
Here A is a real-valued constant. The advantage of this method is that the value of m is not so critical. We can take m as power of 2 also. Although any value of A gives the hash function, but some values of A are better than others.
According to Knuth, we can use the golden ratio for A, So A will be
A=5−12=0.61803398
Of course, no matter what value is chosen for A. The pigeonhole principle implies that if u ≥ nm, then there will be one hash value i and some S ⊆ U of size n, such that h(x) = i for all x in S.
So we can say that the worst case hashing by multiplication is as bad as hashing by division.
Possible to make a divisible by 3 number using all digits in an array in C++

In this problem, we are given an array. Our task is to check whether a number generated by using all digits of the elements of the array is divisible by 3. If possible then print “Yes” otherwise print “No”.
Let’s take an example to understand the problem
Input − arr = {3, 5, 91, }
Output − YES
Explanation − The number 5193 is divisible by 3. So, our answer is YES.
To solve this problem, we will check its divisibility by 3.
Divisibility by 3 − a number is divisible by 3 if the sum of its digits is divisible by 3.
Now, we will have to find the sum of all array elements. If this sum is divisible by 3, then it is possible to print YES. otherwise No.
Program to show the implementation of our solution
 Live Demo
#include <iostream>
using namespace std;
bool is3DivisibleArray(int arr[]) {
   int n = sizeof(arr) / sizeof(arr[0]);
   int rem = 0;
   for (int i=0; i<n; i++)
      rem = (rem + arr[i]) % 3;
   return (rem == 0);
}
int main(){
   int arr[] = { 23, 64, 87, 12, 9 };
   cout<<"Creating a number from digits of array which is divisible by 3 ";
   is3DivisibleArray(arr)?cout<<"is Possible":cout<<"is not Possible";
   return 0;
}
Creating a number from digits of array which is divisible by 3 is Possible
How to deserialize a JSON into Javascript object?

JSON is literally Javascript Object notation. JS has built in support
using the JSON object to parse JSON strings into JS objects.
You can use it in the following way −
const json = '{"result":true, "count":42}';
// Parse the object
const obj = JSON.parse(json);
console.log(obj.count);
console.log(obj.result);
This will give the output −
42
true
Travelling Salesman Problem

One sales-person is in a city, he has to visit all other cities those are listed, the cost of traveling from one city to another city is also provided. Find the route where the cost is minimum to visit all of the cities once and return back to his starting city.
The graph must be complete for this case, so the sales-person can go from any city to any city directly.
Here we have to find minimum weighted Hamiltonian Cycle.
Input:
Cost matrix of the matrix.
0  20 42 25 30
20  0 30 34 15
42 30  0 10 10
25 34 10  0 25
30 15 10 25  0

Output:
Distance of Travelling Salesman: 80
travellingSalesman (mask, pos)
There is a table dp, and VISIT_ALL value to mark all nodes are visited
Input − mask value for masking some cities, position.
Output minus; Find the shortest route to visit all the cities.
Begin
   if mask = VISIT_ALL, then //when all cities are visited
      return cost[pos, 0]
   if dp[mask, pos] ≠ -1, then
      return dp[mask, pos]
   finalCost := ∞

   for all cities i, do
      tempMask := (shift 1 left side i times)
      if mask AND tempMask = 0, then
         tempCpst := cost[pos, i] +
         travellingSalesman(mask OR tempMask, i)
         finalCost := minimum of finalCost and tempCost
   done

   dp[mask, pos] = finalCost
   return finalCost
End
#include<iostream>
#define CITY 5
#define INF 9999
using namespace std;

int cost[CITY][CITY] = {
   {0, 20, 42, 25, 30},
   {20, 0, 30, 34, 15},
   {42, 30, 0, 10, 10},
   {25, 34, 10, 0, 25},
   {30, 15, 10, 25, 0}
};
                         
int VISIT_ALL = (1 << CITY) - 1;

int dp[16][4];    //make array of size (2^n, n)

int travellingSalesman(int mask, int pos) {
   if(mask == VISIT_ALL)    //when all cities are marked as visited
      return cost[pos][0];    //from current city to origin
         
   if(dp[mask][pos] != -1)    //when it is considered
      return dp[mask][pos];
         
   int finalCost = INF;
         
   for(int i = 0; i<CITY; i++) {
      if((mask & (1 << i)) == 0) {    //if the ith bit of the result is 0, then it is unvisited
         int tempCost = cost[pos][i] + travellingSalesman(mask | (1 << i), i);    //as ith city is visited
         finalCost = min(finalCost, tempCost);
      }
   }
   return dp[mask][pos] = finalCost;
}

int main() {    
   int row = (1 << CITY), col = CITY;
   for(int i = 0; i<row; i++)
      for(int j = 0; j<col; j++)
         dp[i][j] = -1;    //initialize dp array to -1
    cout << "Distance of Travelling Salesman: ";  
    cout <<travellingSalesman(1, 0);    //initially mask is 0001, as 0th city already visited
}
Distance of Travelling Salesman: 80
Fuzzy Search in JavaScript - GeeksforGeeks

05 Nov, 2020

Fuzzy searching matches the meaning, not necessarily the precise wording or specified phrases. It performs something the same as full-text search against data to see likely misspellings and approximate string matching. it’s a very powerful tool that takes into consideration the context of the phrase you wish to look.
Fuzzy Search is additionally called as approximate string matching. It’s powerful because often text data is messy. For instance, shorthand and abbreviated text are common in various sorts of data. Additionally, outputs from OCR or voice to text conversions tend to be messy or imperfect. Thus, we want to make the foremost of our data by extrapolating the maximum amount of information as possible.
Fuzzy search is more powerful than exact searching when used for research and investigation. Fuzzy search is very useful when researching unfamiliar, foreign-language, or sophisticated terms, the correct spellings of which don’t seem to be widely known. Fuzzy search can also be used to locate individuals supported incomplete or partially inaccurate identifying information.
Installing the package:
$ npm install --save fuse.js
Example:
Javascript
 

 
 










const Fuse = require('fuse.js')
 
const people = [
    {
        name: "John",
        city: "New York"
    },
    {
        name: "Steve",
        city: "Seattle"
    },
    {
        name: "Bill",
        city: "Omaha"
    }
]
 
const fuse = new Fuse(people, {
    keys: ['name', 'city']
})
 
// Search
const result = fuse.search('jon')
 
console.log(result)






Output:
[ { item: { name: 'John', city: 'New York' }, refIndex: 0 } ]

Some common fuzzy search libraries for JavaScript are:
List.js : https://listjs.com/
Fuse.js : https://fusejs.io/
Fuzzy-search :https://www.npmjs.com/package/fuzzy-search

JavaScript-Misc


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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
C | Pointer Basics | Question 17 - GeeksforGeeks

28 Jun, 2021
Assume that float takes 4 bytes, predict the output of following program.
#include <stdio.h>  int main(){    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};    float *ptr1 = &arr[0];    float *ptr2 = ptr1 + 3;      printf("%f ", *ptr2);    printf("%d", ptr2 - ptr1);     return 0;}
(A) 90.5000003
(B) 90.50000012(C) 10.00000012(D) 0.5000003Answer: (A)Explanation: When we add a value x to a pointer p, the value of the resultant expression is p + x*sizeof(*p) where sizeof(*p) means size of data type pointed by p. That is why ptr2 is incremented to point to arr[3] in the above code. Same rule applies for subtraction. Note that only integral values can be added or subtracted from a pointer. We can also subtract or compare two pointers of same type.Quiz of this Question
C-Pointer Basics
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Function Pointer in C
Substring in C++
std::string class in C++
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
Find the sum of series 3, -6, 12, -24 . . . upto N terms - GeeksforGeeks

25 Mar, 2021
Given an integer N. The task is to find the sum upto N terms of the given series: 
3, -6, 12, -24, ... upto N terms
Examples:  
Input : N = 5
Output : Sum = 33

Input : N = 20
Output : Sum = -1048575
 
On observing the given series, it can be seen that the ratio of every term with their previous term is same which is -2. Hence the given series is a GP(Geometric Progression) series.You can learn more about GP series here.So, when r < 0.In above GP series the first term i:e a = 3 and common ratio i:e r = (-2).Therefore, . Thus, .Below is the implementation of above approach:  
C++
Java
Python
C#
PHP
Javascript
//C++ program to find sum upto N term of the series:// 3, -6, 12, -24, ..... #include<iostream>#include<math.h>using namespace std;//calculate sum upto N term of series class gfg{    public:    int Sum_upto_nth_Term(int n)    {        return (1 - pow(-2, n));    }};// Driver codeint main(){    gfg g;    int N = 5;    cout<<g.Sum_upto_nth_Term(N);}
//Java program to find sum upto N term of the series:// 3, -6, 12, -24, ..... import java.util.*;//calculate sum upto N term of series class solution{ static int Sum_upto_nth_Term(int n){    return (1 -(int)Math.pow(-2, n));} // Driver codepublic static void main (String arr[]){    int N = 5;    System.out.println(Sum_upto_nth_Term(N));} }
# Python program to find sum upto N term of the series:# 3, -6, 12, -24, ..... # calculate sum upto N term of seriesdef Sum_upto_nth_Term(n):    return (1 - pow(-2, n)) # Driver codeN = 5print(Sum_upto_nth_Term(N))
// C# program to find sum upto// N term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesclass GFG{ static int Sum_upto_nth_Term(int n){    return (1 -(int)System.Math.Pow(-2, n));} // Driver codepublic static void Main(){    int N = 5;    System.Console.WriteLine(Sum_upto_nth_Term(N));}} // This Code is contributed by mits
<?php// PHP program to find sum upto// Nth term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesfunction Sum_upto_nth_Term($n){    return (1 - pow(-2, $n));} // Driver code$N = 5;echo (Sum_upto_nth_Term($N)); // This code is contributed// by Sach_Code?>
<script>// Java program to find sum upto N term of the series:// 3, -6, 12, -24, ..... // calculate sum upto N term of seriesfunction Sum_upto_nth_Term( n) {    return (1 - parseInt( Math.pow(-2, n)));} // Driver code     let N = 5;    document.write(Sum_upto_nth_Term(N)); // This code is contributed by 29AjayKumar</script>
33
 
SoumikMondal
SURENDRA_GANGWAR
Mithun Kumar
Sach_Code
29AjayKumar
Geometric Progression
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Program to convert a given number to words
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Find first and last digits of a number
atomic.Store() Function in Golang With Examples - GeeksforGeeks

01 Apr, 2020
In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The Store() function in Go language is used to set the value of the Value to x(i.e, interface).And all the calls to Store method for a stated Value should use values of an identical concrete type. Moreover, Store of a contradictory type will call panic. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func (v *Value) Store(x interface{})

Here, v is the value of any type and x is the interface which is the output result type of Store method.
Note: (*Value) is the pointer to a Value type. And Value type supplied in the sync/atomic standard package is used to atomically store as well as load values of any type.
Return value: It stores the value provided and can be loaded when required.
Example 1:
// Program to illustrate the usage of// Store function in Golang  // Including main packagepackage main  // importing fmt and sync/atomicimport (    "fmt"    "sync/atomic")  // Main functionfunc main() {      // Defining a struct type L    type L struct{ x, y, z int }      // Defining a variable to assign    // values to the struct type L    var r1 = L{9, 10, 11}      // Defining Value type to store    // values of any type    var V atomic.Value      // Calling Store function    V.Store(r1)      // Printed if the value stated is stored    fmt.Println("Any type of value is stored!")}
Output:
Any type of value is stored!

In the above example, we have used Value type in order to store the values of any type. And these values are stored at r1 which is the interface stated.
Example 2:
// Program to illustrate the usage of// Store function in Golang  // Including main packagepackage main  // importing fmt and sync/atomicimport (    "sync/atomic")  // Main functionfunc main() {      // Defining a struct type L    type L struct{ x, y, z int }      // Defining a variable to assign    // values to the struct type L    var r1 = L{9, 10, 11}      // Defining Value type to store    // values of any type    var V atomic.Value      // Calling Store function    V.Store(r1)      // Storing value of     // different concrete type    V.Store("GeeksforGeeks")}
Output:
panic: sync/atomic: store of inconsistently typed value into Value

goroutine 1 [running]:
sync/atomic.(*Value).Store(0x40c018, 0x99a40, 0xb23e8, 0x40e010)
    /usr/local/go/src/sync/atomic/value.go:77 +0x160
main.main()
    /tmp/sandbox206117237/prog.go:31 +0xc0

Here, the value stored above is of different concrete type so panic is called.
GoLang-atomic
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
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Slices in Golang
Golang Maps
Interfaces in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
How to Trim a String in Golang?
How to change the space between bars in a barplot in R?

By default, the space between bars is equal irrespective of the number of bars in the plot. If we want to have different space between bars then space arguments need to be used inside the barplot function but the first value does not make an impact because the first space is fixed between Y-axis and the first bar. For example, if we have a vector x that contains three values then the barplot with different space between bars can be created by using the below command −
barplot(x,space=c(0.5,0.1,0.5))
 Live Demo
x<-rpois(4,5)
x
[1] 3 8 4 4
barplot(x)
barplot(x,space=c(0.01,0.1,0.5,0.1))
barplot(x,space=c(0.1,0.2,0.2,0.5))