code-rag-bench/online-tutorials huggingface dataset:
How to Fix “class, interface, or enum expected” Error in Java with Examples?

28 Jan, 2021
In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java: 
Case 1: Extra curly Bracket
Java
class Hello {      public static void main(String[] args)    {        System.out.println("Helloworld");    }}} // extra bracket.
 
In this case, the error can be removed by simply removing the extra bracket.
Java
class Hello {      public static void main(String[] args)    {        System.out.println("Helloworld");    }}
 
Case 2: Function outside the class
Java
class Hello {    public static void main(String args[])    {        System.out.println("HI");    }}public static void func() { System.out.println("Hello"); }
 
In the earlier example, we get an error because the method func() is outside the Hello class. It can be removed by moving the closing curly braces “}” to the end of the file. In other words, move the func() method inside of​ Hello.
Java
class Hello {    public static void main(String args[])    {        System.out.println("HI");    }    public static void func()    {        System.out.println("Hello");    }}
 
Case 3: Forgot to declare class at all
There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not.
Case 4: Declaring more than one package in the same file
Java
package A;class A {    void fun1() { System.out.println("Hello"); }}package B; //getting class interface or enum expectedpublic class B {    public static void main(String[] args)    {        System.out.println("HI");    }}
 
We can not put different packages into the same source file. In the source file, the package statement should be the first line. 
Java
package A;class A {    void fun1() { System.out.println("Hello"); }}public class B {    public static void main(String[] args)    {        System.out.println("HI");    }}
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Different ways of Reading a text file in Java
Constructors in Java
Strings in Java
HashMap containsKey() Method in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Traverse Through a HashMap in Java
Extends vs Implements in Java
How to set Cookie in ReactJS ?

