code-rag-bench/online-tutorials huggingface dataset:
List all Files with Specific Extension in R - GeeksforGeeks

17 Jun, 2021
R programming language contains a wide variety of method to work with directory and its associated sub-directories. There are various inbuilt methods in R programming language which are used to return the file names with the required extensions. It can be used to efficiently locate the presence of a file. 
Directory in use:
The list.files() method in R language is used to produce a character vector of the names of files or directories in the named directory. The regular expression is specified to match the files with the required file extension. The ‘$‘ symbol indicates the end-of-the-string, and the ‘\\‘ symbol before the ‘.’ is used to make sure that the files match the specified extension exactly. The pattern is case-sensitive, and any matches returned are strictly based on the specified characters of the pattern. 
The file names returned are sorted in alphabetical order.
Syntax:
list.files(path = “.”, pattern = NULL, full.names = FALSE, ignore.case = FALSE)
Parameters : 
path – (Default : current working directory) A character vector of full path names
pattern – regular expression to match the file names with
full.names – If TRUE, returns the absolute path of the file locations
ignore.case – Indicator of whether to ignore the case while searching for files.
Example:
R
# list all the file names of the# specified patternfnames <- list.files(pattern = "\\.pdf$")  print ("Names of files")print (fnames)
Output
[1] “Names of files” 
[1] “cubegfg.pdf”       “maytravelform.pdf”
The case of the file name can also be ignored by setting the attribute of ignore.case as the TRUE. 
Example:
R
# list all the file names of the # specified patternfnames <- list.files(pattern = "\\.pdf$",                      ignore.case = TRUE)  print ("Names of files")print (fnames)
Output
[1] “Names of files” 
[1] “cubegfg.pdf”       “maytravelform.pdf” “pdf2.pDf”
The Sys.glob() method in R is used to extract the file names with the matched pattern. This method is used to expand wild cards, termed as “globbing” in file paths. The special character “*” is used to find matches for zero or more characters, in the retrieved string. 
Syntax:
Sys.glob ( pattern)
Parameters : 
pattern – character vector of patterns for relative or absolute file paths
Example:
R
# list all the file names of # the specified patternfnames <- Sys.glob("*.png")  print ("Names of files")print (fnames)
Output
[1] “Names of files” 
[1] “Screenshot 2021-06-03 at 4.35.54 PM.png” “cubegfg.png”                            
[3] “gfg.png” 
Picked
R directory-programs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Reverse String in Python

Suppose we have an array of characters. We have to reverse the string without using any additional space. So if the string is like [‘H’, ‘E’, ‘L’, ‘L’, ‘O’], the output will be [‘O’, ‘L’, ‘L’, ‘E’, ‘H’]
To solve this, we will follow these steps −
Take two pointers to start = 0 and end = length of the string – 1
swap first and last characters
increase start by 1 and decrease-end by 1
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def reverseString(self, s):
      """
      :type s: List[str]
      :rtype: None Do not return anything, modify s in-place instead.
      """
      start = 0
      end = len(s)-1
      while start<end:
         s[start],s[end] = s[end],s[start]
         start+=1
         end-=1string_1 = ["H","E","L","L","O"]
ob1 = Solution()
ob1.reverseString(string_1)
print(string_1)
String = ["H","E","L","L","O"]

["O","L","L","E","H"]
How can we prevent the resizing of UI controls in JavaFX?

