code-rag-bench/online-tutorials huggingface dataset:
Minimum and Maximum Priority Threads in Java

The thread priority determines when the processor is provided to the thread as well as other resources. It can be changed using the method setPriority() of class Thread.
There are three static variables for thread priority in Java i.e. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY. The values of these variables are 1, 10 and 5 respectively.
A program that demonstrates this is given as follows:
 Live Demo
public class ThreadDemo extends Thread {
   public void run() {
      System.out.println("Running...");
   }
   public static void main(String[] args) {
      ThreadDemo thread1 = new ThreadDemo();
      ThreadDemo thread2 = new ThreadDemo();
      System.out.println("Default thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Default thread priority of Thread 2: " + thread2.getPriority());
      thread1.setPriority(MAX_PRIORITY);
      thread2.setPriority(MIN_PRIORITY);
      System.out.println("\nThe maximum thread priority of Thread 1 is: " + thread1.getPriority());
      System.out.println("The minimum thread priority of Thread 2 is: " + thread2.getPriority());
      System.out.println("\n" + Thread.currentThread().getName());
      System.out.println("Default thread priority of Main Thread: " + Thread.currentThread().getPriority());
      Thread.currentThread().setPriority(MAX_PRIORITY);
      System.out.println("The maximum thread priority of Main Thread is: " + Thread.currentThread().getPriority());
   }
}
Default thread priority of Thread 1: 5
Default thread priority of Thread 2: 5
The maximum thread priority of Thread 1 is: 10
The minimum thread priority of Thread 2 is: 1
main
Default thread priority of Main Thread: 5
The maximum thread priority of Main Thread is: 10
Objective-C Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
Objective-C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
Objective-C programming language provides following types of decision making statements. Click the following links to check their details −
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
You can use one if or else if statement inside another if or else if statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
You can use one switch statement inside another switch statement(s).
We have covered conditional operator ? : in previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
How to set the left margin of an element with JavaScript?

Use the marginLeft property in JavaScript, to set the left margin. You can try to run the following code to set the left margin of an element with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button type="button" onclick="display()">Add left margin</button>
      <p id="myID">This is demo text.</p>
      <script>
         function display() {
            document.getElementById("myID").style.marginLeft = "80px";
         }
      </script>
   </body>
</html>
TensorFlow - Linear Regression

In this chapter, we will focus on the basic example of linear regression implementation using TensorFlow. Logistic regression or linear regression is a supervised machine learning approach for the classification of order discrete categories. Our goal in this chapter is to build a model by which a user can predict the relationship between predictor variables and one or more independent variables.
The relationship between these two variables is cons −idered linear. If y is the dependent variable and x is considered as the independent variable, then the linear regression relationship of two variables will look like the following equation −
Y = Ax+b

We will design an algorithm for linear regression. This will allow us to understand the following two important concepts −
Cost Function
Gradient descent algorithms
The schematic representation of linear regression is mentioned below −
The graphical view of the equation of linear regression is mentioned below −
We will now learn about the steps that help in designing an algorithm for linear regression.
It is important to import the necessary modules for plotting the linear regression module. We start importing the Python library NumPy and Matplotlib.
import numpy as np 
import matplotlib.pyplot as plt

Define the number of coefficients necessary for logistic regression.
number_of_points = 500 
x_point = [] 
y_point = [] 
a = 0.22 
b = 0.78

Iterate the variables for generating 300 random points around the regression equation −
Y = 0.22x+0.78
for i in range(number_of_points): 
   x = np.random.normal(0.0,0.5) 
   y = a*x + b +np.random.normal(0.0,0.1) x_point.append([x]) 
   y_point.append([y])

View the generated points using Matplotlib.
fplt.plot(x_point,y_point, 'o', label = 'Input Data') plt.legend() plt.show()

The complete code for logistic regression is as follows −
import numpy as np 
import matplotlib.pyplot as plt 

number_of_points = 500 
x_point = [] 
y_point = [] 
a = 0.22 
b = 0.78 

for i in range(number_of_points): 
   x = np.random.normal(0.0,0.5) 
   y = a*x + b +np.random.normal(0.0,0.1) x_point.append([x]) 
   y_point.append([y]) 
   