16 Dec, 2020
Cookies are an important part of an application because cookies are used to set value in a key-value form which can be set in browser storage and used further for identifying the current user. The following example shows how to set the cookie in the ReactJS application, here we have taken the username as key, which is set in the cookie with its value.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app setcookiedemo
Step 2: After creating your project folder i.e. setcookiedemo, move to it using the following command:
cd setcookiedemo
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to set cookies in localStorage with basic UI.
Javascript
import React, { useState } from "react";  const App = () => {    const [message, setMessage] = useState('')      const setCookieFunction = (value) => {        localStorage.setItem('username', value)      setMessage('Username set as cookie!!')  }    return (    <div style={{      marginLeft: '200px',    }}>      <pre>        <h2>Setting Cookie in ReactJS</h2>        <span>Enter User Name: </span><input type="text"         onChange={(e) => setCookieFunction(e.target.value)}></input> <br />        <span style={{          fontWeight: 'bold',          color: 'red',        }}>{message}</span>      </pre>    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters a username which is set as a cookie as shown below:Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:
The following will be the output if the user enters a username which is set as a cookie as shown below:
The following will be the output if the user enters a username which is set as a cookie as shown below:
Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:
Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:
react-js
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Perl | my keyword

07 May, 2019
my keyword in Perl declares the listed variable to be local to the enclosing block in which it is defined. The purpose of my is to define static scoping. This can be used to use the same variable name multiple times but with different values. Note: To specify more than one variable under my keyword, parentheses are used.
Syntax: my variable
Parameter:variable: to be defined as local
Returns:does not return any value.
Example 1:
#!/usr/bin/perl -w  # Local variable outside of subroutinemy $string = "Geeks for Geeks";print "$string\n";  # Subroutine callmy_func();print "$string\n";  # defining subroutine sub my_func{    # Local variable inside the subroutine    my $string = "This is in Function";    print "$string\n";    mysub();}  # defining subroutine to show# the local effect of my keywordsub mysub {    print "$string\n";}
Output:
Geeks for Geeks
This is in Function
Geeks for Geeks
Geeks for Geeks
Example 2:
#!/usr/bin/perl -w  # Local variable outside of subroutinemy $string = "Welcome to Geeks";print "$string\n";  # Subroutine callmy_func();print "$string\n";  # defining subroutine sub my_func{    # Local variable inside the subroutine    my $string = "Let's GO Geeky!!!";    print "$string\n";    mysub();}  # defining subroutine to show# the local effect of my keywordsub mysub {    print "$string\n";}
Output:
Welcome to Geeks
Let's GO Geeky!!!
Welcome to Geeks
Welcome to Geeks
How to define dynamic scoping?The opposite of “my” is “local”. The local keyword defines dynamic scoping.
# A perl code to demonstrate dynamic scoping $x = 10; sub f {    return $x; } sub g {    # Since local is used, x uses      # dynamic scoping.    local $x = 20;      return f(); }   print g()."\n"; 
perl-basics
Perl-Keywords
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to check date in date range

06 Jun, 2021
Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range.
Example:
Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
Output : True
Explanation : 30 Dec’2019 lies in range of 14 March 2019 to 4 January 2020, hence True.
Input : test_list = [datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
Output : False
Explanation : No date lies in range.
Method 1: Using loop
In this, for each element, we check using conditionals if any date falls in the range, if found, true is returned.
Python3
# Python3 code to demonstrate working of# Test for date in date range# Using loopfrom datetime import datetime  # initializing listtest_list = [datetime(2019, 12, 30), datetime(2018, 4, 4),              datetime(2016, 12, 21), datetime(2021, 2, 2),              datetime(2020, 2, 3), datetime(2017, 1, 1)]  # printing original listprint("The original list is : " + str(test_list))  # initializing date rangesdate_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)  res = Falsefor ele in test_list:      # checking for date in range    if ele >= date_strt and ele <= date_end:        res = True  # printing resultprint("Does list contain any date in range : " + str(res))
Output:
The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2018, 4, 4, 0, 0), datetime.datetime(2016, 12, 21, 0, 0), datetime.datetime(2021, 2, 2, 0, 0), datetime.datetime(2020, 2, 3, 0, 0), datetime.datetime(2017, 1, 1, 0, 0)]
Does list contain any date in range : True
Method 2: Using any()
Similar to the above method, the only difference being any() is used to check for the presence of any date in range.
Python3
# Python3 code to demonstrate working of# Test for date in date range# Using any()from datetime import datetime  # initializing listtest_list = [datetime(2019, 12, 30), datetime(2018, 4, 4),             datetime(2016, 12, 21), datetime(2021, 2, 2),              datetime(2020, 2, 3), datetime(2017, 1, 1)]  # printing original listprint("The original list is : " + str(test_list))  # initializing date rangesdate_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)  # any() for checking presence of any date in rangeres = any(ele >= date_strt and ele <= date_end for ele in test_list)  # printing resultprint("Does list contain any date in range : " + str(res))
Output:
The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2018, 4, 4, 0, 0), datetime.datetime(2016, 12, 21, 0, 0), datetime.datetime(2021, 2, 2, 0, 0), datetime.datetime(2020, 2, 3, 0, 0), datetime.datetime(2017, 1, 1, 0, 0)]
Does list contain any date in range : True
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to refresh a file in Node.js ?

13 Feb, 2020
Node.js has seen an important growth in past years and is still increasing its value in many organizations and business models. Companies like Walmart or PayPal have already started to adopt it.NPM, the package manager of Node.js has been already installed when you install Node.js and is ready to run on your computer. Node.js doesn’t offer you the privilege of automatic restart like other languages such as PHP or Ruby. Whenever you make changes in your source code, you need to run the code again and again by using command.
Most of us are used to save the file in Editor and then hit [ctrl + c] (To stop application) & then restart by hitting again [UP arrow + Enter]. However rather than doing this repetitive task manually, we can certainly automate it and can make the process more easier by using some tools:
nodemonnode-supervisorforever
nodemon
node-supervisor
forever
1. nodemin: Among all those tools, we would like to start with nodemon first. Basically, Nodemon is a utility that monitor for any changes in your source and automatically restart your server.
Installation Command:
npm install nodemon -g
After installing the nodemon utility we will use the following command to run the code.
nodemon filename.js
2. node-supervisor:Installation Command
npm install supervisor -g
After installing the node-supervisor we will use the following command to run the code.
supervisor filename.js
3. forever: The remaining tool so called forever is a node.js package that is used to keep server alive even when it crashes or stops because of some error/exception. Forever automatically restarts it.Installation Command
npm install forever -g
frorever start filename.js
Picked
Technical Scripter 2019
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Explain array of pointers in C programming language

Pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
Execution time of pointer is faster because of direct access to memory location.
With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Consider the following statement −
int qty = 179;
In memory, the variable can be represented as follows −
It means ‘p’ is a pointer variable, which holds the address of another integer variable, as shown below −
Int *p;
Address operator (&) is used to initialise a pointer variable.
For Example − int qty = 175;
        int *p;
        p= &qty;
It is collection of addresses (or) collection of pointers
Following is the declaration for array of pointers −
datatype *pointername [size];
For example,
int *p[5];
It represents an array of pointers that can hold 5 integer element addresses.
‘&’ is used for initialisation.
For Example,
int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i] = a+i;
Indirection operator (*) is used for accessing.
For Example,
for (i=0, i<3; i++)
printf ("%d", *p[i]);
Given below is the program for array of pointers −
 Live Demo
#include<stdio.h>
main ( ){
   int a[3] = {10,20,30};
   int *p[3],i;
   for (i=0; i<3; i++)
      p[i] = &a[i];
   printf ("elements of the array are \n");
   for (i=0; i<3; i++)
      printf ("%d \t", *p[i]);
}
When the above program is executed, it produces the following result −
elements at the array are : 10 20 30
Given below is the program for the array of pointers to strings −
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main(void){
   char *a[5] = {"one", "two", "three", "four", "five"};
   int i;
   printf ( "the strings are at locations:\n");
   for (i=0; i<5; i++)
      printf ("%d\n", a[i]);
   return 0;
}
When the above program is executed, it produces the following result −
The strings are at locations:
4210688
4210692
4210696
4210702
4210707
Tryit Editor v3.7

Tryit: A list with ABC
How to replace a character in a MySQL table?

To replace only a single character, use REPLACE() in MySQL. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John Smitk');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David Miller');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam Smitk');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| Name         |
+--------------+
| John Smitk   |
| David Miller |
| Adam Smitk   |
+--------------+
3 rows in set (0.00 sec)
Here is the query to replace a character −
mysql> update DemoTable
   -> set Name=replace(Name,'k','h');
Query OK, 2 rows affected (0.13 sec)
Rows matched: 3 Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| Name         |
+--------------+
| John Smith   |
| David Miller |
| Adam Smith   |
+--------------+
3 rows in set (0.00 sec)
Lodash _.flatMap() Method - GeeksforGeeks

10 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.flatMap() method creates a flattened array of values by running each element in collection through iteratee and flattening the mapped results.
Syntax:
_.flatMap(collection, iteratee)
Parameters: This method accepts two parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
iteratee: This parameter holds the function invoked per iteration.
Return Value: This method returns the new flattened array.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array var user1 = ([35, 47, 58, 69, 94, 13, 72]);  // Use of _.flatMap() methodlet gfg1 = _.flatMap(user1, function duplicate(n) {  return [n, n];})  // Printing the output console.log(gfg1);
Output:
[
  35, 35, 47, 47, 58, 58, 
  69, 69, 94, 94, 13, 13,
  72, 72
]

Example 2:
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array var user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);var user2 = ([3, 4, 5, 9, 9, 1, 7]);  // Use of _.flatMap() methodlet gfg1 = _.flatMap(user1, function duplicate(n) {  return [n, n];})  let gfg2 = _.flatMap(user2, function duplicate(n) {  return [n, n];})  // Printing the output console.log(gfg1);console.log(gfg2);
Output:
[
  3.5, 3.5, 4.7, 4.7, 5.8, 5.8, 
  6.9, 6.9, 9.4, 9.4, 1.3, 1.3,
  7.2, 7.2
]
[
  3, 3, 4, 4, 5, 5,
  9, 9, 9, 9, 1, 1,
  7, 7
]

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Form validation using HTML and JavaScript
Express.js express.Router() Function
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Python | Ways to check string contain all same characters

