code-rag-bench/online-tutorials huggingface dataset:
aplay command in Linux with examples - GeeksforGeeks

05 Mar, 2019
aplay is a command-line audio player for ALSA(Advanced Linux Sound Architecture) sound card drivers. It supports several file formats and multiple soundcards with multiple devices. It is basically used to play audio on command-line interface. aplay is much the same as arecord only it plays instead of recording. For supported soundfile formats, the sampling rate, bit depth, and so forth can be automatically determined from the soundfile header.
Syntax:
aplay [flags] [filename [filename]] ...

If filename not specified uses Standard output.
Options:
-h, –help : Show the help information.
–version : Print current version.
-l, –list-devices : List all soundcards and digital audio devices.
-L, –list-pcms : List all PCMs(Pulse Code Modulation) defined.
-D, –device=NAME : Select PCM by name.
-q –quiet : Quiet mode. Suppress messages (not sound :)).
-t, –file-type TYPE : File type (voc, wav, raw or au). If this parameter is omitted the WAVE format is used.
-c, –channels=# : The number of channels. The default is one channel. Valid values are 1 through 32.
-f –format=FORMAT : If no format is given U8 is used.
-r, –rate=# : Sampling rate in Hertz. The default rate is 8000 Hertz.
-d, –duration=# : Interrupt after # seconds.
-s, –sleep-min=# : Min ticks to sleep. The default is not to sleep.
-M, –mmap : Use memory-mapped (mmap) I/O mode for the audio stream. If this option is not set, the read/write I/O mode will be used.
-N, –nonblock : Open the audio device in non-blocking mode.If the device is busy the program will exit immediately.
Note: This command contain various other options that we normally don’t need. If you want to know more about you can simply run following command on your terminal.
aplay --help
Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE DSD_U32_LE DSD_U16_BE DSD_U32_BE
Note: Some of these may not be available on selected hardware.
Examples:
Plays audio for only 10 secs at 2500hz frequency.
Plays full audio clip at 2500hz frezuency.
Display version information.
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Compiling with g++
Percentile rank of a column in a Pandas DataFrame - GeeksforGeeks

17 Aug, 2020
Let us see how to find the percentile rank of a column in a Pandas DataFrame. We will use the rank() function with the argument pct = True to find the percentile rank.
Example 1 :
# import the moduleimport pandas as pd   # create a DataFrame data = {'Name': ['Mukul', 'Rohan', 'Mayank',                  'Shubham', 'Aakash'],        'Location' : ['Saharanpur', 'Meerut', 'Agra',                       'Saharanpur', 'Meerut'],        'Pay' : [50000, 70000, 62000, 67000, 56000]} df = pd.DataFrame(data)    # create a new column of percentile rankdf['Percentile Rank'] = df.Pay.rank(pct = True)  # displaying the percentile rankdisplay(df) 
Output :
Example 2 :
# import the moduleimport pandas as pd   # create a DataFrame ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting',                       'Jayasurya', 'Jayawardene', 'Kohli',                       'Haq', 'Kallis', 'Ganguly', 'Dravid'],             'runs': [18426, 14234, 13704, 13430, 12650,                      11867, 11739, 11579, 11363, 10889]} df = pd.DataFrame(ODI_runs)    # create a new column of percentile rankdf['Percentile Rank'] = df.runs.rank(pct = True)  # displaying the percentile rankdisplay(df) 
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Java Program to Count Number of Digits in a String - GeeksforGeeks

30 Apr, 2021
The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it’s content can’t change. Complete traversal in the string is required to find the total number of digits in a string.
Examples:
Input : string = "GeeksforGeeks password is : 1234"
Output: Total number of Digits = 4

Input : string = "G e e k s f o r G e e k 1234"
Output: Total number of Digits = 4
Approach:
Create one integer variable and initialize it with 0.Start string traversal.If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable.After the end of the traversal, print variable.
Create one integer variable and initialize it with 0.
Start string traversal.
If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable.
After the end of the traversal, print variable.
Below is the implementation of the above approach:
Java
// Java Program to Count Number of Digits in a Stringpublic class GFG {     public static void main(String[] args)    {        String str = "GeeksforGeeks password is : 1234";        int digits = 0;        for (int i = 0; i < str.length(); i++) {            if (str.charAt(i) >= 48 && str.charAt(i) <= 57)                digits++;        }        System.out.println("Total number of Digits = "                           + digits);    }}
  
Total number of Digits = 4
 
Time Complexity: O(N), where N is the length of the string.
 