In JavaFX the javafx.scene.control package provides various classes for nodes specially designed for UI applications by instantiating these classes you can create UI elements such as button, Label, etc..
You can resize the created elements using the setPrefWidth() or, setPrefHeight() or, setprefSize() methods accordingly.
To prevent the resize of the UI controls you need to set the minimum-maximum and preferred width/height to same value as −
button.setMinWidth(80.0);
button.setPrefWidth(80.0);
button.setMaxWidth(80.0);
The following JavaFX example contains two buttons and a slider. You can resize the button (Hello) by moving the slider. Once you click the PreventResizing button, then you cannot resize the “Hello” button further.
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PreventingResize extends Application {
   public void start(Stage stage) {
      //Creating a button
      Button button = new Button("Hello");
      //Creating a slider to resize the button
      Slider slider = new Slider(40, 200, 40);
      //Setting its orientation to Horizontal
      slider.setPrefHeight(180);
      slider.setOrientation(Orientation.VERTICAL);
      slider.setShowTickLabels(true);
      slider.setShowTickMarks(true);
      slider.setMajorTickUnit(40);
      slider.setBlockIncrement(20);
      slider.valueProperty().addListener(new ChangeListener<Number>() {
         public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){
            button.setPrefSize((double)newValue, (double)newValue);
         }
      });
      //Preventing the resize
      Button prevent = new Button("Prevent Resizing");
      //Setting action to the button
      prevent.setOnAction(e -> {
         button.setMinWidth(45);
         button.setPrefWidth(45);
         button.setMaxWidth(45);
         button.setMinHeight(25);
         button.setMaxHeight(25);
         button.setPrefHeight(25);
      });
      //Creating the pane
      BorderPane pane = new BorderPane();
      pane.setCenter(button);
      pane.setRight(prevent);
      pane.setLeft(new VBox(new Label("Button Reize"), slider));
      pane.setPadding(new Insets(10, 10, 10, 10));
      //Preparing the scene
      Scene scene = new Scene(pane, 595, 250);
      stage.setTitle("Preventing Resize");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
How to detect duplicate values in primitive Java array?

To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements, in case of a match you got your duplicate element.
One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.
import java.util.Arrays;
import java.util.Scanner;

public class DetectDuplcate {
   
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
   
      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      System.out.println("indices of the duplicate elements :: ");
   
      for(int i=0; i<myArray.length; i++) {
         for (int j=i+1; j<myArray.length; j++) {
            if(myArray[i] == myArray[j]) {
               System.out.println(j);
            }
         }
      }
   }
}
Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
87
52
87
63
41
63
The array created is :: [87, 52, 87, 63, 41, 63]
indices of the duplicate elements ::
2
5
Solution 2: In addition to this we have a more reliable solution:
The interface set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class DetectDuplcateUsingSet {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      System.out.println("indices of duplicate elements in the array are elements::");
      Set set = new HashSet();
 
      for(int i=0; i<myArray.length; i++) {
         if(!set.add(myArray[i])) {
            System.out.println(i);
         }
      }
   }
}
Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
78
56
23
78
45
The array created is :: [78, 56, 23, 78, 45]
indices of duplicate elements in the array are elements::
3
Circular (polar) histogram in Python

To plot circular (polar) histogram in Python, we can take the following steps−
Create data points for theta, radii and width using numpy.
Add a subplot to the current figure, where projection='polar' and nrows=1, ncols=1 and
index=1.
. Make a bar plot using bar() method, with theta, radii and width data points
Iterate radii and bars after zipping them together and set the face color of the bar and the alpha
value. Lesser the alpha value, greater the transparency.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.rainbow(r / 10.0))
bar.set_alpha(0.5)
plt.show()
Demonstrate constructors in a Multilevel Hierarchy in Java

Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A.
A program that demonstrates constructors in a Multilevel Hierarchy in Java is given as follows:
 Live Demo
class A {
   A() {
      System.out.println("This is constructor of class A");
   }
}
class B extends A {
   B() {
      System.out.println("This is constructor of class B");
   }
}
class C extends B {
   C() {
      System.out.println("This is constructor of class C");
   }
}
public class Demo {
   public static void main(String args[]) {
      C obj = new C();
   }
}
This is constructor of class A
This is constructor of class B
This is constructor of class C
Now let us understand the above program.
The class A contains the constructor A(). The class B uses the extends keyword to inherit class A. It also contains the constructor B(). The class C uses the extends keyword to inherit class B. It contains the constructor C(). A code snippet which demonstrates this is as follows:
class A {
   A() {
      System.out.println("This is constructor of class A");
   }
}
class B extends A {
   B() {
      System.out.println("This is constructor of class B");
   }
}
class C extends B {
   C() {
      System.out.println("This is constructor of class C");
   }
}
In the main() method in class Demo, an object obj of class C is created. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String args[]) {
      C obj = new C();
   }
}
How to create a table from view in MySQL?