plt.plot(x_point,y_point, 'o', label = 'Input Data') plt.legend() 
plt.show()
The number of points which is taken as input is considered as input data.

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    29 Lectures 
     3.5 hours 

 Mohammad Nauman

    82 Lectures 
     4 hours 

 Anis Koubaa
 Print
 Add Notes
 Bookmark this page
How can we show/hide the echo character of a JPasswordField in Java?


A JPasswordField is a subclass of JTextField and each character entered in a JPasswordField can be replaced by an echo character. This allows confidential input for passwords. By default, the echo character is the asterisk(*). The important methods of JPasswordField are get password(), getText(), getAccessibleContext() and etc. By default, JPasswordField can show the echo characters. We can hide the echo characters and show the original text to the use by click on JCheckBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public final class ShowJPasswordTest extends JPanel {
   private JPasswordField pf1;
   private JCheckBox jcb;
   private JPanel panel;
   public ShowJPasswordTest() {
      pf1 = makePasswordField();
      jcb = new JCheckBox("Show Passwords");
      jcb.addActionListener(ae -> {
         JCheckBox c = (JCheckBox) ae.getSource();
         pf1.setEchoChar(c.isSelected() ? '\u0000' : (Character)          UIManager.get("PasswordField.echoChar"));
      });
      panel = new JPanel(new BorderLayout());
      panel.add(pf1);
      panel.add(jcb, BorderLayout.SOUTH);
      add(makeTitledPanel("Show/Hide Password", panel));
      setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
   }
   private static JPasswordField makePasswordField() {
      JPasswordField pf = new JPasswordField(20);
      pf.setText("tutorialspoint");
      pf.setAlignmentX(Component.RIGHT_ALIGNMENT);
      return pf;
   }
   private static Component makeTitledPanel(String title, Component cmp) {
      JPanel p = new JPanel(new GridBagLayout());
      p.setBorder(BorderFactory.createTitledBorder(title));
      GridBagConstraints c = new GridBagConstraints();
      c.weightx = 1d;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.insets = new Insets(5, 5, 5, 5);
      p.add(cmp, c);
      return p;
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("Show/HidePasswordField Test");
      frame.getContentPane().add(new ShowJPasswordTest());
      frame.setSize(375, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
enum PasswordField {
   SHOW, HIDE;
}
How to Set environment variables using PowerShell?

To set the environmental variable using PowerShell you need to use the assignment operator (=). If the
variable already exists then you can use the += operator to append the value, otherwise, a new environment variable will be created.
For example, there is no AZURE_RESOURCE_GROUP environment variable that exists in the system. We can create it as below.
$env:AZURE_RESOURCE_GROUP = 'MyTestResourceGroup'
Now when you check the environment variables in the system, you will get the above variable name.
PS C:\Windows\system32> dir env:
Name                            Value
----                            -----
ALLUSERSPROFILE                 C:\ProgramData
APPDATA                         C:\Users\delta\AppData\Roaming
AZURE_RESOURCE_GROUP            MyTestResourceGroup
CommonProgramFiles              C:\Program Files\Common Files
CommonProgramFiles(x86)         C:\Program Files (x86)\Common Files
CommonProgramW6432              C:\Program Files\Common Files
COMPUTERNAME                    TEST1-WIN2K12
ComSpec                         C:\Windows\system32\cmd.exe
If you have another resource group and if you need to add to the same environment variable then as
mentioned earlier use += operator and separate value with a semicolon (;).
$env:AZURE_RESOURCE_GROUP = ';MyTestResourceGroup2'
PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP
MyTestResourceGroup;MyTestResourceGroup2
If the value(s) already exists for an environment variable then you can also change the value by simply assigning the value to the variable. For example,
PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP = 'NewResourceGroup'
PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP
NewResourceGroup
The above method we have seen is to set the environment variable temporarily, once you close the
PowerShell console the value gets destroyed. To add or set the environment variable persistently you
need to use the .NET method.
To set the environment persistently so they should remain even when close the session, PowerShell uses [System.Environment] class with the SetEnvironmentVariable method for the environment variable to set it persistently.
[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group')
PS C:\> $env:ResourceGroup
AZ_Resource_Group
How to close a Python figure by keyboard input using Matplotlib?

To close a Python figure by a keyboard input, we can use plt.pause() method, an input, and close() method.
Set the figure size and adjust the padding between and around the subplots.
Create random t and y data points using numpy.
Create a new figure or activate an existing figure using figure() method.
Plot t and y data points using plot() method.
Set the title of the plot.
Redraw the current figure using draw() method.
Run a true loop to pause the current figure.
Take input from the user to go to the next statement.
Use close() method to close the figure.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
t = np.arange(0.0, 2.0, 0.01)
y = np.exp(-t)
fig = plt.figure()
plt.plot(t, y, lw=5, color='red')
plt.title("$y=e^{-t}$")
plt.draw()
plt.pause(1)
input("<Hit Enter>")
plt.close(fig)
Format date with DATE_FORMAT() and STR_TO_DATE() in MySQL

Let us first create a table −
mysql> create table DemoTable
(
   DueDate varchar(100)
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('August 04,2019');
Query OK, 1 row affected (0.25 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------+
| DueDate        |
+----------------+
| August 04,2019 |
+----------------+
1 row in set (0.00 sec)
Following is the query to format date −
mysql> set @stringToDate=(select date_format(str_to_date(DueDate, '%M %d,%Y'), '%Y-%m-%d') from DemoTable);
Query OK, 0 rows affected (0.02 sec)
Let us use a select statement to display the date −
mysql> select @stringToDate;
This will produce the following output −
+---------------+
| @stringToDate |
+---------------+
| 2019-08-04    |
+---------------+
1 row in set (0.00 sec)
Pattern quote() method in Java with examples

The java.util.regex package of java provides various classes to find particular patterns in character sequences.
The pattern class of this package is a compiled representation of a regular expression. The quote() method of this class accepts a string value and returns a pattern string that would match the given string i.e. to the given string additional metacharacters and escape sequences are added. Anyway, the meaning of the given string is not affected.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      System.out.print("Enter the string to be searched: ");
      String regex = Pattern.quote(sc.nextLine());
      System.out.println("pattern string: "+regex);
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //retrieving the Matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}
Enter input string
This is an example program demonstrating the quote() method
Enter the string to be searched: the
pattern string: \Qthe\E
Match found
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      String regex = "[aeiou]";
      String input = "Hello how are you welcome to Tutorialspoint";
      //Compiling the regular expression
      Pattern.compile(regex);
      regex = Pattern.quote(regex);
      System.out.println("pattern string: "+regex);
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("The input string contains vowels");
      } else {
         System.out.println("The input string does not contain vowels");
      }
   }
}
pattern string: \Q[aeiou]\E
The input string contains vowels
Data Structure & Algorithms - Tower of Hanoi

Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings is as depicted −
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over the larger one. There are other variations of the puzzle where the number of disks increase, but the tower count remains the same.
The mission is to move all the disks to some another tower without violating the sequence of arrangement. A few rules to be followed for Tower of Hanoi are −
Only one disk can be moved among the towers at any given time.
Only the "top" disk can be removed.
No large disk can sit over a small disk.
Following is an animated representation of solving a Tower of Hanoi puzzle with three disks.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with lesser amount of disks, say → 1 or 2. We mark three towers with name, source, destination and aux (only to help moving the disks). If we have only one disk, then it can easily be moved from source to destination peg.
If we have 2 disks −
First, we move the smaller (top) disk to aux peg.
Then, we move the larger (bottom) disk to destination peg.
And finally, we move the smaller disk from aux to destination peg.
So now, we are in a position to design an algorithm for Tower of Hanoi with more than two disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one part and all other (n-1) disks are in the second part.
Our ultimate aim is to move disk n from source to destination and then put all other (n1) disks onto it. We can imagine to apply the same in a recursive way for all given set of disks.
The steps to follow are −
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

A recursive algorithm for Tower of Hanoi can be driven as follows −
START
Procedure Hanoi(disk, source, dest, aux)

   IF disk == 1, THEN
      move disk from source to dest             
   ELSE
      Hanoi(disk - 1, source, aux, dest)     // Step 1
      move disk from source to dest          // Step 2
      Hanoi(disk - 1, aux, dest, source)     // Step 3
   END IF
   
END Procedure
STOP
To check the implementation in C programming, click here.

    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Broken Calculator in Python

Suppose we have a broken calculator that has a number showing on its display, we can perform only two operations −
Double − This will multiply the number on the display by 2, or;
Double − This will multiply the number on the display by 2, or;
Decrement − This will decrease the number that is showing, by 1,
Decrement − This will decrease the number that is showing, by 1,
Initially, the calculator is displaying the number X. We have to find the minimum number of operations needed to display the number Y.
So if the input is like X = 5 and Y is 8, then the output will be 2, as decrement, it once, then double it
To solve this, we will follow these steps −
res := 0
res := 0
while Y > Xres := res + Y mod 2 + 1Y := Y / 2 when Y is even, otherwise (Y + 1) / 2
while Y > X
res := res + Y mod 2 + 1
res := res + Y mod 2 + 1
Y := Y / 2 when Y is even, otherwise (Y + 1) / 2
Y := Y / 2 when Y is even, otherwise (Y + 1) / 2
return res + X - Y
return res + X - Y
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def brokenCalc(self, X, Y):
      res = 0
      while Y > X:
         res += Y % 2 + 1
         Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
      return res + X - Y
ob = Solution()
print(ob.brokenCalc(5,8))
5
8
2
What does built-in class attribute __dict__ do  in Python?

A special attribute of every module is __dict__. This is the dictionary containing the module’s symbol table.
object.__dict__
A dictionary or other mapping object used to store an object’s (writable) attributes.
The following code shows how __dict__ works
class MyClass(object):
    class_var = 1

    def __init__(self, i_var):
        self.i_var = i_var

foo = MyClass(2)
bar = MyClass(3)

print MyClass.__dict__
print foo.__dict__
print bar.__dict__
This gives the output
{'__module__': '__main__', 'class_var': 1, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None, '__init__': <function __init__ at 0x0000000004E55CF8>}
{'i_var': 2}
{'i_var': 3}
Python Number sqrt() Method

Python number method sqrt() returns the square root of x for x > 0.
Following is the syntax for sqrt() method −
import math

math.sqrt( x )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This is a numeric expression.
x − This is a numeric expression.
This method returns square root of x for x > 0.
The following example shows the usage of sqrt() method.
#!/usr/bin/python
import math   # This will import math module

print "math.sqrt(100) : ", math.sqrt(100)
print "math.sqrt(7) : ", math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi)
When we run above program, it produces following result −
math.sqrt(100) :  10.0
math.sqrt(7) :  2.64575131106
math.sqrt(math.pi) :  1.77245385091


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML Input attributes
Tryit: The list attribute
Tryit Editor v3.7

Tryit: input type = checkbox
How to turn on minor ticks only on the y-axis Matplotlib?

First, we can create fig, ax using subplots() and then, we can plot the lines. After that, using ax.yaxis.set_minor_locator(tck.AutoMinorLocator()), we can turn on the minor ticks.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Plot the line using two lists.
Plot the line using two lists.
Set the locator of the minor ticker.
Set the locator of the minor ticker.
Dynamically find minor tick positions based on the positions of major ticks. The scale must be linear with major ticks evenly spaced.
Dynamically find minor tick positions based on the positions of major ticks. The scale must be linear with major ticks evenly spaced.
Using plt.show() method, we can show the figure.
Using plt.show() method, we can show the figure.
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots()
plt.plot([0, 2, 4], [3, 6, 1])
ax.yaxis.set_minor_locator(tck.AutoMinorLocator())
plt.show()
key_down method - Action Chains in Selenium Python - GeeksforGeeks

11 Aug, 2021
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 key_down method on Action Chains in Python Selenium. key_down method is used to send a key press, without releasing it. this method is used in case one wants to press, ctrl+c, or ctrl+v. For this purpose one needs to first hold the ctrl key down and then press c. This method automates this work. It should only be used with modifier keys (Control, Alt and Shift).Syntax –  
key_down(value, element=None)
Args –  
value: The modifier key to send. Values are defined in Keys class.
element: The element to send keys. If None, sends a key to current focused element.
Example – One can use key_down method as an Action chain as below. This example clicks Ctrl+C after opening the webpage  
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
 
To demonstrate, key_down method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and press ctrl+f to open search bar.Program –  
Python3
# import webdriverfrom selenium import webdriver # import Action chainsfrom selenium.webdriver.common.action_chains import ActionChains # import KEYSfrom selenium.webdriver.common.keys import Keys # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # create action chain objectaction = ActionChains(driver) # perform the operationaction.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perform()
Output –  
 
varshagumber28
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
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
How to Use Static Variables in Arduino?

A static variable is a special kind of variable; it is allocated memory 'statically'. Its lifetime is the entire run of the program. It is specific to a function, i.e., only the function that defined it can access it. However, it doesn't get destroyed after the function call ends. It preserves its value between successive function calls. It is created and initialized the first time a function is called. In the next function call, it is not created again. It just exists.
Take a look at the following example.
void setup() {
   Serial.begin(9600);
   Serial.println();
}
void loop() {
   staticFunctionDemo();
}
void staticFunctionDemo() {
   static int staticVariable = 0;
   int normalVariable = 0;
   staticVariable = staticVariable+1;
   normalVariable = normalVariable+1;
   Serial.print("The value of static variable is: ");Serial.println(staticVariable);
   Serial.print("The value of normal variable is: ");Serial.println(normalVariable);
}
The Serial Monitor output is shown below −
As you can see, the normal variable is created and destroyed with each function call, whereas the static variable preserves its value in between function calls.
Java program to find whether given character is vowel or consonant

In English alphabet the characters 'a', 'e', 'i', 'o','u' are vowels and remaining letters are consonants. To find whether the given letter is a vowel or consonant.
Using loop and or operator verify whether given character is 'a' or 'e' or 'i' or 'o' or 'u' else it is consonant.
import java.util.Scanner;
public class VowelOrConsonant {
   public static void main(String args[]){
      System.out.println("Enter a character :");
      Scanner sc = new Scanner(System.in);
      char ch = sc.next().charAt(0);
      if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'||ch == ' '){
         System.out.println("Given character is an vowel");
      }else{
         System.out.println("Given character is a consonant");
      }
   }
}
Enter a character :
a
Given character is an vowel
Enter a character :
l
Given character is a consonant
CSS Tutorial

CSS is the language we use to style an HTML document.
CSS describes how HTML elements should be displayed.
This tutorial will teach you CSS from basic to advanced.
This CSS tutorial contains hundreds of CSS examples.
With our online editor, you can edit the CSS, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Learn from over 300 examples! With our editor, you can edit the CSS, and click on a
button to view the result.
Go to CSS Examples!
We recommend reading this tutorial, in the sequence listed in the menu.
If you have a large screen, the menu will always be present on the left.
If you have a small screen, open the menu by clicking the top menu sign ☰.
We have created some responsive W3.CSS templates for you to use.
You are free to modify, save, share, and use them in all your projects.
Free CSS Templates!
Set the color of all <p> elements to red.
<style>
 {
   red;
}
</style>

Start the Exercise
Test your CSS skills with a quiz.
Start CSS Quiz!
At W3Schools you will find complete CSS references of all properties and selectors with syntax, examples, browser support, and more.
Get certified by completing the CSS course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
JavaScript function to take a number n and generate an array with first n prime numbers

We are required to write a JavaScript function that takes in a number n and returns an array that
contains first n prime numbers. We know that prime numbers are those numbers that are only
divisible by 1 and themselves like 2, 3, 19, 37, 73 etc.
We will first write a function that checks whether a given number is prime or not and then run a
loop to generate n prime numbers. The code to check for prime numbers −
const isPrime = (n) => {
   for(let i = 2; i <= n/2; i++){
      if(n % i === 0){
         return false;
      }
   };
   return true;
};
And the full generating code will be −
const isPrime = (n) => {
   for(let i = 2; i <= n/2; i++){
      if(n % i === 0){
         return false;
      }
   };
   return true;
};
const generatePrime = num => {
   const arr = [];
   let i = 2;
   while(arr.length < num){
      if(isPrime(i)){
         arr.push(i);
      };
      i = i === 2 ? i+1 : i+2;
   };
   return arr;
};
console.log(generatePrime(6));
console.log(generatePrime(16));
console.log(generatePrime(36));
The output in the console will be −
[ 2, 3, 5, 7, 11, 13 ]
[
   2, 3, 5, 7, 11, 13,
   17, 19, 23, 29, 31, 37,
   41, 43, 47, 53
]
[
   2, 3, 5, 7, 11, 13, 17, 19, 23,
   29, 31, 37, 41, 43, 47, 53, 59, 61,
   67, 71, 73, 79, 83, 89, 97, 101, 103,
   107, 109, 113, 127, 131, 137, 139, 149, 151
]
Send SMS updates to mobile phone using python

In this tutorial, we are going to learn how to send SMS in Python. We will be using Twilio for sending SMS.
First of all, go the Twilio and create an account. You will get free trial account. And finish settings.
We have to install a module called twilio to work with Twilio client. Install it with the following command.
pip install twilio
Now, go to the Twilio Documentation on how to send SMS using Twilio client. Or follow the steps to send the SMS.
Import the twilio Client from twilio.rest.
Get and store the account_sid and auth_token from the your Twilio account.
Make instance of the Client by passing account_sid and auth_token.
Now, get the from number from your Twilio account.
Now, send the message using client.messages.create(body=message,
from_=from_number, to=verified_number).
You will get the message.
# importing the client from the twilio
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio account
account_sid = [ACCOUNT_SID]
auth_token = [AUTH_TOKEN]
# instantiating the Client
client = Client(account_sid, auth_token)
# sending message
message = client.messages.create(body='Hi there! How are you?', from_=[FROM_NUM
, to=[VERIFIED_NUMBER])
# printing the sid after success
print(message.sid)
If the message is sent successfully, then you will get the hash code as follows without any
SMd954e170ca2545248075c3bc2623aabd
If you have any doubts in the tutorial, mention them in the comment section.
Loops & Control Structure in C - GeeksQuiz

22 Sep, 2021
C
How many times GeeksQuiz is printed in the above program ? 
1 
3 
4 
Compile-time error 
If a macro needs to be expanded in multiple lines, it is the best practice to write those lines within do{ }while(0) to avoid macro side effects. After GeeksQuiz is printed once, the control reaches the while statement to check for the condition. Since, the condition is false, the loop gets terminated. 
 switch (c)
 {
    case 'a':
    case 'e':
    case 'i' :
    case 'o':
    case 'u':
      printf(" Vowel character");
      break;
    default :
      printf("Not a Vowel character");; break;
  }
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to set background images in ReactJS ?
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Alter Multiple Columns at Once in SQL Server?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Check for integer overflow on multiplication in C++

Suppose we want to find the result after multiplying two numbers A and B. We have to check whether the multiplied value will exceed the 64-bit integer or not. If we multiply 100, and 200, it will not exceed, if we multiply 10000000000 and -10000000000, it will overflow.
To check this, we have to follow some steps. These are like below −
Steps −
If anyone of the numbers is 0, then it will not exceed
If anyone of the numbers is 0, then it will not exceed
Otherwise, if the product of two divided by one equals to the other, then it will not exceed
Otherwise, if the product of two divided by one equals to the other, then it will not exceed
For some other cases, it will exceed.
For some other cases, it will exceed.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
bool isMulOverflow(long long A, long long B) {
   if (A == 0 || B == 0)
      return false;
   long long result = A * B;
   if (A == result / B)
      return false;
   else
      return true;
}
int main() {
   long long a = 10000000000 , b = -10000000000;
   if(isMulOverflow(a, b)){
      cout <<"It will overflow";
   }
   else{
      cout <<"It will not overflow";
   }
}
It will overflow
How to detach a package in R?

To detach a package in R, we can simply use the detach function. But we need to remember that once the package will be detached there is no way to use any of the functions of that particular package. We make this mistake if we forget about detachment. For example, if we detach ggplot2 package using detach function detach(package:ggplot2,unload=TRUE) and again run the ggplot or qplot function then there will be an error.
Consider the below data frame −
Live Demo
> x<-rnorm(10)
> y<-rnorm(10)
> df<-data.frame(x,y)
> df
x y
1 -0.09124881 0.8106691
2 -0.20521435 -1.0067072
3 -1.07904498 1.3867400
4 1.34461945 -1.4676405
5 -0.21731862 0.5801624
6 -0.54413731 0.1817524
7 1.05737101 0.7518694
8 -0.08566360 0.3428287
9 -0.40894417 -0.2992289
10 1.71507507 0.9979026
Loading ggplot2 package and creating a scatterplot −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Detaching the ggplot2 package −
> detach(package:ggplot2,unload=TRUE)
Now again creating the plot −
> ggplot(df,aes(x,y))+geom_point()
Error in ggplot(df, aes(x, y)) : could not find function "ggplot"
HTML - <track> tag

The HTML <track> tag is used for defining captions, subtitles, and other content for <audio> and <video> tags
<!Doctype html>
<html>

   <head>
      <title>HTML source Tag</title>
   </head>

   <body>
      <audio controls>
         <source src = "yourfile.mp3">
         <track src = "subtitles.vtt" kind = "subtitles" srclang = "en" label =" English">
         <p>:The browser doesnot support the file</p>
      </audio>
   </body>

</html>
This will produce the following result −
:The browser doesnot support the file
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <track> tag also supports the following additional attributes −
captions
chapters
descriptions
metadata
subtitles
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
When should you use a class vs a struct in C++?

Structures and classes are very similar in C++ except for some differences. So details about these differences are given below that help to decide when to use a class or structure in C++.
All the members of a class are private by default. This is different compared to structures as all the members of a structure are public by default.
A program that demonstrates a class in C++ is given as follows −
#include <iostream>
using namespace std;
class Example {
   int val;
};
int main() {
   Example obj;
   obj.val = 20;
   return 0;
}
This program results in an error as val is private by default and so cannot be accessed directly using obj.
A program that demonstrates a structure in C++ is given as follows −
 Live Demo
#include <iostream>
using namespace std;
struct Example {
   int val;
};
int main() {
   Example obj;
   obj.val = 20;
   cout<<"Value is: "<<obj.val;
   return 0;
}
The output of the above program is as follows −
Value is: 20
The above program works correctly as val is public by default and so can be accessed directly using obj.
Another difference between a class and a structure is evident during inheritance. When inheriting a class, the access specifier of the base class is private by default. Comparatively, when inheriting a structure, the access specifier of the base structure is public by default.
SQL - TOP, LIMIT or ROWNUM Clause

The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.
Note − All the databases do not support the TOP clause. For example MySQL supports the LIMIT clause to fetch limited number of records while Oracle uses the ROWNUM command to fetch a limited number of records.
The basic syntax of the TOP clause with a SELECT statement would be as follows.
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]

Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

The following query is an example on the SQL server, which would fetch the top 3 records from the CUSTOMERS table.
SQL> SELECT TOP 3 * FROM CUSTOMERS;
This would produce the following result −
+----+---------+-----+-----------+---------+
| ID | NAME    | AGE | ADDRESS   | SALARY  |
+----+---------+-----+-----------+---------+
|  1 | Ramesh  |  32 | Ahmedabad | 2000.00 |
|  2 | Khilan  |  25 | Delhi     | 1500.00 |
|  3 | kaushik |  23 | Kota      | 2000.00 |
+----+---------+-----+-----------+---------+

If you are using MySQL server, then here is an equivalent example −
SQL> SELECT * FROM CUSTOMERS
LIMIT 3;
This would produce the following result −
+----+---------+-----+-----------+---------+
| ID | NAME    | AGE | ADDRESS   | SALARY  |
+----+---------+-----+-----------+---------+
|  1 | Ramesh  |  32 | Ahmedabad | 2000.00 |
|  2 | Khilan  |  25 | Delhi     | 1500.00 |
|  3 | kaushik |  23 | Kota      | 2000.00 |
+----+---------+-----+-----------+---------+

If you are using an Oracle server, then the following code block has an equivalent example.
SQL> SELECT * FROM CUSTOMERS
WHERE ROWNUM <= 3;
This would produce the following result −
+----+---------+-----+-----------+---------+
| ID | NAME    | AGE | ADDRESS   | SALARY  |
+----+---------+-----+-----------+---------+
|  1 | Ramesh  |  32 | Ahmedabad | 2000.00 |
|  2 | Khilan  |  25 | Delhi     | 1500.00 |
|  3 | kaushik |  23 | Kota      | 2000.00 |
+----+---------+-----+-----------+---------+


    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to create a point chart with empty points using ggplot2 in R?

The point chart can be created by using geom_point function and if we want to create a point chart for single vector then we should pass the vector in both the places inside aes function. Also, by default the points are complete black circles and if we want to change the points to empty points then shape argument can be used.
Consider the below data frame −
 Live Demo
set.seed(171)
x<−rnorm(20,1,0.04)
df<−data.frame(x)
df
x
1 0.9608285
2 1.0077832
3 1.0420915
4 0.9526998
5 1.0423519
6 1.0023625
7 0.9184376
8 1.0215420
9 1.0841583
10 1.0164277
11 1.0215934
12 0.9135340
13 0.9975233
14 1.0626451
15 1.0335912
16 1.0702276
17 0.9642820
18 1.0088072
19 0.9794760
20 0.9665569
Loading ggplot2 package and creating point chart −
library(ggplot2)
ggplot(df,aes(x,x))+geom_point()
Creating the point chart with empty points −
ggplot(df,aes(x,x))+geom_point(shape=1)
Creating the point chart with empty points and a larger size −
ggplot(df,aes(x,x))+geom_point(shape=1,size=3)
How to add jar as library on Android Studio?

This example demonstrates how to add jar as a library on Android Studio.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following jar file to Project/app/libs/
Step 3 − Add the following dependencies to File/Project Structure
Step 4 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 5 − Add the following code to src/MainActivity.java
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 6 − Add the following code to Manifests/AndroidManifest.xml 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.app.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
      </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − 
   
Click here to download the project code.
Python Pillow - Creating Thumbnails

Sometimes, it is required to have all images of equal height and width. One way to achieve this, is by creating a thumbnail of all images using the thumbnail() function from pillow library.
This method modifies the image to contain a thumbnail version of itself and the size of the image will be no larger than the given size.
The method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft () method to configure the file reader (where applicable) and finally, resizes the image.
Image.thumbnail(size, resample=3)

Where,
Size − Required size
Size − Required size
Resample − Optional resampling filter. It can be one of these PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS. If omitted, it defaults to PIL.Image.BICUBIC.
Resample − Optional resampling filter. It can be one of these PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS. If omitted, it defaults to PIL.Image.BICUBIC.
Returns − None
Returns − None
Following example demonstrates the creation of a thumbnail using python pillow −
from PIL import Image
def tnails():
   try:
      image = Image.open('images/cat.jpg')
      image.thumbnail((90,90))
      image.save('images/thumbnail.jpg')
      image1 = Image.open('images/thumbnail.jpg')
      image1.show()
   except IOError:
      pass
tnails()
If you save the above program as Example.py and execute, it displays the created thumbnail using the default PNG display utility, as follows −
Original image
Output image

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to calculate sum of random numbers in between 0 to 100 using files in C Programming?

In this program, we are adding random numbers that are generated in between 0 and 100.
After every runtime, the result of sum of random numbers is different, i.e., we get a different result for every execution.
The logic we use to calculate the sum of random numbers in between 0 to 100 is −
for(i = 0; i <=99; i++){
   // Storing random numbers in an array.
   num[i] = rand() % 100 + 1;
   // calculating the sum of the random numbers.
   sum+= num[i];
}
First, we calculate the sum of random numbers and store that sum in a file. For that open file in write open and append the sum to the array file using fprintf.
fprintf(fptr, "Total sum of the array is %d\n", sum);
//appending sum to the array file.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define max 100
// Declaring the main function in the main header.
int main(void){
   srand(time(0));
   int i;
   int sum = 0, num[max];
   FILE *fptr;
   // Declaring the loop to generate 100 random numbers
   for(i = 0; i <=99; i++){
      // Storing random numbers in an array.
      num[i] = rand() % 100 + 1;
      // calculating the sum of the random numbers.
      sum+= num[i];
   }
   // intializing the file node with the right node.
   fptr = fopen("numbers.txt", "w");
   // cheching if the file pointer is null, check if we are going to exit or not.
   if(fptr == NULL){
      printf("Error!");
      exit(1);
   }
   fprintf(fptr, "Total sum of the array is %d\n", sum); // appending sum to the array file.
   fclose(fptr); // closing the file pointer
}
Run 1: Total sum of the array is 5224
Run 2: Total sum of the array is 5555
Note: after executing a text file is created in the same folder with number.txt
We have to open it; there we can see the sum of random numbers.