29 Jun, 2019
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same.
Method #1: Using Naive Method [Inefficient]
# Python code to demonstrate # to check whether string contains# all characters same or not  # Initialising string listini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]  # Printing initial stringprint ("Initial Strings list", ini_list)  # Using Naive Method:flag = Truefor i in ini_list:    for j in range(0, len(i)-1):        if i[j]!= i[j + 1]:            print ("String {} don't have all characters same".format(i))            flag = False            break    if flag == True:        print ("String {} don't have all characters same".format(i))         
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa don't have all characters same
String aaaaaaabaa don't have all characters same

 Method #2: Using String Comparisons
# Python code to demonstrate # to check whether string contains# all characters same or not  # Initialising string listini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]  # Printing initial stringprint ("Initial Strings list", ini_list)  # Using String comparisonfor i in ini_list:    if i == len(i)*i[0]:        print ("String {} have all characters same".format(i))    else:        print ("String {} don't have all characters same".format(i))         
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same

 Method #3: Using count comparison
# Python code to demonstrate # to check whether string contains# all characters same or not  # Initialising string listini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]  # Printing initial stringprint ("Initial Strings list", ini_list)  # Using String comparisonfor i in ini_list:    if i.count(i[0]) == len(i):        print ("String {} have all characters same".format(i))    else:        print ("String {} don't have all characters same".format(i))         
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
UUID() function in MySQL

16 Dec, 2020
This function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”.It is designed as a number that is universally unique. Two UUID values are expected to be distinct, even they are generated on two independent servers. In MySQL, a UUID value is a 128-bit number represented as a utf8 string, and the format in hexadecimal number will be as follows.
Example –
aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee

Here, the first three numbers are generated from the low, middle, and high parts of a timestamp. As you can see that in the above format fourth place digits code will preserve temporal uniqueness and fifth place code will provide spatial uniqueness and it is an IEEE 802 node number.
Syntax :
UUID()
Parameter :This method does not any parameter.Returns :It returns a Universal Unique Identifier number.
Example-1 :Generating a Universal Unique Identifier value with the help of UUID Function.
SELECT UUID() 
AS UUID_Value ;
Output :
Example-2 :Whenever we will use UUID function we will get different Universal Unique Identifier value. Lets check it.
  SELECT UUID() 
AS  
UUID_VALUE1, 
UUID() 
AS UUID_VALUE2, 
UUID() 
AS UUID_VALUE3 ;
Output :
Example-3 :In this example, we will use UUID as a primary key in a table. To demonstrate create a table named OrderDetails.
CREATE TABLE OrderDetails(
   OrderId BINARY(16) PRIMARY KEY,
   ProductName VARCHAR(100) NOT NULL,
   Price DECIMAL(10, 2) NOT NULL,
   ExpectedDelivery DATE NOT NULL
);

Now, inserting data into OrderDetails table. Here, We will use UUID and UUID_TO_BIN() functions to assign the value in OrderId Column.
INSERT INTO OrderDetails(OrderId, ProductName, Price, ExpectedDelivery)
VALUES(UUID_TO_BIN(UUID()), 'Asus Rog', 90000.00, '2020-12-20'),
      (UUID_TO_BIN(UUID()), 'Acer Predator', 100000.00, '2020-12-18'),
      (UUID_TO_BIN(UUID()), 'Lenovo Legion', 85000.00, '2020-12-19'),
      (UUID_TO_BIN(UUID()), 'Hp Omen', 70000.00, '2020-12-18'),
      (UUID_TO_BIN(UUID()), 'Dell Inspiron', 65000.00, '2020-12-23'),
      (UUID_TO_BIN(UUID()), 'Acer Nitro', 60000.00, '2020-12-22'),
      (UUID_TO_BIN(UUID()), 'Asus Tuf', 80000.00, '2020-12-19');
Next we will use the following command to check the table.
SELECT  * from OrderDetails;
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList element() method in Java with Examples