To create a table from the view below is the syntax −
create table yourTableName select *from yourViewName;
Let us first create a table −
mysql> create table DemoTable830(Name varchar(100));
Query OK, 0 rows affected (0.91 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable830 values('Chris');
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable830 values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable830 values('David');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable830 values('Mike');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable830;
This will produce the following output −
+--------+
| Name   |
+--------+
| Chris  |
| Robert |
| David  |
| Mike   |
+--------+
4 rows in set (0.00 sec)
Following is the query to create a view −
mysql> create view table_view AS select *from DemoTable830;
Query OK, 0 rows affected (0.39 sec)
Now, we will create a table from view. Following is the query −
mysql> create table DemoTable831 select *from table_view;
Query OK, 4 rows affected (1.64 sec)
Records: 4 Duplicates: 0 Warnings: 0
Let us check the records of the table which has been created from the view −
mysql> select *from DemoTable831;
This will produce the following output −
+--------+
| Name   |
+--------+
| Chris  |
| Robert |
| David  |
| Mike   |
+--------+
4 rows in set (0.00 sec)
What is the difference between a Java method and a native method?

A native method is the one whose method implementation is done in other languages like c++ and Java. These programs are linked to Java using JNI or JNA interfaces.
The difference between normal method and native method is That the native method declaration contains native keyword and, the implementation of the method will be other programming language.
public class Tester {
   public native int getValue(int i);
   
   public static void main(String[] args) {
      System.loadLibrary("Tester");
      System.out.println(new Tester().getValue(2));
   }
}
#include <jni.h>
#include "Tester.h"

JNIEXPORT jint JNICALL Java_Tester_getValue(
JNIEnv *env, jobject obj, jint i) {
   return i * i;
}
javac Tester.java
javah -jni Tester
gcc -shared -fpic -o libTester.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Tester.c
java -Djava.library.path=. Tester
4
Styling First-Letters with CSS ::first-letter

CSS can help us style the first letter of an element using the ::first-letter pseudo-element. Note that punctuation marks, digraphs and content property can change the first-letter.
The following examples illustrate CSS ::first-letter pseudo-element.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
   text-align: center;
}
::first-letter {
   font-size: 3em;
   color: sienna;
   box-shadow: -10px 0 10px green;
   background-color: gainsboro;
}
</style>
</head>
<body>
<h2>Proin ut diam eros</h2>
<p>Donec rutrum a erat vitae interdum. </p>
<p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p>
</body>
</html>
This will produce the following result −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
   text-align: center;
}
body > * {
   background-color: slategrey;
}
::first-letter {
   font-size: 1.6em;
   color: darkviolet;
   background-color: silver;
   text-shadow: -15px 8px palevioletred;
}
</style>
</head>
<body>
<h2>Proin ut diam eros
<p>Donec rutrum a erat vitae interdum. </p>
<p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p>
</body>
</html>
This will produce the following result −
How to get the datatype of MySQL table columns?

You can get the MySQL table columns data type with the help of “information_schema.columns”.
The syntax is as follows −
SELECT DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where
table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’.
To understand the above syntax, let us first create a table −
mysql> create table DataTypeDemo
−> (
   −> Id int,
   −> Address varchar(200),
   −> Money decimal(10,4)
−> );
Query OK, 0 rows affected (0.60 sec)
Apply the above syntax to get the MySQL columns data type. The query is as follows −
mysql> select data_type from information_schema.columns where table_schema = 'business' and able_name = 'DataTypeDemo';
The following is the output −
+-----------+
| DATA_TYPE |
+-----------+
| int       |
| varchar   |
| decimal   |
+-----------+
3 rows in set (0.00 sec)
If you want, include the column name as well in the output before the datatype. The query is as follows −
mysql> select column_name,data_type from information_schema.columns where table_schema = 'business' and table_name = 'DataTypeDemo';
The following output displays the column name corresponding to the data type −
+-------------+-----------+
| COLUMN_NAME | DATA_TYPE |
+-------------+-----------+
| Id          | int       |
| Address     | varchar   |
| Money       | decimal   |
+-------------+-----------+
3 rows in set (0.00 sec)
How to change text font in HTML?