pranaythanneru
Java-String-Programs
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Python | sympy.symbols() method - GeeksforGeeks

02 Aug, 2019
With the help of sympy.symbols() method, we can declare some variables for the use of mathematical expression and polynomials by using sympy.symbols() method.
Syntax : sympy.symbols()Return : Return nothing or None.
Example #1 :In this example we can see that by using sympy.symbols() method, we are able to get the variables for mathematical expression and polynomials.
# import sympyfrom sympy import *  # Use sympy.symbols() methodx, y = symbols('x y')x = 2gfg = x**2 + 4 * x + 4  print(gfg)
Output :
16
Example #2 :
# import sympyfrom sympy import *  # Use sympy.symbols() methodx, y = symbols('x y')x = 5y = 5gfg = x**2 + y  print(gfg)
Output :
30
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Convert a String to an Expression in R Programming - parse() Function - GeeksforGeeks

24 Jun, 2020
parse() function in R Language is used to convert an object of character class to an object of expression class.
Syntax: parse(text = character)
Parameters:character: Object of character class
Example 1:
# R program to convert # character to expression  # Creating an object of character classx <- "sin(pi / 2)"  # Class of objectclass(x)  # Calling parse() Functionx1 <- parse(text = x)  # Class of parsed objectclass(x1)
Output:
[1] "character"
[1] "expression"

Example 2:
# R program to convert # character to expression  # Creating an object of character classx <- "2 ^ 3"  # Evaluating the value of objecteval(x)  # Calling parse() Functionx1 <- parse(text = x)  # Evaluating the value of objecteval(x1)
Output:
[1] "2^3"
[1] 8

R String-Functions
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
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
Replace Specific Characters in String in R
numpy.random.permutation() in Python - GeeksforGeeks

15 Jul, 2020
With the help of numpy.random.permutation() method, we can get the random samples of sequence of permutation and return sequence by using this method.
Syntax : numpy.random.permutation(x)
Return : Return the random sequence of permuted values.
Example #1 :
In this example we can see that by using numpy.random.permutation() method, we are able to get the sequence of permutation and it will return the sequence by using this method.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt  # Using permutation() methodgfg = np.random.permutation(200)  count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt  arr = np.arange(12).reshape((4, 3))# Using permutation() methodgfg = np.random.permutation(arr)  count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How to check a JavaScript Object is a DOM Object ? - GeeksforGeeks

19 Jun, 2019
Prerequisite: DOM (Document object model), Instanceof Operator
DOM (Document Object Model): Document Object Model is a hierarchical representation of HTML and XML documents in a format that is easier to interpret in terms of programming. It makes manipulation of tags, elements, attributes, and classes by interpreting its structure in the form of a tree-like model consisting of nodes.
Element: In HTML DOM, Element is the general base class for all objects. An Element object represents all HTML elements.
Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator. The instanceof operator returns a boolean value which specifies whether or not an object is an instance of a given Class.
Syntax:
Object instanceof ObjectType
Parameters:
Object: It stores the Object which need to be tested.
ObjectType: It stores the Object Type to be tested against.
Example:
<!DOCTYPE HTML> <html>   <head>     <title>        How to check a JavaScript         Object is a DOM Object ?    </title></head>  <body>    <div id="div1"></div>     <div id="nonElem"></div>       <script>        // Function to check the object        // id DOM object or not        function isDOM(Obj) {                           // Function that checks whether              // object is of type Element            return Obj instanceof Element;        }              // Set all elements into HTML        var div = document.getElementById('div1');        var nonElem = document.getElementById('nonElem');                  // Creating a non-DOM Object         var x = 1;                   // Checks against HTML elements and        // non-HTML elements        if (isDOM(div))            div.innerHTML = "Div is detected as a DOM Object";                  if (!isDOM(x))             nonElem.innerHTML = "x is detected as a non-DOM Object";     </script></body>  </html>
Output:
Div is detected as a DOM Object
x is detected as a non-DOM Object

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
javascript-object
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
MySQL count(*) from multiple tables?

To achieve this for multiple tables, use the UNION ALL.
The syntax is as follows
select sum(variableName.aliasName)
from
   (
   select count(*) as yourAliasName from yourTableName1
   UNION ALL
   select count(*) as yourAliasName from yourTableName2
   ) yourVariableName;