10 Dec, 2018
The element() method of java.util.LinkedList class retrieves, but does not remove, the head (first element) of this list.
Syntax:
public E element()
Return Value: This method returns the head of this list.
Below are the examples to illustrate the element() method
Example 1:
// Java program to demonstrate// element() method// for Integer value  import java.util.*;  public class GFG1 {    public static void main(String[] argv) throws Exception    {        try {              // creating object of LinkedList<Integer>            LinkedList<Integer> list = new LinkedList<Integer>();              // add some elements to list            list.add(10);            list.add(20);            list.add(30);              // print the linked list            System.out.println("LinkedList : " + list);              // getting the head of list            // using element() method            int value = list.element();              // print the head of list            System.out.println("Head of list : " + value);        }          catch (NullPointerException e) {              System.out.println("Exception thrown : " + e);        }    }}
LinkedList : [10, 20, 30]
Head of list : 10

Example 2:
// Java program to demonstrate// element() method// for String value  import java.util.*;  public class GFG1 {    public static void main(String[] argv) throws Exception    {        try {              // creating object of LinkedList<String>            LinkedList<String> list = new LinkedList<String>();              // add some elements to list            list.add("A");            list.add("B");            list.add("C");              // print the linked list            System.out.println("LinkedList : " + list);              // getting the head of list            // using element() method            String value = list.element();              // print the head of list            System.out.println("Head of list : " + value);        }          catch (NullPointerException e) {              System.out.println("Exception thrown : " + e);        }    }}
LinkedList : [A, B, C]
Head of list : A

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Understanding “register” keyword in C

21 Aug, 2019
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in register.
1) If you use & operator with a register variable then compiler may give an error or warning (depending upon the compiler you are using), because when we say a variable is a register, it may be stored in a register instead of memory and accessing address of a register is invalid. Try below program.
#include<stdio.h>    int main(){    register int i = 10;    int* a = &i;    printf("%d", *a);    getchar();    return 0;}
2) register keyword can be used with pointer variables. Obviously, a register can have address of a memory location. There would not be any problem with the below program.
#include<stdio.h>  int main(){    int i = 10;    register int* a = &i;    printf("%d", *a);    getchar();    return 0;}
3) Register is a storage class, and C doesn’t allow multiple storage class specifiers for a variable. So, register can not be used with static . Try below program.
#include<stdio.h>  int main(){    int i = 10;    register static int* a = &i;    printf("%d", *a);    getchar();    return 0;}
4) Register can only be used within a block (local), it can not be used in the global scope (outside main).
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
#include <stdio.h>  // error (global scope)register int x = 10;int main(){    // works (inside a block)    register int i = 10;    printf("%d\n", i);    printf("%d", x);    return 0;}
Compile Errors:
prog.c:3:14: error: register name not specified for 'x'
 register int x = 10;//error (global scope)
              ^

5) There is no limit on number of register variables in a C program, but the point is compiler may put some variables in register and some not.
Please write comments if you find anything incorrect in the above article or you want to share more information about register keyword.
AnasKhedr
Ankur Trivedi
c-puzzle
C-Storage Classes and Type Qualifiers
Articles
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
SQL Interview Questions
SQL | Views
Java Tutorial
Docker - COPY Instruction
std::sort() in C++ STL
Bitwise Operators in C/C++
Arrays in C/C++
Substring in C++
Function Pointer in C
How to display records having sum between a specific range using GROUP BY, HAVING and ORDER BY in a single MySQL query?

Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(20),
   ProductPrice int
);
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',600);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(CustomerName,ProductPrice) values('David',450);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',980);
Query OK, 1 row affected (0.40 sec)
mysql> insert into DemoTable(CustomerName,ProductPrice) values('Mike',1200);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(CustomerName,ProductPrice) values('Chris',400);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(CustomerName,ProductPrice) values('David',1200);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------------+--------------+
| Id | CustomerName | ProductPrice |
+----+--------------+--------------+
|  1 | Chris        |          600 |
|  2 | David        |          450 |
|  3 | Chris        |          980 |
|  4 | Mike         |         1200 |
|  5 | Chris        |          400 |
|  6 | David        |         1200 |
+----+--------------+--------------+
6 rows in set (0.00 sec)
Following is the query to display a specific range of numbers −
mysql> select CustomerName,sum(ProductPrice) AS Total_Price
   from DemoTable
   group by CustomerName
   having sum(ProductPrice) between 1600 and 2000
   order by CustomerName DESC;