To change the text font in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family, font-size, font-style, etc.
HTML5 do not support the <font> tag, so the CSS style is used to change font. The <font> tag deprecated in HTML5.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to change the font in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Font</title>
   </head>

   <body>
      <h1>Our Products</h1>
      <p style = "font-family:georgia,garamond,serif;font-size:16px;font-style:italic;">
         This is demo text
      </p>
   </body>

</html>
multimap value_comp() function in C++ STL - GeeksforGeeks

22 Oct, 2018
The multimap::value_comp() method returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. Here the 1st object compares the object of type std::multimap::type. The arguments taken by this function object are of member type type. It is defined in multimap as an alias of pair.
Syntax:
multimap::compared_value value_comp() const;
Here compared_value is a nested class type
Parameters: It does not accepts any parameter.
Return Value: This method returns the comparison object which is an object of the member type multimap::compared_value, which is a nested class that uses the internal comparison object to generate the appropriate comparison functional class.
Below program illustrate the multimap value_comp() function:
// C++ program to show// the use of multimap::value_comp  #include <iostream>#include <map>using namespace std;  int main(){    multimap<char, int> m;      // making of pair    m.insert(make_pair('a', 10));    m.insert(make_pair('b', 20));    m.insert(make_pair('c', 30));    m.insert(make_pair('d', 40));      pair<char, int> p = *m.rbegin();    // last element      multimap<char, int>::iterator i = m.begin();      do {          cout << (*i).first             << " = " << (*i).second             << '\n';      } while (m.value_comp()(*i++, p));      return 0;}
a = 10
b = 20
c = 30
d = 40

CPP-Functions
cpp-multimap
cpp-multimap-functions
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
std::string class in C++
new and delete operators in C++ for dynamic memory
Thread Pools in C#

Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.
Let us see how to create a thread pool.
Firstly, use the following namespace −
using System.Threading;
Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem −
ThreadPool.QueueUserWorkItem(new WaitCallback(Run));

Iterate this in a loop and compare it with a normal Thread object.
ArrayList of ArrayList in Java - GeeksforGeeks

11 Dec, 2018
We have discussed that an array of ArrayList is not possible without warning. A better idea is to use ArrayList of ArrayList.
// Java code to demonstrate the concept of// array of ArrayList  import java.util.*;public class Arraylist {    public static void main(String[] args)    {        int n = 3;          // Here aList is an ArrayList of ArrayLists        ArrayList<ArrayList<Integer> > aList =                   new ArrayList<ArrayList<Integer> >(n);          // Create n lists one by one and append to the         // master list (ArrayList of ArrayList)        ArrayList<Integer> a1 = new ArrayList<Integer>();        a1.add(1);        a1.add(2);        aList.add(a1);          ArrayList<Integer> a2 = new ArrayList<Integer>();        a2.add(5);        aList.add(a2);          ArrayList<Integer> a3 = new ArrayList<Integer>();        a3.add(10);        a3.add(20);        a3.add(30);        aList.add(a3);          for (int i = 0; i < aList.size(); i++) {            for (int j = 0; j < aList.get(i).size(); j++) {                System.out.print(aList.get(i).get(j) + " ");            }            System.out.println();        }    }}
1 2 
5 
10 20 30

Java - util package
Java-ArrayList
Java-Arrays
Java-Collections
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Overriding in Java
Collections in Java
Multithreading in Java
Set in Java
Tryit Editor v3.7

HTML Input types
Tryit: input number with restrictions
Externalizable Interface in Java

Externalization is used whenever we need to customize serialization mechanism. If a class implements an Externalizable interface then, object serialization will be done using writeExternal() method. Whereas at receiver's end when an Externalizable object is a reconstructed instance will be created using no argument constructor and then the readExternal() method is called.
If a class implements only Serializable interface object serialization will be done using ObjectoutputStream. At the receiver's end, the serializable object is reconstructed using ObjectInputStream.
Below example showcases usage of Externalizable interface.
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Tester {
   public static void main(String[] args) {

      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.age = 30;
      try (
         FileOutputStream fileOut = new FileOutputStream("test.txt");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
      ) {
         out.writeObject(e);
      }catch (IOException i) {
         System.out.println(i.getMessage());
      }
      try (
         FileInputStream fileIn = new FileInputStream("test.txt");
         ObjectInputStream in = new ObjectInputStream(fileIn);
      ) {
         e = (Employee)in.readObject();
         System.out.println(e.name);
         System.out.println(e.age);
      } catch (IOException i) {
         System.out.println(i.getMessage());
      } catch (ClassNotFoundException e1) {
         System.out.println(e1.getMessage());
      }
   }
}