Let us implement the above syntax. Here, I am using the sample database which has more tables.
The two tables we are using are
userdemo
wheredemo
Here is the query to display all records of both the tables. The query is as follows to display records from table ‘userdemo’.
mysql> select *from userdemo;
The following is the output
+--------+----------+------------------+
| UserId | UserName | RegisteredCourse |
+--------+----------+------------------+
| 1      | John     | Java             |
| 2      | Larry    | C                |
| 3      | Carol    | C++              |
| 4      | Mike     | C#               |
+--------+----------+------------------+
4 rows in set (0.08 sec)
The query is as follows to display records from table ‘wheredemo’.
mysql> select *from wheredemo;
The following is the output
+------+---------+
| Id   | Name    |
+------+---------+
| 101  | Maxwell |
| 110  | David   |
| 1000 | Carol   |
| 1100 | Bob     |
| 115  | Sam     |
+------+---------+
5 rows in set (0.20 sec)
Here is the query to implement count(*) from both the above tables
mysql> select sum(tbl.EachTableCount)
   -> from
   -> (
   -> select count(*) as EachTableCount from userdemo
   -> UNION ALL
   -> select count(*) as EachTableCount from wheredemo
   -> )tbl;
The following is the output
+-------------------------+
| sum(tbl.EachTableCount) |
+-------------------------+
| 9                       |
+-------------------------+
1 row in set (0.00 sec)
What happens if we try to extend a final class in java?

In Java final is the access modifier which can be used with a filed class and a method.
When a method if final it cannot be overridden.
When a variable is final its value cannot be modified further.
When a class is finale it cannot be extended.
When we try to extend a final class that will lead to a compilation error saying “cannot inherit from final SuperClass”
In the following Java program, we have a final class with name SuperClass and we are trying to inherent it from another class (SubClass).
final class SuperClass{
   public void display() {
      System.out.println("This is a method of the superclass");
   }
}
public class SubClass extends SuperClass{
   public static void main(String args[]){
      //Calling method of the superclass
      new SubClass().display();
   }
}
On compiling, this program generates a compilation error as shown below −
SubClass.java:7: error: cannot inherit from final SuperClass
public class SubClass extends SuperClass{
                              ^
1 error
How to Find Armstrong Number in an Interval using Python?

If sum of cubes of individual digits in a number add up to the number itself, it is called armstrong number. for example 153=1**3+5**3+3**3
Following Python program find armstrong numbers between 100 to 1000
for num in range(100,1000):
  temp=num
  sum=0
  while temp>0:
      digit=temp%10
      sum=sum+digit**3
      temp=temp//10
      if sum==num:
           print (num)
The output is as follows −
153
370
371
407
Display video inside HTML5 canvas

You can try the following code snippet to display video inside HTML5 canvas.
var canvas1 = document.getElementById('canvas');
var context = canvas1.getContext('2d');
var video = document.getElementById('video');
video.addEventListener('play', function () {
   var $this = this;
   (function loop() {
      if (!$this.paused && !$this.ended) {
         context.drawImage($this, 0, 0);
         setTimeout(loop, 1000 / 30);
      }
   })();
}, 0);
Sorting List in SAP UI5 project

Yes, you can. You can use the available sorter property available on the List. It lets you specify all the required details. For e.g. −
<List
Items="{
  path: '/EmployeeCollection',
  sorter: {
    path: 'EmployeeName',
    descending: true,
    group: true
  }
}"
headerText="Employees" />
I have specified the employee collection to be sorted on the basis of the name of the employee and specified that the sorting should be in descending manner. It should also consider grouping while sorting the data.
How can I get a list of locally installed Python modules?

There are multiple ways to get a list of locally installed Python modules. Easiest way is using the Python shell, for example,
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
BaseHTTPServer      brain_nose          markupbase          stat
Bastion             brain_numpy         marshal             statvfs
CGIHTTPServer       brain_pkg_resources math                string
Canvas              brain_pytest        matplotlib          stringold
...
...
If you want to get the list of installed modules in your terminal, you can use the Python package manager, pip. For example,
$ pip freeze
You will get the output:
asn1crypto==0.22.0
astroid==1.5.2
attrs==16.3.0
Automat==0.5.0
backports.functools-lru-cache==1.3
cffi==1.10.0
...
If you have pip version >= 1.3, you can also use pip list. For example,
$ pip list
asn1crypto (0.22.0)
astroid (1.5.2)
attrs (16.3.0)
Automat (0.5.0)
backports.functools-lru-cache (1.3)
...
...
Order By date ASC in MySQL?

You can use STR_TO_DATE() function. Let us first create a table −
mysql> create table DemoTable
   (
   AdmissionDate varchar(200)
   );