This will produce the following output −
+--------------+-------------+
| CustomerName | Total_Price |
+--------------+-------------+
| David        |        1650 |
| Chris        |        1980 |
+--------------+-------------+
2 rows in set (0.00 sec)
Scala String substring(int beginIndex, int endIndex) method with example - GeeksforGeeks

29 Oct, 2019
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified.
Method Definition: String substring(int beginIndex, int endIndex)
Return Type: It returns string which is the part of the stated String.
Note: It is same as sub-sequence method but the only difference between the two is that sub-sequence returns CharSequence but the above method returns string.
Example: 1#
// Scala program of substring()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying substring method        val result = "GeeksforGeeks".substring(4, 8)                  // Displays output        println(result)          }} 
sfor

Example: 2#
// Scala program of substring()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying substring method        val result = "GeeksforGeeks".substring(0, 4)                  // Displays output        println(result)          }} 
Geek

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Class and Object in Scala
Break statement in Scala
Operators in Scala
Scala Constructors
How to get the first element of List in Scala
HashMap in Scala
Enumeration in Scala
Scala ListBuffer
Hello World in Scala
Scala Map get() method with example
How to set the Row Height of a JTree with Java?

To set the row height of a JTree, use the setRowHeight() and as a parameter set the height in pixels −
tree.setRowHeight(25);
The following is an example to set the row height of a JTree with Java −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp");
      node.add(node1);
      node.add(node2);
      node.add(node3);
      DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website");
      DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website");
      DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website");
      DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app");
      DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app");
      DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp");
      node1.add(one);
      node1.add(two);
      node1.add(three);
      node2.add(four);
      node2.add(five);
      node3.add(six);
      JTree tree = new JTree(node);
      tree.setRowHeight(25);
      frame.add(tree);
      frame.setSize(550,400);
      frame.setVisible(true);
   }
}
Stream generate() method in Java with examples

06 Dec, 2018
Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.
Syntax :
static <T> Stream<T> generate(Supplier<T> s)

Where, Stream is an interface and T
is the type of stream elements.
s is the Supplier of generated 
elements and the return value is
a new infinite sequential
unordered Stream.

Example 1 : To generate stream of random integer.
// Java code for Stream.generate()// to generate an infinite sequential// unordered streamimport java.util.*;import java.util.stream.Stream;  class GFG {          // Driver code    public static void main(String[] args) {          // using Stream.generate() method     // to generate 5 random Integer values    Stream.generate(new Random()::nextInt)    .limit(5).forEach(System.out::println);     }}
Output :
697197501
50139200
321540264
1042847655
-770409472

Example 2 : To generate stream of random Double.
// Java code for Stream.generate()// to generate an infinite sequential// unordered streamimport java.util.*;import java.util.stream.Stream;  class GFG {          // Driver code    public static void main(String[] args) {          // using Stream.generate() method     // to generate 8 random Double values    Stream.generate(new Random()::nextDouble)    .limit(8).forEach(System.out::println);     }}
Output :
0.5390254520295368
0.8477297185718798
0.23703352435894398
0.09156832989674057
0.9671295321757734
0.9989670394813547
0.8909416330715489
0.08177639888829968

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python | Play a video using OpenCV