class Employee implements Externalizable {
   public Employee(){}
   String name;
   int age;
   public void writeExternal(ObjectOutput out) throws IOException {
      out.writeObject(name);
      out.writeInt(age);
   }
   public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
      name = (String)in.readObject();
      age = in.readInt();
   }
}
This will produce the following result −
Reyan Ali
30
AVG() Function in MySQL - GeeksforGeeks

21 Jan, 2021
AVG() function :
This function in MySQL is used to return the average value of the specified expression.
Features :
This function is used to find the average value of the specified expression.
This function comes under Numeric Functions.
This function accepts only one parameter namely expression.
This function ignores NULL values.
Syntax :
AVG(expression)
Parameter :
This method accepts only one parameter as follows.
expression –The specified numeric value may be either a stated field or a stated formula.
Returns :
It returns the average value of the specified expression.
Example-1 :
Using AVG() function and getting the output.
Creating table –
CREATE TABLE item13
(  
user_id int,    
product01 VARCHAR(4),
product02 VARCHAR(10),
price int  
);
Inserting data –
INSERT item13(product01, price)  
VALUES ('rice', 500);

INSERT item13(product02, price)  
VALUES ('grains', 700);
Reading Data –
SELECT AVG(price) FROM item13;
Output :
600
Here, the average of the first product’s price and the second product’s price is returned.
Example-2 :
Using AVG() function and getting the average of float values.
Creating table –
CREATE TABLE floats
(  
user_id int,
float_val float
);
Inserting Data –
INSERT floats(float_val)  
VALUES (3.5);

INSERT floats(float_val)  
VALUES (2.5);
Reading Data –
SELECT AVG(float_val) FROM floats;
Output :
3
Example-3 :
Using AVG() function and getting the output where MRP is greater than the average MRP of the products.
Creating table –
CREATE TABLE package01
(  
user_id int NOT NULL AUTO_INCREMENT,  
item VARCHAR(10),
mrp int, 
PRIMARY KEY(user_id)  
);
Inserting Data –
INSERT package01(item, mrp)  
VALUES ('book1', 250);

INSERT package01(item, mrp)  
VALUES ('book2', 350);

INSERT package01(item, mrp)  
VALUES ('book3', 400);
Reading Data –
SELECT * FROM package01
WHERE mrp > (SELECT AVG(mrp) FROM package01);
Output :
Example-4 :
Using AVG() function and getting the average of the (MRP-sales price).
Creating table –
CREATE TABLE package011
(  
user_id int NOT NULL AUTO_INCREMENT,  
item VARCHAR(10) NOT NULL,
mrp int NOT NULL,
sp int NOT NULL,
PRIMARY KEY(user_id)  
);
Inserting Data –
INSERT package011(item, mrp, sp)  
VALUES ('book1', 250, 240);

INSERT package011(item, mrp, sp)  
VALUES ('book2', 350, 320);

INSERT package011(item, mrp, sp)  
VALUES ('book3', 400, 350);
Reading Data –
SELECT AVG(mrp-sp) FROM package011;
Output :
30
Application :
This function is used to find the average of the expression specified.
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | DROP, TRUNCATE
Composite Key in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
SQL | ALTER (ADD, DROP, MODIFY)
Get all array elements with true values in Julia | Array findall() Method - GeeksforGeeks