Query OK, 0 rows affected (1.19 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('12-01-2019');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('14-12-2016');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('26-04-2018');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values('31-05-2013');
Query OK, 1 row affected (0.30 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 12-01-2019    |
| 14-12-2016    |
| 26-04-2018    |
| 31-05-2013    |
+---------------+
4 rows in set (0.00 sec)
Following is the query to sort order by date ASC −
mysql> select *from DemoTable ORDER BY STR_TO_DATE(AdmissionDate,'%d-%m-%Y') ASC;
This will produce the following output −
+---------------+
| AdmissionDate |
+---------------+
| 31-05-2013    |
| 14-12-2016    |
| 26-04-2018    |
| 12-01-2019    |
+---------------+
4 rows in set (0.00 sec)
How to convert Unicode values to characters in JavaScript?

To convert Unicode values to characters in JavaScript, use the fromCharCode() string method.
You can try to run the following code to convert Unicode to character −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         var a = String.fromCharCode(72);
         document.write("Character: "+a);
      </script>
   </body>
</html>
What are the differences between the BLOB and TEXT datatypes in MySQL?

BLOB stands for Binary Large Objects and as its name suggests, it can be used for storing binary data while TEXT is used for storing large number of strings. BLOB can be used to store binary data that means we can store pictures, videos, sounds and programs also.
For example, the following image can be stored into BLOB because the image has binary data.
BLOB values behave like byte string and BLOB does not have a character set. Therefore, comparison and sorting is fully dependent upon numeric values of bytes.
TEXT values behave like non-binary string or character string. TEXT has a character set and the comparison/ sorting fully depends upon the collection of character set.
mysql> create table TextTableDemo
   -> (
   -> Address TEXT
   -> );
Query OK, 0 rows affected (0.58 sec)
To describe tables with the help of DESC command.
mysql> DESC TextTableDemo;
The following is the output.
+---------+------+------+-----+---------+-------+
| Field   | Type | Null | Key | Default | Extra |
+---------+------+------+-----+---------+-------+
| Address | TEXT | YES  |     | NULL    |       |
+---------+------+------+-----+---------+-------+
1 row in set (0.08 sec)

In the above output, “Type” is telling the data type, which is TEXT.
mysql> create table BlobTableDemo
   -> (
   -> Images BLOB
   -> );
Query OK, 0 rows affected (0.51 sec)
Let us get the description of the table with the help of DESC command.
mysql> desc BlobTableDemo;
The following is the output.
+--------+------+------+-----+---------+-------+
| Field  | Type | Null | Key | Default | Extra |
+--------+------+------+-----+---------+-------+
| Images | BLOB | YES  |     | NULL    |       |
+--------+------+------+-----+---------+-------+
1 row in set (0.04 sec)

In the sample output, “Type” is telling the data type which is BLOB.
JavaScript TypeError - Invalid assignment to const "X" - GeeksforGeeks

31 Jul, 2020
This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared.
Message:
TypeError: invalid assignment to const "x" (Firefox)
TypeError: Assignment to constant variable. (Chrome)
TypeError: Assignment to const (Edge)
TypeError: Redeclaration of const 'x' (IE)

Error Type:
TypeError

Cause of Error: A const value in JavaScript is changed by the program which can not be altered during normal execution. 
Example 1: In this example, the value of the variable(‘GFG’) is changed, So the error has occurred.
HTML
<script>    const GFG = "This is GFG";    // Error here    GFG = "This is GeeksForGeeks"; </script>
Output(in console):
TypeError: Assignment to const

Example 2: In this example, the value of the object(‘GFG_Obj’) is changed, So the error has occurred.
HTML
<script>    const GFG_Obj = {key: 'val1'};    // Error here    GFG_Obj = {key: 'val2'}; </script>
Output:
TypeError: Assignment to const

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to combine two arrays into an array of objects in JavaScript?

Let’s say the following are our two arrays −
var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike','Sam','Carol'];
To combine two arrays into an array of objects, use map() from JavaScript.
var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike','Sam','Carol'];
var arrayOfObject = firstArray.map(function (value, index){
   return [value, secondArray[index]]
});
console.log("The First Array=");
console.log(firstArray);
console.log("The Second Array=");
console.log(secondArray);
console.log("The mix Of array object=");
console.log(arrayOfObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo190.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo190.js
The First Array=
[ 'John', 'David', 'Bob' ]
The Second Array=
[ 'Mike', 'Sam', 'Carol' ]
The mix Of array object=
[ [ 'John', 'Mike' ], [ 'David', 'Sam' ], [ 'Bob', 'Carol' ] ]
C | Dynamic Memory Allocation | Question 2 - GeeksforGeeks

28 Jun, 2021
Consider the following three C functions :
[PI] int * g (void) {   int x= 10;   return (&x); }      [P2] int * g (void) {   int * px;   *px= 10;   return px; }     [P3] int *g (void) {   int *px;   px = (int *) malloc (sizeof(int));   *px= 10;   return px; }
Which of the above three functions are likely to cause problems with pointers? (GATE 2001)(A) Only P3(B) Only P1 and P3(C) Only P1 and P2
(D) P1, P2 and P3Answer: (C)Explanation: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.In P2, pointer variable px is being assigned a value without allocating memory to it.P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap.Quiz of this Question
C-Dynamic Memory Allocation
Dynamic Memory Allocation
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
How to check whether column value is NULL or having DEFAULT value in MySQL?

You can use the concept of IFNULL() for this. Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100) DEFAULT 'Larry',
   Age int DEFAULT NULL
);
Query OK, 0 rows affected (0.73 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(Name,Age) values('John',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Age) values(24);
Query OK, 1 row affected (0.13 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | John  | 23   |
| 2  | Larry | NULL |
| 3  | David | NULL |
| 4  | Larry | 24   |
+----+-------+------+
4 rows in set (0.00 sec)
Following is the query to check whether column value is NULL or having DEFAULT value in MySQL.
mysql> select *from DemoTable WHERE IFNULL(Name, DEFAULT(Name)) <> DEFAULT(Name);
This will produce the following output −
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | John  | 23   |
| 3  | David | NULL |
+----+-------+------+
2 rows in set (0.00 sec)
PHP | image_type_to_extension() Function - GeeksforGeeks

15 Nov, 2019
The image_type_to_extension() function is an inbuilt function in PHP which is used to get the file extension for an image type. This function can be found in any PHP version silimar or greater than 5.2.0.
Syntax:
string image_type_to_extension( int $imagetype, bool $include_dot )
Parameters: This function accepts two parameters as mentioned above and described below:
$imagetype: It takes an integer value as first parameter that is one of the IMAGETYPE_XXX constant. For example: IMAGETYPE_GIF, IMAGETYPE_JPEG etc.
$include_dot: The second parameter takes a boolean value to decide whether to prepend a dot to the extension or not. The default value is set to TRUE in the function.
Return Value: This function returns a string value associated with the extension corresponding to the given image type.
Below programs illustrate the image_type_to_extension() function in PHP:
Program 1:
<?php   // Extension with dotecho image_type_to_extension(IMAGETYPE_PNG, TRUE) . "\n";  // Extension without dotecho image_type_to_extension(IMAGETYPE_PNG, FALSE);  ?>
Output:
.png
png

Program 2:
<?php  // Create image instance$image = imagecreatetruecolor(100, 100);   // Creates an image with .png extensionimagepng($image, './test' .         image_type_to_extension(IMAGETYPE_PNG));  // Free any memory associated with imageimagedestroy($image);  ?>
Output:
Creates an image with name test.png
Reference: https://www.php.net/manual/en/function.image-type-to-extension.php
Image-Processing
PHP-function
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to generate PDF file using PHP ?
How to create admin login page using PHP?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Java program to print unique values from a list

To print unique values from a List in Java, the code is as follows −
 Live Demo
import java.io.*;
public class Demo{
   static void distinct_vals(int my_arr[], int len){
      for (int i = 0; i < len; i++){
         int j;
         for (j = 0; j < i; j++)
         if (my_arr[i] == my_arr[j])
            break;
         if (i == j)
         System.out.print( my_arr[i] + " ");
      }
   }
   public static void main (String[] args){
      int my_arr[] = {55, 67, 99, 11, 54, 55, 88, 99, 1, 13, 45};
      int arr_len = my_arr.length;
      System.out.println("The distinct elements in the array are ");
      distinct_vals(my_arr, arr_len);
   }
}
The distinct elements in the array are
55 67 99 11 54 88 1 13 45
A class named Demo contains a function named ‘distinct_vals’ that takes in the array and the length of the array as parameters. It iterates over the array and checks for duplicate values and prints only the unique values of the array. In the main function, an array is defined and its length is stored in a variable. This ‘distinct_vals’ function is called with the defined array and length and the result is displayed on the console.
How will you handle alerts in Selenium with python?

We can handle alerts in Selenium with the help of numerous APIs. The alerts are basically the browser popups that are triggered for either dismissing or accepting the data entered.
All these actions are performed by Selenium with the help of class selenium.webdriver.common.alert.Alert(driver). It has the methods to extract the text on a particular alert, accepting and dismissing these pop ups of the browser.
The elements on the alert cannot be identified by simply spying them from the html code. This is because these are considered implemented by Javascript.
Selenium alert methods are listed below −
accept() – This method accepts an alert pop up.
accept() – This method accepts an alert pop up.
Syntax −
a = Alert(driver)
a.accept()
dismiss() – This method dismisses an alert pop up.
dismiss() – This method dismisses an alert pop up.
Syntax −
a = Alert(driver)
a.dismiss()
send_keys(value) – This method keys in text on alert pop up.
send_keys(value) – This method keys in text on alert pop up.
Syntax −
a = Alert(driver)
a.send_keys("Yes")
text – This method extracts text from the alert pop up.
text – This method extracts text from the alert pop up.
Syntax −
a = Alert(driver)
print(a.text)
switch_to.alert – This method switches focus to alert.
switch_to.alert – This method switches focus to alert.
Syntax −
a = driver.switch_to.alert
Code Implementation with alert methods.
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
#click on submit button
driver.find_element_by_xpath("//button[@name='submit']").click()
# alert object creation and switching focus to alert
a = driver.switch_to.alert
# accept the alert
a.accept()
driver.close()
DecimalFormat("00.00E0") in Java

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. Let us set DecimalFormat("00.00E0") and use the format() method as well.
DecimalFormat decFormat = new DecimalFormat("00.00E0");
System.out.println(decFormat.format(-289.8787));
System.out.println(decFormat.format(8.19));
Since, we have used DecimalFormat class in Java, therefore importing the following package is a must −
import java.text.DecimalFormat;
The following is the complete example −
 Live Demo
import java.text.DecimalFormat;
public class Demo {
   public static void main(String[] argv) throws Exception {
      DecimalFormat decFormat = new DecimalFormat("00.00E0");
      System.out.println(decFormat.format(-289.8787));
      System.out.println(decFormat.format(8.19));
      System.out.println(decFormat.format(9897.88));
      System.out.println(decFormat.format(9.9099));
      System.out.println(decFormat.format(12.788));
      System.out.println(decFormat.format(9.678));
   }
}
-28.99E1
81.90E-1
98.98E2
99.10E-1
12.79E0
96.78E-1
drag_and_drop_by_offset method - Action Chains in Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around drag_and_drop_by_offset method on Action Chains in Python Selenium. drag_and_drop_by_offset method holds down the left mouse button on the source element, then moves to the target offset and releases the mouse button.
Syntax –
drag_and_drop_by_offset(source, xoffset, yoffset)
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use drag_and_drop_by_offset method as an Action chain as below –
drag_and_drop_by_offset(element, 100, 200)

To demonstrate, drag_and_drop_by_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # drag_and_drop_by_offset the itemaction.drag_and_drop_by_offset(element, 100, 200)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
Matrix multiplication algorithm

In this section we will see how to multiply two matrices. The matrix multiplication can only be performed, if it satisfies this condition. Suppose two matrices are A and B, and their dimensions are A (m x n) and B (p x q) the resultant matrix can be found if and only if n = p. Then the order of the resultant matrix C will be (m x q).
matrixMultiply(A, B):
Assume dimension of A is (m x n), dimension of B is (p x q)
Begin
   if n is not same as p, then exit
   otherwise define C matrix as (m x q)
   for i in range 0 to m - 1, do
      for j in range 0 to q – 1, do
         for k in range 0 to p, do
            C[i, j] = C[i, j] + (A[i, k] * A[k, j])
         done
      done
   done
End
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
   int a[3][3] = {
      {2, 4, 1},
      {2, 3, 9},
      {3, 1, 8}
   };
   int b[3][3] = {
      {1, 2, 3},
      {3, 6, 1},
      {2, 4, 7}
   };
   if (c1 != r2) {
      cout<<"Column of first matrix should be equal to row of second matrix";
   } else {
      cout<<"The first matrix is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c1; ++j)
            cout<<a[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      cout<<"The second matrix is:"<<endl;
      for(i=0; i<r2; ++i) {
         for(j=0; j<c2; ++j)
            cout<<b[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      for(i=0; i<r1; ++i)
         for(j=0; j<c2; ++j) {
            product[i][j] = 0;
         }
      for(i=0; i<r1; ++i)
         for(j=0; j<c2; ++j)
            for(k=0; k<c1; ++k) {
               product[i][j]+=a[i][k]*b[k][j];
            }
      cout<<"Product of the two matrices is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c2; ++j)
            cout<<product[i][j]<<" ";
         cout<<endl;
      }
   }
   return 0;
}
The first matrix is:
2 4 1
2 3 9
3 1 8
The second matrix is:
1 2 3
3 6 1
2 4 7
Product of the two matrices is:
16 32 17
29 58 72
22 44 66
How to match only digits in Python using Regular Expression?

The following code matches only digits in the given string using python regular expression.
import re
m = re.search(r'\d+', '5Need47forSpeed 2')
print m
<_sre.SRE_Match object at 0x0000000004B46648>
The following code finds all digits in the given string and prints them as a list
import re
m = re.findall(r'\d', '5Need47forSpeed 2')
print m
['5', '4', '7', '2']
How to calculate the sensitivity and specificity from a confusion matrix in R?

If we have a confusion matrix then the sensitivity and specificity can be calculated using confusionMatrix function of caret package. For example, if we have a contingency table named as table then we can use the code confusionMatrix(table). This will return sensitivity and specificity as well as many other metrics.
Live Demo
> x1<-sample(letters[1:4],20,replace=TRUE)
> y1<-sample(letters[1:4],20,replace=TRUE)
> table1<-table(x1,y1)
> table1
y1
x1 a b c d
 a 0 0 1 0
 b 0 1 2 1
 c 2 2 0 2
 d 3 2 1 3
Loading caret package:
> library(caret)
Finding sensitivity and specificity of table1:
> confusionMatrix(table1)
Confusion Matrix and Statistics
y1
x1 a b c d
 a 0 0 1 0
 b 0 1 2 1
 c 2 2 0 2
 d 3 2 1 3
Overall Statistics
Accuracy : 0.2
95% CI : (0.0573, 0.4366)
No Information Rate : 0.3
P-Value [Acc > NIR] : 0.8929

Kappa : -0.0774

Mcnemar's Test P-Value : NA
Statistics by Class:
Class: a Class: b Class: c Class: d
Sensitivity 0.0000 0.20 0.0000 0.5000
Specificity 0.9333 0.80 0.6250 0.5714
Pos Pred Value 0.0000 0.25 0.0000 0.3333
Neg Pred Value 0.7368 0.75 0.7143 0.7273
Prevalence 0.2500 0.25 0.2000 0.3000
Detection Rate 0.0000 0.05 0.0000 0.1500
Detection Prevalence 0.0500 0.20 0.3000 0.4500
Balanced Accuracy 0.4667 0.50 0.3125 0.5357
Live Demo
> x2<-sample(c("India","China","Croatia","Indonesia"),2000,replace=TRUE)
> y2<-sample(c("India","China","Croatia","Indonesia"),2000,replace=TRUE)
> table2<-table(x2,y2)
> table2
y2
x2 China Croatia India Indonesia
China 143 131 138 118
Croatia 118 118 123 119
India 115 132 115 132
Indonesia 107 126 124 141
> confusionMatrix(table2)
Confusion Matrix and Statistics
y2
x2 China Croatia India Indonesia
China 143 131 138 118
Croatia 118 118 123 119
India 115 132 115 132
Indonesia 107 126 124 141
Overall Statistics
Accuracy : 0.2585
95% CI : (0.2394, 0.2783)
No Information Rate : 0.255
P-Value [Acc > NIR] : 0.3680

Kappa : 0.0116

Mcnemar's Test P-Value : 0.6665
Statistics by Class:
Class: China Class: Croatia Class: India Class: Indonesia
Sensitivity 0.2961 0.2327 0.2300 0.2765
Specificity 0.7449 0.7589 0.7473 0.7604
Pos Pred Value 0.2698 0.2469 0.2328 0.2831
Neg Pred Value 0.7687 0.7444 0.7444 0.7543
Prevalence 0.2415 0.2535 0.2500 0.2550
Detection Rate 0.0715 0.0590 0.0575 0.0705
Detection Prevalence 0.2650 0.2390 0.2470 0.2490
Balanced Accuracy 0.5205 0.4958 0.4887 0.5184
> x3<-sample(c("Male","Female"),20,replace=TRUE)
> y3<-sample(c("Male","Female"),20,replace=TRUE)
> df<-data.frame(x3,y3)
> confusionMatrix(table(df$x3,df$y3))
Confusion Matrix and Statistics
Female Male
Female 3 7
Male 6 4

Accuracy : 0.35
95% CI : (0.1539, 0.5922)
No Information Rate : 0.55
P-Value [Acc > NIR] : 0.9786

Kappa : -0.3

Mcnemar's Test P-Value : 1.0000

Sensitivity : 0.3333
Specificity : 0.3636
Pos Pred Value : 0.3000
Neg Pred Value : 0.4000
Prevalence : 0.4500
Detection Rate : 0.1500
Detection Prevalence : 0.5000
Balanced Accuracy : 0.3485

'Positive' Class : Female
Create a circular badge with Bootstrap

Use the .badge class in Bootstrap to create a circular badge with Bootstrap.
You can try to run the following code to implement .badge class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Blog Posts</h2>
         <a href = "#">Tech <span class="badge">95</span></a><br>
         <a href = "#">Entertainment <span class="badge">30</span></a><br>
         <a href = "#">Research <span class="badge">9</span></a><br>
         <a href = "#">Viral <span class="badge">20</span></a><br>
         <a href = "#">Sport <span class="badge">105</span></a>
      </div>
   </body>
</html>
What are Character Literals in C++?

A character literal is a type of literal in programming for the representation of a single character's value within the source code of a computer program.
In C++, A character literal is composed of a constant character. It is represented by the character surrounded by single quotation marks. There are two kinds of character literals −
Narrow-character literals of type char, for example 'a'
Wide-character literals of type wchar_t, for example L'a'
The character used for a character literal may be any graphic character, except for reserved characters such as newline ('\n'), backslash ('\'), single quotation mark ('), and double quotation mark ("). Reserved characters are be specified with an escape sequence. For example,
#include <iostream>
using namespace std;

int main() {
   char newline = '\n';
   char tab = '\t';
   char backspace = '\b';
   char backslash = '\\';
   char nullChar = '\0';

   cout << "Newline character: " << newline << "ending" << endl;
   cout << "Tab character: " << tab << "ending" << endl;
   cout << "Backspace character: " << backspace << "ending" << endl;
   cout << "Backslash character: " << backslash << "ending" << endl;
   cout << "Null character: " << nullChar << "ending" << endl;
}
This gives the output −
Newline character:  ending
Tab character:  ending
Backspace character:  ending
Backslash character: \ending
Null character:  ending
Python program to extract only the numbers from a list which have some specific digits

22 Oct, 2020
Given Elements List, extract numbers with specific digits. 
Input : test_list = [3456, 23, 128, 235, 982], dig_list = [2, 3, 5, 4] Output : [23, 235] Explanation : 2, 3 and 2, 3, 5 are in digit list, hence extracted elements.Input : test_list = [3456, 23, 28, 235, 982], dig_list = [2, 3, 5, 4, 8] Output : [23, 28, 235] Explanation : 2, 3; 2, 8 and 2, 3, 5 are in digit list, hence extracted elements. 
Method #1 : Using list comprehension + all()
In this, we check for each element in number against the elements from target list to be present, if all are found in list, element  is returned.
Python3
# Python3 code to demonstrate working of # Elements with specific digits# Using list comprehension + all()  # initializing listtest_list = [345, 23, 128, 235, 982]  # printing original listprint("The original list is : " + str(test_list))  # initializing digit list dig_list = [2, 3, 5, 4]  # checking for all digits using all()res = [sub for sub in test_list if all(int(ele) in dig_list for ele in str(sub))]  # printing result print("Extracted elements : " + str(res))
Output:
The original list is : [345, 23, 128, 235, 982]
Extracted elements : [345, 23, 235]
Method #2 : Using filter() + lambda + all()
In this, filtering of elements is done using filter() + lambda, all() is used to check for all the digits from other list.
Python3
# Python3 code to demonstrate working of # Elements with specific digits# Using filter() + lambda + all()  # initializing listtest_list = [345, 23, 128, 235, 982]  # printing original listprint("The original list is : " + str(test_list))  # initializing digit list dig_list = [2, 3, 5, 4]  # filter() used to filter from logic res = list(filter(lambda sub : all(int(ele) in dig_list for ele in str(sub)), test_list))  # printing result print("Extracted elements : " + str(res))
Output:
The original list is : [345, 23, 128, 235, 982]
Extracted elements : [345, 23, 235]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.