15 Oct, 2018
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos.
Let’s see how to play a video using the OpenCV Python.
To capture a video, we need to create a VideoCapture object. VideoCapture have the device index or the name of a video file. Device index is just the number to specify which camera. If we pass 0 then it is for first camera, 1 for second camera so on. We capture the video frame by frame.Syntax :
cv2.VideoCapture(0): Means first camera or webcam.
cv2.VideoCapture(1):  Means second camera or webcam.
cv2.VideoCapture("file name.mp4"): Means video file
Below is the implementation:
# importing librariesimport cv2import numpy as np   # Create a VideoCapture object and read from input filecap = cv2.VideoCapture('tree.mp4')   # Check if camera opened successfullyif (cap.isOpened()== False):   print("Error opening video  file")   # Read until video is completedwhile(cap.isOpened()):        # Capture frame-by-frame  ret, frame = cap.read()  if ret == True:       # Display the resulting frame    cv2.imshow('Frame', frame)       # Press Q on keyboard to  exit    if cv2.waitKey(25) & 0xFF == ord('q'):      break     # Break the loop  else:     break   # When everything done, release # the video capture objectcap.release()   # Closes all the framescv2.destroyAllWindows()
Note : Video file should have in same directory where program is executed.Output:
Sample Frame of video :
Related Article : How to play video in reverse mode.
Image-Processing
OpenCV
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
Print multiplication table of a given number in C

Print multiplication table of a given number
Accept any number from the User for which we need to form multiplication table.
Multiply the given number starting with the value of I (=1)
Multiply the given number by incrementing the value of I till the I value is lesser than or equal to 12.
/* Program to print the multiplication table of a given number */
#include <stdio.h>
int main() {
   int number, i;
   clrscr();
   printf("Please enter any number to find multiplication table:");
   scanf("%d", &number);
   printf("Multiplication table for the given number %d: ", number);
   printf("\n");
   for(i=1;i<=12;i++){
      printf("%d x %d = %d", number, i, number * i);
      printf("\n");
   }
   getch();
   return 0;
}
How to Make a Bell Curve in R?

24 Feb, 2021
To make a bell curve in R we will be using the help of normal distribution which will lead to a bell curve that will be symmetrical about the mean. Half of the data will fall to the left of the mean and half will fall to the right.
In probability theory, a normal distribution is a type of continuous probability distribution for a real-valued random variable. 
Mathematical formula:
Where,
 is mean
 is standard deviation.
For the normal distribution, we use dnorm() function to get the value of the probability density function for the normal distribution given parameters for x, μ, and σ.
Syntax: dnorm(x, mean, sd) (sd=Standard Deviation)
Parameters:-
X is a vector of numbers.
Mean is the mean value of the sample data. Its default value is zero.
Sd is the standard deviation. Its default value is 1.
Returns:-The probability distribution at each point for a given mean and standard deviation.
Approach
Create a sequence of numbers
Get probability distribution at each point for a given mean and standard deviation
Plot data with appropriate attributes
Example 1:
R
# sequence of numbers between -10 and 10 incrementing by 0.1.x <- seq(-12, 12, by = .1)  # getting probability distribution for each pointy <- dnorm(x, mean = 5, sd = 1)  # Plot graphplot(x,y)
Output:
Example 2:
R
# sequence of numbers between -10 and 10 incrementing by 0.1.x <- seq(-5, 5, by = .5)  # getting probability distributiony <- dnorm(x, mean = 1, sd = 1.5)  # plot dataplot(x,y, col="red")
Output:
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Finding the k smallest values of a NumPy array

02 Sep, 2020
In this article, let us see how to find the k number of the smallest values from a NumPy array.
Examples:
Input: [1,3,5,2,4,6] 
k = 3

Output: [1,2,3] 

Method 1: Using np.sort() . 
Approach:
Create a NumPy array.Determine the value of k.Sort the array in ascending order using the sort() method.Print the first k values of the sorted array.
Create a NumPy array.
Determine the value of k.
Sort the array in ascending order using the sort() method.
Print the first k values of the sorted array.
Python3
# importing the modulesimport numpy as np  # creating the array arr = np.array([23, 12, 1, 3, 4, 5, 6])print("The Original Array Content")print(arr)  # value of kk = 4  # sorting the arrayarr1 = np.sort(arr)  # k smallest number of arrayprint(k, "smallest elements of the array")print(arr1[:k])
Output:
The Original Array Content
[23 12  1  3  4  5  6]
4 smallest elements of the array
[1 3 4 5]