23 Mar, 2020
The findall() is an inbuilt function in julia which is used to return a vector of indices or keys of the all true values from the specified array A. If such true values are not present in the array, return an empty array. Here values of index or key start from 1 i.e, for index of 1st element is 1, index of 2nd element is 2 and so on.
Syntax:findall(A)orfindall(f::Function, A)
Parameters:
A: Specified array
Function: Determines whether something is true or false based on the specified arguments
Returns: It returns a vector of indices or keys of the all true values from the specified array A. If such true values are not present in the array, return an empty array.
Example 1:
# Julia program to illustrate # the use of Array findall() method   # Finding index of all true values from # the 1D array AA = [false, true, true, false]println(findall(A))   # Finding index of all true values from # the 2D array B of size 2 * 2B = [false false; true false]println(findall(B))   # Finding index of all true values from # the 3D array C of size 2 * 2*2C = cat([false false; true false],         [false true; true false],        [true false; true true], dims = 3)println(findall(C))
Output:
Example 2:
# Julia program to illustrate # the use of Array findall() method   # Finding index of all even values from # the 1D array AA = [1, 2, 5, 7]println(findall(iseven, A))   # Finding index of all odd values from # the 2D array B of size 2 * 2B = [3 5; 6 7]println(findall(isodd, B))   # Finding index of all odd values from # the 3D array C of size 2 * 2*2C = cat([6 2; 6 4], [5 6; 2 8],         [2 10; 11 1], dims = 3)println(findall(isodd, C))
Output:
Julia Array-functions
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Comments in Julia
while loop in Julia
Formatting of Strings in Julia
Tuples in Julia
Searching in Array for a given element in Julia
MySQL search if more than one string contains special characters?


To search if strings contain special characters, you can use REGEXP. Following is the syntax −
select * from yourTableName
where yourColumnName REGEXP '[^a-zA-Z0-9]';
Let us first create a table −
mysql> create table specialCharactersDemo
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)
Insert records in the table using insert command. Following is the query −
mysql> insert into specialCharactersDemo values('STU_1234');
Query OK, 1 row affected (0.15 sec)
mysql> insert into specialCharactersDemo values('STU567');
Query OK, 1 row affected (0.14 sec)
mysql> insert into specialCharactersDemo values('STU#1234');
Query OK, 1 row affected (0.13 sec)
mysql> insert into specialCharactersDemo values('STU897$');
Query OK, 1 row affected (0.18 sec)
mysql> insert into specialCharactersDemo values('STU999');
Query OK, 1 row affected (0.43 sec)
mysql> insert into specialCharactersDemo values('STU1010');
Query OK, 1 row affected (0.14 sec
Following is the query to display all records from the table using select statement −
mysql> select *from specialCharactersDemo;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| STU_1234  |
| STU567    |
| STU#1234  |
| STU897$   |
| STU999    |
| STU1010   |
+-----------+
6 rows in set (0.00 sec)
Here is the query to search if a string contains special characters −
mysql> select *from specialCharactersDemo
   -> where StudentId REGEXP '[^a-zA-Z0-9]';
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| STU_1234  |
| STU#1234  |
| STU897$   |
+-----------+
3 rows in set (0.02 sec)
You can use another syntax for the above result. Following is the query −
mysql> select *from specialCharactersDemo
   -> where StudentId REGEXP'[^[:alnum:]]';
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| STU_1234  |
| STU#1234  |
| STU897$   |
+-----------+
3 rows in set (0.05 sec)
finally keyword in Python - GeeksforGeeks

29 Apr, 2019
Prerequisites: Exception Handling, try and except in Python
In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on.So, in order to handle these situations, Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception.
Syntax:
try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

finally:
      # Some code .....(always executed)      


Important Points –
finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.
finally block is used to deallocate the system resources.
One can use finally just after try without using except block, but no exception is handled in that case.
Example #1:
# Python program to demonstrate finally  # No exception Exception raised in try blocktry:    k = 5//0 # raises divide by zero exception.    print(k)  # handles zerodivision exception    except ZeroDivisionError:       print("Can't divide by zero")      finally:    # this block is always executed     # regardless of exception generation.    print('This is always executed') 
Output:
Can't divide by zero
This is always executed
 Example #2:
# Python program to demonstrate finally  try:    k = 5//1 # No exception raised    print(k)  # intends to handle zerodivision exception    except ZeroDivisionError:       print("Can't divide by zero")      finally:    # this block is always executed     # regardless of exception generation.    print('This is always executed') 
Output:
5
This is always executed

 Example #3:
# Python program to demonstrate finally  # Exception is not handledtry:    k = 5//0 # exception raised    print(k)      finally:    # this block is always executed     # regardless of exception generation.    print('This is always executed') 
Output:
This is always executed

Runtime Error –
Unhandled Exception 
    k=5//0 #No exception raised
ZeroDivisionError: integer division or modulo by zero
Explanation:In above code, the exception is generated integer division or modulo by zero, which was not handled. The exception was re-raised after execution of finally block. This shows that finally block is executed regardless of exception is handled or not.
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
sum() function in Python
*args and **kwargs in Python
Getting an HTML H1 value to JavaScript variable?

To get the value of H1 to JavaScript variable, you can use −
document.getElementById().innerHTML.
Let’s say the following is our H1 heading −
<h1 id="demo"> This is the demo program of JavaScript ........</h1>
Now, let’s get the H1 value using the below code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<h1 id="demo"> This is the demo program of JavaScript ........</h1>
<script>
   var data=document.getElementById('demo').innerHTML;
   console.log("The data is="+data);
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
What is the difference between $ErrorActionPreference and $ErrorAction cmdlet in PowerShell ?

As we know $ErrorActionPreference and $ErrorAction both have the same functionality and both are used to handle terminating errors by converting Non-Terminating errors to Terminating errors. But when both the variables are used, we need to know which takes precedence.
$ErrorActionPreference variable is used at the start of the script while the $erroraction variable is a common parameter and used with the cmdlet. In some cases, we might need the script to be terminated as soon as an error occurs but inside the script, we have some cmdlets which need to be ignored or continued if the error occurs. In that situation, we -ErrorAction is important and it takes precedence.
$ErrorActionPreference = "Stop"
try{
   Get-Service -Name ABC
   Get-Process powershell
   Get-Process chromesds
   Get-Service Spooler
}
catch{
   $_.Exception.Message
}
Cannot find any service with service name 'ABC'.
In the above example, the script is terminated because the ABC service name doesn’t exist and because of it, the next commands can’t execute as the $ErrorActionPreference value is set to Stop. Once we add the -ErrorAction in the Get-Service command, it will take the precedence.
$ErrorActionPreference = "Stop"
try{
   Get-Service -Name ABC -ErrorAction Continue
   Get-Process powershell
   Get-Process chromesds
   Get-Service Spooler
}
catch{
   $_.Exception.Message
}
Line |
   4 |       Get-Service -Name ABC -ErrorAction Continue
     |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find any service with service name 'ABC'.
NPM(K)    PM(M)    WS(M)    CPU(s)    Id    SI    ProcessName
------    -----    -----    ------    --    --    -----------
43       234.39    11.33    49.17    7668    1    powershell
Cannot find a process with the name "chromesds". Verify the process name and call
the cmdlet again.
Once we add the -ErrorAction parameter with Continue value, execution moves to the next command as shown in the above output and stops when it can’t find process name “Chromesds” and can’t execute next command as -ErrorAction is not mentioned in that command.
numpy.polyder() in Python - GeeksforGeeks

04 Dec, 2020
The numpy.polyder() method evaluates the derivative of a polynomial with specified order.
Syntax :numpy.polyder(p, m)Parameters :p : [array_like or poly1D]the polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.For example : poly1d(3, 2, 6) = 3x2 + 2x + 6
m : [int, optional] Order of differentiation.
Return: Derivative of polynomial.
Code : Python code explaining polyder()
# Python code explaining # numpy.polyder()    # importing librariesimport numpy as npimport pandas as pd  # Constructing polynomial p1 = np.poly1d([1, 2]) p2 = np.poly1d([4, 9, 5, 4])     print ("P1 : ", p1) print ("\n p2 : \n", p2) 
   # Solve for x = 2 print ("\n\np1 at x = 2 : ", p1(2)) print ("p2 at x = 2 : ", p2(2)) 
a = np.polyder(p1, 1)b = np.polyder(p2, 1)print ("\n\nUsing polyder")print ("p1 derivative of order = 1 : \n", a) print ("p2 derivative of order = 1 : \n", b) 
a = np.polyder(p1, 2)b = np.polyder(p2, 2)print ("\n\nUsing polyder")print ("p1 derivative of order = 2 : ", a) print ("p2 derivative of order = 2 : ", b)
Python numpy-polynomials
Python-numpy
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Pandas Timestamp.timetuple - GeeksforGeeks

17 Jan, 2019
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 Timestamp.timetuple() function return a time tuple for the given Timestamp object. The returned tuple contains values ranging from year, month to hours and seconds. The time tuple is compatible with time.localtime().
Syntax :Timestamp.timetuple()
Parameters : None
Return : time tuple
Example #1: Use Timestamp.timetuple() function to return a time tuple for the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                   hour = 10, second = 49, tz = 'US/Central')   # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.timetuple() function to return a time tuple.
# return time tuplets.timetuple()
Output :
As we can see in the output, the Timestamp.timetuple() function has returned a tuple for the given Timestamp object which contains values like year, month, day etc.
Example #2: Use Timestamp.timetuple() function to return a time tuple for the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                   hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.timetuple() function to return a time tuple.
# return time tuplets.timetuple()
Output :
As we can see in the output, the Timestamp.timetuple() function has returned a tuple for the given Timestamp object which contains values like year, month, day etc.
Python Pandas-Timestamp
Python-pandas
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 | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
numpy.conj() in Python - GeeksforGeeks

04 Dec, 2020
The numpy.conj() function helps the user to conjugate any complex number.
The conjugate of a complex number is obtained by changing the sign of its imaginary part. If the complex number is 2+5j then its conjugate is 2-5j.
Syntax:numpy.conj(x[, out] = ufunc ‘conjugate’)Parameters :x [array_like]: Input value.out [ndarray, optional] : Output array with same dimensions as Input array, placed with result.
Return :x : ndarray. The complex conjugate of x, with same dtype as y.
Code #1 :
# Python3 code demonstrate conj() function  #importing numpyimport numpy as np  in_complx1 = 2+4jout_complx1 = np.conj(in_complx1)print ("Output conjugated complex number of  2+4j : ", out_complx1)  in_complx2 =5-8jout_complx2 = np.conj(in_complx2)print ("Output conjugated complex number of 5-8j: ", out_complx2)
Output :
Output conjugated complex number of  2+4j :  (2-4j)
Output conjugated complex number of 5-8j:  (5+8j)

 Code #2 :
# Python3 code demonstrate conj() function  # importing numpyimport numpy as np  in_array = np.eye(2) + 3j * np.eye(2)print ("Input array : ", in_array)  out_array = np.conjugate(in_array)print ("Output conjugated array : ", out_array)
Output :
Input array :  [[ 1.+3.j  0.+0.j]
 [ 0.+0.j  1.+3.j]]
Output conjugated array :  [[ 1.-3.j  0.-0.j]
 [ 0.-0.j  1.-3.j]]

Python numpy-Mathematical Function
Python-numpy
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
Python - Itertools.tee() - GeeksforGeeks

11 Jun, 2020
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse().
Note: For more information, refer to Python Itertools
This iterator splits the container into a number of iterators mentioned in the argument.
Syntax:
tee(iterator, count)
Parameter: This method contains two arguments, the first argument is iterator and the second argument is a integer.Return Value: This method returns the number of iterators mentioned in the argument.
Example 1:
# Python code to demonstrate the working of tee()     # importing "itertools" for iterator operations import itertools     # initializing list  li = [2, 4, 6, 7, 8, 10, 20]     # storing list in iterator iti = iter(li)     # using tee() to make a list of iterators # makes list of 3 iterators having same values. it = itertools.tee(iti, 3)     # printing the values of iterators print ("The iterators are : ") for i in range (0, 3):     print (list(it[i])) 
Output:
The iterators are : 
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]

Example 2:
# Python code to demonstrate the working of tee()     # importing "itertools" for iterator operations import itertools        # using tee() to make a list of iterators   iterator1, iterator2 = itertools.tee([1, 2, 3, 4, 5, 6, 7], 2)    # printing the values of iterators print (list(iterator1)) print (list(iterator1)) print (list(iterator2)) 
Output:
[1, 2, 3, 4, 5, 6, 7]
[]
[1, 2, 3, 4, 5, 6, 7]

Example 3:
# Python code to demonstrate the working of tee()     # importing "itertools" for iterator operations import itertools        # using tee() to make a list of iterators   for i in itertools.tee(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 4):    # printing the values of iterators     print (list(i))
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']

Picked
Python-itertools
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()