Method 2: Using np.argpartition() 
Approach:
Create a NumPy array.Determine the value of k.Get the indexes of the smallest k elements using the argpartition() method.Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array.
Create a NumPy array.
Determine the value of k.
Get the indexes of the smallest k elements using the argpartition() method.
Fetch the first k values from the array obtained from argpartition() and print their index values with respect to the original array.
Python3
# importing the moduleimport numpy as np  # creating the array arr = np.array([23, 12, 1, 3, 4, 5, 6])print("The Original Array Content")print(arr)  # value of kk = 4  # using np.argpartition()result = np.argpartition(arr, k)  # k smallest number of arrayprint(k, "smallest elements of the array")print(arr[result[:k]])
Output:
The Original Array Content
[23 12  1  3  4  5  6]
4 smallest elements of the array
[4 3 1 5]

Python numpy-Sorting Searching
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python | os.path.join() method
How to use close() and quit() method in Selenium Python ?

06 Mar, 2020
While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.dispose method that successively closes all the browser windows and ends the WebDriver session graciously.
Syntax :
driver.close()
driver.quit()

Argument :
Both methods takes no argument
Action performed :close() method closes the current window.quit() method quits the driver instance, closing every associated window, which is opened.
# importing webdriver from seleniumfrom selenium import webdriver  # Here Chrome  will be useddriver = webdriver.Chrome()  # URL of websiteurl = "https://www.geeksforgeeks.org/"  # Opening the websitedriver.get(url)  # Closes the current windowdriver.close()
Output : The webpage will loaded then closes due to close() method.
Code for quit() method:
# importing webdriver from seleniumfrom selenium import webdriver  # Here Chrome  will be useddriver = webdriver.Chrome()  # URL of websiteurl = "https://www.geeksforgeeks.org/"  # Opening the websitedriver.get(url)  # All windows related to driver instance will quitdriver.quit()
Output : The webpage will be loaded then window get quit due to quit() method.
Python-selenium
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TensorFlow - Exporting

Here, we will focus on MetaGraph formation in TensorFlow. This will help us understand export module in TensorFlow. The MetaGraph contains the basic information, which is required to train, perform evaluation, or run inference on a previously trained graph.
Following is the code snippet for the same −
def export_meta_graph(filename = None, collection_list = None, as_text = False): 
   """this code writes `MetaGraphDef` to save_path/filename. 
   
   Arguments: 
   filename: Optional meta_graph filename including the path. collection_list: 
      List of string keys to collect. as_text: If `True`, 
      writes the meta_graph as an ASCII proto. 
   
   Returns: 
   A `MetaGraphDef` proto. """
One of the typical usage model for the same is mentioned below −
# Build the model ... 
with tf.Session() as sess: 
   # Use the model ... 
# Export the model to /tmp/my-model.meta. 
meta_graph_def = tf.train.export_meta_graph(filename = '/tmp/my-model.meta')
Print characters and their frequencies in order of occurrence in C++

This problem, We are given a string of lowercase characters. and we have to find the frequencies of each character that occurs in the string. the below example when explaining more about the problem.
Input : “jskdk”
Output :
j 1
s 1
k 2
d 1
Explanation − In the String, the characters j, s, d occur once and k occurs twice. Hence, the output printed gives the above result.
Now let's create a logic to solve this problem. As stated we have to find the frequency of occurrence of each character in the string. One logical way is to traverse the string and count the frequency of occurrence of a character and store it in an array and then print the character along with their frequency of occurrence.
Step 1 : Create an array of size 26 that stores the frequency of characters in the string.
Step 2 : print all the characters along with their frequency of occurrence from the array.
Now, let’s create a program to find the solution to this problem,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "tutorialspoint";
   int n = str.size();
   int frequency[26];
   memset(frequency, 0, sizeof(frequency));
   for (int i = 0; i < n; i++)
      frequency[str[i] - 'a']++;
   for (int i = 0; i < n; i++) {
      if (frequency[str[i] - 'a'] != 0) {
         cout<<str[i]<<"\t"<<frequency[str[i] - 'a']<<"\n";
         frequency[str[i] - 'a'] = 0;
      }
   }
   return 0;
}
t 3
u 1
o 2
r 1
i 2
a 1
l 1
s 1
p 1
n 1