code-rag-bench/online-tutorials huggingface dataset:
HBase - Count & Truncate

You can count the number of rows of a table using the count command. Its syntax is as follows:
count ‘<table name>’ 

After deleting the first row, emp table will have two rows. Verify it as shown below.
hbase(main):023:0> count 'emp'
2 row(s) in 0.090 seconds
⇒ 2 

This command disables drops and recreates a table. The syntax of truncate is as follows:
hbase> truncate 'table name'

Given below is the example of truncate command. Here we have truncated the emp table.
hbase(main):011:0> truncate 'emp'
Truncating 'one' table (it may take a while):
   - Disabling table...
   - Truncating table...
   0 row(s) in 1.5950 seconds

After truncating the table, use the scan command to verify. You will get a table with zero rows.
hbase(main):017:0> scan ‘emp’
ROW                  COLUMN + CELL
0 row(s) in 0.3110 seconds

 Print
 Add Notes
 Bookmark this page
TypeScript - String replace()

This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
The replacement string can include the following special replacement patterns −
string.replace(regexp/substr, newSubStr/function[, flags]);

regexp − A RegExp object. The match is replaced by the return value of parameter #2.
regexp − A RegExp object. The match is replaced by the return value of parameter #2.
substr − A String that is to be replaced by newSubStr.
substr − A String that is to be replaced by newSubStr.
newSubStr − The String that replaces the substring received from parameter #1.
newSubStr − The String that replaces the substring received from parameter #1.
function − A function to be invoked to create the new substring.
function − A function to be invoked to create the new substring.
flags − A String containing any combination of the RegExp flags: g
flags − A String containing any combination of the RegExp flags: g
It simply returns a new changed string.
var re = /apples/gi; 
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges"); 
console.log(newstr)

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
oranges are round, and oranges are juicy.

var re = /(\w+)\s(\w+)/; 
var str = "zara ali"; 
var newstr = str.replace(re, "$2, $1"); 
console.log(newstr);

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
ali, zara


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Find the difference between current date and the date records from a MySQL table

To find the difference, use the DATEDIFF() method. Let us first create a table −
mysql> create table DemoTable1446
   -> (
   -> DueDate date
   -> );
Query OK, 0 rows affected (1.42 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1446 values('2019-01-21');
Query OK, 1 row affected (0.69 sec)
mysql> insert into DemoTable1446 values('2019-02-01');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable1446 values('2019-09-30');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1446;
This will produce the following output −
+------------+
| DueDate    |
+------------+
| 2019-01-21 |
| 2019-02-01 |
| 2019-09-30 |
+------------+
3 rows in set (0.10 sec)
The current date is as follows −
mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2019-10-01 |
+------------+
1 row in set (0.12 sec)
Following is the query get the difference between current date and date records in the table −
mysql> select datediff(curdate(),DueDate) from DemoTable1446;
This will produce the following output −
+-----------------------------+
| datediff(curdate(),DueDate) |
+-----------------------------+
|                         253 |
|                         242 |
|                           1 |
+-----------------------------+
3 rows in set (0.00 sec)
F# - Data Types

The data types in F# can be classified as follows −
Integral types
Floating point types
Text types
Other types
The following table provides the integral data types of F#. These are basically integer data types.
42y
-11y
42uy
200uy
42s
-11s
42us
200us
42
-11
42u
200u
42L
-11L
42UL
200UL
42I
1499999
9999999
9999999
9999999
9999I
(* single byte integer *)
let x = 268.97f
let y = 312.58f
let z = x + y

printfn "x: %f" x
printfn "y: %f" y
printfn "z: %f" z

(* unsigned 8-bit natural number *)

let p = 2uy
let q = 4uy
let r = p + q

printfn "p: %i" p
printfn "q: %i" q
printfn "r: %i" r

(* signed 16-bit integer *)

let a = 12s
let b = 24s
let c = a + b

printfn "a: %i" a
printfn "b: %i" b
printfn "c: %i" c

(* signed 32-bit integer *)

let d = 212l
let e = 504l
let f = d + e

printfn "d: %i" d
printfn "e: %i" e
printfn "f: %i" f
When you compile and execute the program, it yields the following output −
x: 1
y: 2
z: 3
p: 2
q: 4
r: 6
a: 12
b: 24
c: 36
d: 212
e: 504
f: 716

The following table provides the floating point data types of F#.
42.0F
-11.0F
42.0
-11.0
42.0M
-11.0M
42N
-11N
(* 32-bit signed floating point number *)
(* 7 significant digits *)

let d = 212.098f
let e = 504.768f
let f = d + e

printfn "d: %f" d
printfn "e: %f" e
printfn "f: %f" f

(* 64-bit signed floating point number *)
(* 15-16 significant digits *)
let x = 21290.098
let y = 50446.768
let z = x + y

printfn "x: %g" x
printfn "y: %g" y
printfn "z: %g" z
When you compile and execute the program, it yields the following output −
d: 212.098000
e: 504.768000
f: 716.866000
x: 21290.1
y: 50446.8
z: 71736.9

The following table provides the text data types of F#.
'x'
'\t'
"Hello"
"World"
let choice = 'y'
let name = "Zara Ali"
let org = "Tutorials Point"

printfn "Choice: %c" choice
printfn "Name: %s" name
printfn "Organisation: %s" org
When you compile and execute the program, it yields the following output −
Choice: y
Name: Zara Ali
Organisation: Tutorials Point

The following table provides some other data types of F#.
true
false
let trueVal = true
let falseVal = false

printfn "True Value: %b" (trueVal)
printfn "False Value: %b" (falseVal)
When you compile and execute the program, it yields the following output −
True Value: true
False Value: false

 Print
 Add Notes
 Bookmark this page
RegEx in ReactJS

In this article, we are going to see how to handle the strings with RegEx handling in a React application.
A RegEx or Regular Expression is a sequence of characters that forms a search pattern and is used to check if a string contains a specified search pattern or not. It is also used to validate strings which consist of email, passwords etc.
new RegExp(pattern[, flags])
In this example, we will build an authentication React application that takes an email and password from the user and checks if they are validated or not.
We have Regex.js which contains all the regular expressions to validate the email and password for our application.
Regex.jsx
export const validEmail = new RegExp(
   '^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$'
);
export const validPassword = new RegExp('^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$');
App.jsx
import React, { useState } from 'react';
import { validEmail, validPassword } from './regex.js';

const App = () => {
   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');
   const [emailErr, setEmailErr] = useState(false);
   const [pwdError, setPwdError] = useState(false);
   const validate = () => {
      if (!validEmail.test(email)) {
         setEmailErr(true);
      }
      if (!validPassword.test(password)) {
         setPwdError(true);
      }
   };
   return (
      <div>
         <input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
         />
         <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
         />
         <div>
            <button onClick={validate}>Validate
         </div>
         {emailErr && <p>Your email is invalid</p>}
         {pwdError && <p>Your password is invalid</p>}
      </div>
   );
};
export default App;
In the above example, when the user clicks the Validate button, it checks for the validity of the email and password and displays the result accordingly.
This will produce the following result.
Plotting dates on the X-axis with Python's Matplotlib

Using Pandas, we can create a dataframe and can set the index for datetime. Using gcf().autofmt_xdate(), we will adjust the date on the X-axis.
Make the list of date_time and convert into it in date_time using pd.to_datetime().
Make the list of date_time and convert into it in date_time using pd.to_datetime().
Consider data = [1, 2, 3]
Consider data = [1, 2, 3]
Instantiate DataFrame() object, i.e., DF.
Instantiate DataFrame() object, i.e., DF.
Set the DF[‘value’] with data from step 2.
Set the DF[‘value’] with data from step 2.
Set DF.index() using date_time from step 1.
Set DF.index() using date_time from step 1.
Now plot the data frame i.e., plt.plot(DF).
Now plot the data frame i.e., plt.plot(DF).
Get the current figure and make it autofmt_xdate().
Get the current figure and make it autofmt_xdate().
Using plt.show() method, show the figure.
Using plt.show() method, show the figure.
import pandas as pd
import matplotlib.pyplot as plt

date_time = ["2021-01-01", "2021-01-02", "2021-01-03"]
date_time = pd.to_datetime(date_time)
data = [1, 2, 3]

DF = pd.DataFrame()
DF['value'] = data
DF = DF.set_index(date_time)
plt.plot(DF)
plt.gcf().autofmt_xdate()
plt.show()
PUT method – Python requests

22 Sep, 2021
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PUT request to a specified URL using requests.put() method. Before checking out the PUT method, let’s figure out what a Http PUT request is –  
PUT is a request method supported by HTTP used by the World Wide Web. The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI.  
Python’s requests module provides in-built method called put() for making a PUT request to a specified URI.Syntax –  
requests.put(url, params={key: value}, args)
Example – Let’s try making a request to httpbin’s APIs for example purposes.  
Python3
import requests # Making a PUT requestr = requests.put('https://httpbin.org / put', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.content)
save this file as request.py and through terminal run,  
python request.py
Output – 
 
 
PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). Example –  
PUT /article/{article-id}
 
POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. Example –  
POST /articles
 
 
clintra
sooda367
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by clause in MS SQL Server

24 Aug, 2020
Group by clause will be discussed in detail in this article.
There are tons of data present in the database system. Even though the data is arranged in form of a table in a proper order, the user at times wants the data in the query to be grouped for easier access. To arrange the data(columns) in form of groups, a clause named group by has to be used in the query. The group by clause arranges the data according to the columns specified in the query. The basic syntax is-
Syntax :
select select_list 
from table_name 
group by column_1 column_2 
An example is given below-Student table :
select name
from student 
group by roll number 
Output –
This way, the table can be grouped using group by clause. In real-time production, group by clause is used for generating calculations by applying aggregate functions(maximum, minimum, etc). The users often confuse group by and order by clauses. Order by clause is used to arrange the data in chronological order. Group by clause is used to arrange the data in form of groups.
For better understanding, an example is given below.
Queries using order by and group by –
select  roll number
from student 
order by name ASC 
Output –
select roll number
from student 
group by  name 
Output –
From the example, we can clearly notice the difference between group by and order by clauses. In case of order by, the names are arranged in an alphabetical order(A-Z). In case the user has to arrange from Z-A, it can be done as follows.
select 
roll number 
from 
student
order by
name DESC

The output will be arranged as follows :
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
Difference between OLAP and OLTP in DBMS
Difference between Where and Having Clause in SQL
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
TypeScript | Array map() Method

17 Feb, 2021
The Array.map() is an inbuilt TypeScript function that is used to create a new array with the results of calling a provided function on every element in this array.
Syntax: 
array.map(callback[, thisObject])
Parameter: This method accepts two parameters as mentioned above and described below: 
callback : This parameter is the function that produces an element of the new Array from an element of the current one.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns the created array. 
Below examples illustrate the Array map() method in TypeScript.Example 1: 
JavaScript
// language is TypeScript     // Driver code    var arr = [ 11, 89, 23, 7, 98 ];     // use of map() method    var val = arr.map(Math.log)          // printing element    console.log( val );
Output: 
[ 2.3978952727983707,
  4.48863636973214,
  3.1354942159291497,
  1.9459101490553132,
  4.584967478670572 ]
Example 2: 
JavaScript
// language is TypeScript     // Driver code    var arr = [2, 5, 6, 3, 8, 9];     // use of map() method        var newArr = arr.map(function(val, index){       // printing element      console.log("key : ",index, "value : ",val*val);    })
Output: 
key :  0 value :  4
key :  1 value :  25
key :  2 value :  36
key :  3 value :  9
key :  4 value :  64
key :  5 value :  81
pratikraut0000
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Types of Functions in Dart

31 Oct, 2021
The function is a set of statements that take inputs, do some specific computation, and produce output. Functions are created when certain statements are repeatedly occurring in the program and a function is created to replace them. Functions make it easy to divide the complex program into smaller sub-groups and increase the code reusability of the program. 
Basically, there are four types of functions in Dart. These are as follows:
No arguments and no return type 
With arguments and no return type 
No arguments and return type 
With arguments and with return type
Basically in this function, we do not give any argument and expect no return type. It can be better understood by an example. 
Dart
void myName(){  print("GeeksForGeeks");} void main(){  print("This is the best website for developers:");  myName();}
  So myName is the function which is void means it is not returning and anything and the empty pair of parentheses suggest that there is no argument that is passed to the function. 
Basically in this function, we are giving an argument and expect no return type. 
Dart
int myPrice(){  int price = 0;  return price;} void main(){  int Price = myPrice();  print("GeeksforGeeks is the best website for developers which costs : ${Price}/-");}
  So myPrice is the function which is int means it is returning int type and the empty pair of parentheses suggests that there is no argument which is passed to the function.
Basically in this function, we do not give any argument but expect a return type. 
Dart
myPrice(int price){  print(price);}void main(){   print("GeeksforGeeks is the best website for developers which costs : ");  myPrice(0);}
 So myPrice is the function which is void means it is not returning anything and the pair of parentheses is not empty this time that suggests that it accept an argument.  
Basically in this function, we are giving an argument and expect return type. It can we better understand by an example. 
Dart
int mySum(int firstNumber, int secondNumber){  return (firstNumber + secondNumber);}void main(){  int additionOfTwoNumber = mySum(100, 500);  print(additionOfTwoNumber);}
 So mySum is the function which is int means it is returning int type and the pair of parentheses is having two arguments which are used further in this function and then in the main function we are printing the addition of two numbers.
nosenselesstalks
Dart Function
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Row and Column Widgets
ListView Class in Flutter
Dart Tutorial
Flutter - Stack Widget
Flutter - Search Bar
How to Append or Concatenate Strings in Dart?
Container class in Flutter
WebAssembly - WASM

WebAssembly is also called wasm, which is an improvement to Javascript. It is designed to run inside browsers just like javascript and also with nodejs. You happen to get wasm output, when any high level language like C, C++, Rust is compiled.
Consider the following C program −
int factorial(int n) {
   if (n == 0) 
      return 1; 
   else 
      return n * factorial(n-1); 
}

Make use of WasmExplorer, which is available at https://mbebenita.github.io/WasmExplorer/ to get the compiled code as shown below −
The WebAssembly text format for factorial program is as stated below −
(module 
   (table 0 anyfunc) 
   (memory $0 1) 
   (export "memory" (memory $0)) (export "factorial" (func $factorial)) 
   (func $factorial (; 0 ;) (param $0 i32) (result i32)
      (local $1 i32) 
      (local $2 i32) 
      (block $label$0 
         (br_if $label$0 
            (i32.eqz 
               (get_local $0) 
            )
         )
         (set_local $2 
            (i32.const 1) 
         ) 
         (loop $label$1 
            (set_local $2 
               (i32.mul 
                  (get_local $0) (get_local $2) 
               ) 
            ) 
            (set_local $0 
               (tee_local $1        (i32.add 
                  (get_local $0) (i32.const -1) 
               ) 
               ) 
            ) 
            (br_if $label$1      (get_local $1) 
            ) 
         ) 
         (return 
            (get_local $2)
         ) 
      ) 
      (i32.const 1) 
   )
)
Using the Wat2Wasm tool, you can view the WASM code, just like how it is mentioned below −
Developers are not supposed to write code in wasm or learn to code in it, as it is mostly generated when you compile high level languages.
In WASM, all the instructions are pushed on to the stack. The arguments are popped and the result is pushed back to the stack.
Consider the following WebAssembly Text format that adds 2 numbers −
(module
   (func $add (param $a i32) (param $b i32) (result i32) 
      get_local $a 
      get_local $b 
      i32.add
   )
   (export "add" (func $add))
)
The name of the function is $add, it takes in 2 params $a and $b. The result is a type 32-bit integer. The local variables are accessed using get_local and the add operation is performed using i32.add.
The stack representation to add 2 numbers while execution will be as follows −
In step 1 − The execution of get_local $a instruction, the first parameters i.e., $a is pushed on the stack.
In step 2 − During execution of get_local $b instruction, the second parameters i.e., $b is pushed on the stack.
In step 3 − The execution of i32.add will pop the elements from the stack and will push the result back to the stack. The value that remains in the end inside the stack is the result of the function $add.
 Print
 Add Notes
 Bookmark this page
jQuery - ajaxStart( callback ) Method

The ajaxStart( callback ) method attaches a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event.
Here is the simple syntax to use this method −
$(document).ajaxStart( callback )

Here is the description of all the parameters used by this method −
callback − The function to execute.
callback − The function to execute.
Assuming we have following HTML content in result.html file −
<h1>THIS IS RESULT...</h1>

Following is a simple example a simple showing the usage of this method.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            /* Global variable */
            var count = 0;

            $("#driver").click(function(event){
               $('#stage1').load('result.html');
            });
				
            /* Gets called when request starts */
				
            $(document).ajaxStart(function(){
               count++;
               $("#stage2").html("<h1>Starts, Count :" + count + "</h1>");
            });
				
            /* Gets called when request complete */
            $(document).ajaxComplete(function(event,request,set){
               count++;
               $("#stage3").html("<h1>Completes,Count:" + count + "</h1>");
            });
				
         });
      </script>
   </head>
	
   <body>
      <p>Click on the button to load result.html file:</p>
		
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
		
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
		
      <div id = "stage3" style = "background-color:blue;">
         STAGE - 3
      </div>
		
      <input type = "button" id = "driver" value = "Load Data" />
   </body>
</html>
This will produce following result −
Click on the button to load result.html file −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Adaptive Software Development (ASD) - GeeksforGeeks

20 Nov, 2021
Adaptive Software Development is a method to build complex software and system. ASD focuses on human collaboration and self-organization. ASD “life cycle” incorporates three phases namely: 
1. Speculation
2. Collaboration
3. Learning 
These are explained as following below. 
1. Speculation: During this phase project is initiated and planning is conducted. The project plan uses project initiation information like project requirements, user needs, customer mission statement, etc, to define set of release cycles that the project wants. 
2. Collaboration: It is the difficult part of ASD as it needs the workers to be motivated. It collaborates communication and teamwork but emphasizes individualism as individual creativity plays a major role in creative thinking. People working together must trust each others to  
Criticize without animosity,
Assist without resentment,
Work as hard as possible,
Possession of skill set,
Communicate problems to find effective solution.
3. Learning: The workers may have a overestimate of their own understanding of the technology which may not lead to the desired result. Learning helps the workers to increase their level of understanding over the project. Learning process is of 3 ways: 
Focus groupsTechnical reviewsProject postmortem
Focus groups
Technical reviews
Project postmortem
ASD’s overall emphasis on the dynamics of self-organizing teams, interpersonal collaboration, and individual and team learning yield software project teams that have a much higher likelihood of success. 
singghakshay
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Software Engineering | Classical Waterfall Model
Functional vs Non Functional Requirements
Software Requirement Specification (SRS) Format
Software Engineering | Requirements Engineering Process
Differences between Verification and Validation
Software Engineering | SDLC V-Model
Levels in Data Flow Diagrams (DFD)
Software Testing Life Cycle (STLC)
Class Diagram for Library Management System
Software Engineering | Iterative Waterfall Model
Python - Extract Emails from Text

To extract emails form text, we can take of regular expression. In the below example we take help of the regular expression package to define the pattern of an email ID and then use the findall() function to retrieve those text which match this pattern.
import re
text = "Please contact us at contact@tutorialspoint.com for further information."+\
        " You can also give feedbacl at feedback@tp.com"


emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", text)
print emails

When we run the above program, we get the following output −
['contact@tutorialspoint.com', 'feedback@tp.com']


    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

CSS Attr Selectors
Tryit: The [attribute] selector
Validate the first name and last name with Java Regular Expressions

In order to match the first name and last name using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression.
Declaration −The java.lang.String.matches() method is declared as follows −
public boolean matches(String regex)
Let us see a program to validate the first name and last name with regular expressions −
 Live Demo
public class Example {
   public static void main( String[] args ) {
      System.out.println(firstName("Tom"));
      System.out.println(lastName("hanks"));
   }
   // validate first name
   public static boolean firstName( String firstName ) {
      return firstName.matches( "[A-Z][a-z]*" );
   }
   // validate last name
   public static boolean lastName( String lastName ) {
      return lastName.matches( "[A-Z]+([ '-][a-zA-Z]+)*" );
   }
}
true
false
Create Different Types of Cells

How to create different types of cells in a spreadsheet using Java.
Following is the program to create different types of cells in a spreadsheet using Java.
import java.io.File;
import java.io.FileOutputStream;

import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TypesOfCellsInExcel {
   public static void main(String[] args)throws Exception {

      //Creating a Workbook
      XSSFWorkbook workbook = new XSSFWorkbook();

      //Creating a Spread sheet
      XSSFSheet spreadsheet = workbook.createSheet("cell types");
      XSSFRow row = spreadsheet.createRow((short) 2);

      row.createCell(0).setCellValue("Type of Cell");
      row.createCell(1).setCellValue("cell value");
      row = spreadsheet.createRow((short) 3);
      
      row.createCell(0).setCellValue("set cell type BLANK");
      row.createCell(1);
      row = spreadsheet.createRow((short) 4);
      
      row.createCell(0).setCellValue("set cell type BOOLEAN");
      row.createCell(1).setCellValue(true);
      row = spreadsheet.createRow((short) 5);
      
      row.createCell(0).setCellValue("set cell type ERROR");
      row.createCell(1).setCellValue(XSSFCell.CELL_TYPE_ERROR );
      row = spreadsheet.createRow((short) 6);
      
      row.createCell(0).setCellValue("set cell type date");
      row.createCell(1).setCellValue(new Date());
      row = spreadsheet.createRow((short) 7);
      
      row.createCell(0).setCellValue("set cell type numeric" );
      row.createCell(1).setCellValue(20 );
      row = spreadsheet.createRow((short) 8);
      
      row.createCell(0).setCellValue("set cell type string");
      row.createCell(1).setCellValue("A String");
      
      FileOutputStream out = new FileOutputStream(new File("typesofcells.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("typesofcells.xlsx written successfully");
   }
}
 Print
 Add Notes
 Bookmark this page
How to animate a scatter plot in Matplotlib?

Using the FuncAnimation method of matplotlib, we can animate the diagram. We can pass a user defined method where we will be changing the position of the particles, and at the end, we will return plot type.
Get the particle's initial position, velocity, force, and size.
Get the particle's initial position, velocity, force, and size.
Create a new figure, or activate an existing figure with figsize = (7, 7).
Create a new figure, or activate an existing figure with figsize = (7, 7).
Add an axes to the current figure and make it the current axes, with xlim and ylim.
Add an axes to the current figure and make it the current axes, with xlim and ylim.
Plot scatter for initial position of the particles.
Plot scatter for initial position of the particles.
Make an animation by repeatedly calling a function *func*. We can pass a user-defined method that helps to change the position of particles, into the FuncAnimation class.
Make an animation by repeatedly calling a function *func*. We can pass a user-defined method that helps to change the position of particles, into the FuncAnimation class.
Using plt.show(), show the figure.
Using plt.show(), show the figure.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

dt = 0.005
n=20
L = 1
particles=np.zeros(n,dtype=[("position", float , 2),
                           ("velocity", float ,2),
                           ("force", float ,2),
                           ("size", float , 1)])

particles["position"]=np.random.uniform(0,L,(n,2));
particles["velocity"]=np.zeros((n,2));
particles["size"]=0.5*np.ones(n);

fig = plt.figure(figsize=(7,7))
ax = plt.axes(xlim=(0,L),ylim=(0,L))
scatter=ax.scatter(particles["position"][:,0], particles["position"][:,1])

def update(frame_number):
   particles["force"]=np.random.uniform(-2,2.,(n,2));
   particles["velocity"] = particles["velocity"] + particles["force"]*dt
   particles["position"] = particles["position"] + particles["velocity"]*dt

   particles["position"] = particles["position"]%L
   scatter.set_offsets(particles["position"])
   return scatter,

anim = FuncAnimation(fig, update, interval=10)
plt.show()
MomentJS - Checking current locale

We can check the current locale using moment.locale().
moment.locale();

moment.locale('fr');
var k = moment.locale();
moment.locale('fr');
var k = moment.locale();
moment.locale('ja');
var s = moment.locale();
moment.locales() gives the list of all the locales available for use or which are loaded. Observe the following line of code and its output −
moment.locales()
In the above example, we are using thelocale.min.js with all locales, so moment.locales() displays all the locales as shown above.
 Print
 Add Notes
 Bookmark this page
Most Frequent Number in Intervals in C++

Suppose we have a list of lists of integers intervals where each element has interval like [start, end]. We have to find the most frequently occurred number in the intervals. If there are ties, then return the smallest number.
So, if the input is like [[2, 5],[4, 6],[7, 10],[8, 10]], then the output will be 4
To solve this, we will follow these steps −
Define one map m
Define one map m
cnt := 0, val := 0
cnt := 0, val := 0
for each value it in x −(increase m[it[0]] by 1)decrease m[it[1] + 1] by 1
for each value it in x −
(increase m[it[0]] by 1)
(increase m[it[0]] by 1)
decrease m[it[1] + 1] by 1
decrease m[it[1] + 1] by 1
last := 0
last := 0
for each key it in mlast := last + value of itif last > cnt, then:cnt := lastval := it
for each key it in m
last := last + value of it
last := last + value of it
if last > cnt, then:cnt := lastval := it
if last > cnt, then:
cnt := last
cnt := last
val := it
val := it
return val
return val
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<vector<int>>& x) {
      map <int, int> m;
      int cnt = 0;
      int val = 0;
      for(auto& it : x){
         m[it[0]]++;
         m[it[1] + 1]--;
      }
      int last = 0;
      for(auto& it : m){
         last += it.second;
         if(last > cnt){
            cnt = last;
            val = it.first;
         }
      }
      return val;
   }
};
main() {
   Solution ob;
   vector<vector<int>> v = {{2, 5},{4, 6},{7, 10},{8, 10}};
   cout << ob.solve(v);
}
{{2, 5},{4, 6},{7, 10},{8, 10}}
4
Transform nested array into normal array with JavaScript?

Let’s say the following is our nested array −
const arrayObject = [
   [
      {
         Name: "John"
      },
      {
         countryName: "US"
      }
   ],
   [
      {
         subjectName: "JavaScript"
      },
      {
         teacherName: "Mike"
      }
   ]
];
To transform nested array into normal array, use the concept of flat() as in the below code −
const arrayObject = [
   [
      {
         Name: "John"
      },
      {
         countryName: "US"
      }
   ],
   [
      {
         subjectName: "JavaScript"
      },
      {
         teacherName: "Mike"
      }
   ]
];
const output = arrayObject.flat();
console.log(output);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo50.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo50.js
[
   { Name: 'John' },
   { countryName: 'US' },
   { subjectName: 'JavaScript' },
   { teacherName: 'Mike' }
]
How to MySQL SELECT by month?

To select by month, use MONTH() function. Let us first create a table −
mysql> create table DemoTable1599
   -> (
   -> Shippingdate datetime
   -> );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1599 values('2019-10-21');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1599 values('2018-12-12');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable1599 values('2015-11-21');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable1599 values('2017-12-31');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1599 values('2018-12-26');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1599;
This will produce the following output −
+---------------------+
| Shippingdate        |
+---------------------+
| 2019-10-21 00:00:00 |
| 2018-12-12 00:00:00 |
| 2015-11-21 00:00:00 |
| 2017-12-31 00:00:00 |
| 2018-12-26 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)
Following is the query to SELECT by month −
mysql> select * from DemoTable1599
   -> where month(Shippingdate)=12;
This will produce the following output −
+---------------------+
| Shippingdate        |
+---------------------+
| 2018-12-12 00:00:00 |
| 2017-12-31 00:00:00 |
| 2018-12-26 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
C# program to count number of bytes in an array

Set a byte array −
byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 };
To count number of bytes −
Buffer.ByteLength(b)
The following is the code −
 Live Demo
using System;
class Program {
   static void Main() {
      byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 };
      int len = Buffer.ByteLength(b);
      for (int i = 0; i < len; i++) {
         Console.WriteLine(b[i]);
      }
      Console.WriteLine("Length of byte array = "+len);
   }
}
5
9
19
23
29
35
55
78
Length of byte array = 8
Python Program for Binary Insertion Sort

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using the concept of binary insertion sort.
Here as the name suggests, we use the concept of the binary search along with the insertion sort algorithm.
Now let’s observe the solution in the implementation below −
 Live Demo
# sort
def insertion_sort(arr):
   for i in range(1, len(arr)):
      temp = arr[i]
      pos = binary_search(arr, temp, 0, i) + 1
      for k in range(i, pos, -1):
         arr[k] = arr[k - 1]
      arr[pos] = temp
def binary_search(arr, key, start, end):
   #key
   if end - start <= 1:
      if key < arr[start]:
         return start - 1
      else:
         return start
   mid = (start + end)//2
   if arr[mid] < key:
      return binary_search(arr, key, mid, end)
   elif arr[mid] > key:
      return binary_search(arr, key, start, mid)
   else:
      return mid
# main
arr = [1,5,3,4,8,6,3,4]
n = len(arr)
insertion_sort(arr)
print("Sorted array is:")
for i in range(n):
   print(arr[i],end=" ")
Sorted array is :
1 3 3 4 4 5 5 6 8
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for Binary Insertion Sort
Generate random string/characters in JavaScript?

To generate random string/ characters in JavaScript, use Math.random(). We are generating 6 random characters here from the following characters −
'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ';
Following is the code −
function generateRandomNumber(numberOfCharacters) {
   var randomValues = '';
   var stringValues = 'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ';  
   var sizeOfCharacter = stringValues.length;  
for (var i = 0; i < numberOfCharacters; i++) {
      randomValues = randomValues+stringValues.charAt(Math.floor(Math.random() * sizeOfCharacter));
   }
   return randomValues;
} 
console.log(generateRandomNumber(6));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo270.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo270.js
qIcoCT
sympy.stats.FDistribution() in python - GeeksforGeeks

05 Jun, 2020
With the help of sympy.stats.FDistribution() method, we can get the continuous random variable representing the F distribution.
Syntax : sympy.stats.FDistribution(name, d1, d2)Where, d1 and d2 denotes the degree of freedom.Return : Return continuous random variable.
Example #1 :In this example we can see that by using sympy.stats.FDistribution() method, we are able to get the continuous random variable which represents the F distribution by using this method.
# Import sympy and FDistributionfrom sympy.stats import FDistribution, densityfrom sympy import Symbol  d1 = Symbol("d1", integer = True, positive = True)d2 = Symbol("d2", integer = True, positive = True)z = Symbol("z")  # Using sympy.stats.FDistribution() methodX = FDistribution("x", d1, d2)gfg = density(X)(z)  pprint(gfg)
Output :
d2— ______________________________2 / d1 -d1 – d2d2 *\/ (d1*z) *(d1*z + d2)————————————–/d1 d2\z*B|–, –|\2 2 /
Example #2 :
# Import sympy and FDistributionfrom sympy.stats import FDistribution, densityfrom sympy import Symbol  d1 = 5d2 = 6z = 1  # Using sympy.stats.FDistribution() methodX = FDistribution("x", d1, d2)gfg = density(X)(z)  pprint(gfg)
Output :
____5400*\/ 55—————–1771561*B(5/2, 3)
Python SymPy-Stats
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How to take care of SSL certificate issues in chrome browser in Selenium?

We can face SSL certificate issue because of the reasons listed below −
While the website was developed, its SSL certificate was not proper.
While the website was developed, its SSL certificate was not proper.
The site may have a self-signed certificate.
The site may have a self-signed certificate.
SSL not configured properly at the server level.
SSL not configured properly at the server level.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SSLCert {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      //Desired capabilities for general chrome profile
      DesiredCapabilities c=DesiredCapabilities.chrome();
      c.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
      c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
      //ChromeOptions for local browser
      ChromeOptions ch= new ChromeOptions();
      ch.merge(c);
      System.setProperty("webdriver.chrome.driver",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver=new ChromeDriver(ch);
   }
}
Convert.ToDecimal(String, IFormatProvider) Method in C#

The Convert.ToDecimal() method in C# converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information.
Following is the syntax −
public static decimal ToDecimal (string val, IFormatProvider provider);
Above, Val is a string that contains a number to convert, whereas the provider is an object that supplies culture-specific formatting information.
Let us now see an example to implement the Convert.ToDecimal() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main() {
      CultureInfo cultures = new CultureInfo("en-US");
      String val = "8787";
      Console.WriteLine("Converted Decimal value...");
      decimal res = Convert.ToDecimal(val, cultures);
      Console.Write("{0}", res);
   }
}
This will produce the following output −
Converted Decimal value...
8787
C# Program to convert Digits to Words

Firstly, declare the words from 0 to 9 −
// words for every digits from 0 to 9
string[] digits_words = { "zero", "one", "two",
   "three", "four", "five",
   "six", "seven", "eight",
   "nine"
};
The following are the digits to be converted to words −
// number to be converted into words
val = 4677;
Console.WriteLine("Number: " + val);
Use the loop to check for every digit in the given number and convert into words −
do {
   next = val % 10;
   a[num_digits] = next;
   num_digits++;
   val = val / 10;
} while(val > 0);
You can try to run the following code to converts digits to words.
Live Demo
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int val, next, num_digits;
         int[] a = new int[10];
         // words for every digits from 0 to 9
         string[] digits_words = {
            "zero",
            "one",
            "two",
            "three",
            "four",
            "five",
            "six",
            "seven",
            "eight",
            "nine"
         };
         // number to be converted into words
         val = 4677;
         Console.WriteLine("Number: " + val);
         Console.Write("Number (words): ");
         next = 0;
         num_digits = 0;
         do {
            next = val % 10;
            a[num_digits] = next;
            num_digits++;
            val = val / 10;
         } while (val > 0);
         num_digits--;
         for (; num_digits >= 0; num_digits--)
         Console.Write(digits_words[a[num_digits]] + " ");
         Console.ReadLine();
      }
   }
}
Number: 4677
Number (words): four six seven seven
How to create a responsive navigation bar with dropdown in CSS?

Following is the code to create a responsive navigation bar with dropdown −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
*,*::after,*::before{
   box-sizing: border-box;
}
.menu-btn {
   font-size: 18px;
   font-weight: bold;
   display: inline-block;
   text-align: center;
   background-color: #040008;
   color: white;
   padding: 20px;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   border: none;
   width: 100%;
}
.dropdown-menu {
   position: relative;
   display: inline-block;
}
.menu-content {
   display: none;
   position: absolute;
   width: 100%;
   background-color: #017575;
   min-width: 160px;
   z-index: 1;
}
nav{
   background-color: #017575;
   width: 100%;
}
.links,.links-hidden{
   display: inline-block;
   color: rgb(255, 255, 255);
   text-decoration: none;
   font-size: 18px;
   font-weight: bold;
   padding: 20px;
}
.links-hidden:hover,.links:hover {
   background-color: rgb(8, 107, 46);
}
.dropdown-menu:hover .menu-content {
   display: block;
}
.dropdown-menu:hover .menu-btn {
   background-color: #3e8e41;
}
.hamburger {
   color: white;
   font-weight: bolder;
   display: none;
}
@media screen and (max-width: 880px) {
      nav a:not(:first-child) {
      display: none;
   }
   nav a.hamburger {
      float: right;
      display: block;
      padding: 12px;
   }
   .dropdown-menu{
      display: none;
   }
   nav.openNav a.hamburger {
      position: relative;
   }
   nav.openNav a {
      float: none;
      display: block;
      text-align: center;
   }
}
nav.openNav div.dropdown-menu{
   display: block;
   width: 100%;
}
</style>
</head>
<body>
<nav>
<a class="links" href="#">HOME</a>
<a class="links" href="#">EMPLOYEES</a>
<a class="links" href="#">CAREER</a>
<a class="links" href="#">Our History</a>
<a class="links" href="#">Fund Us</a>
<a class="links" href="#">More Info</a>
<div class="dropdown-menu">
<button class="menu-btn">Open <</button>
<div class="menu-content">
<a class="links-hidden" href="#">Contact Us</a>
<a class="links-hidden" href="#">Visit Us</a>
<a class="links-hidden" href="#">About Us</a>
</div>
</div>
<a class="hamburger">☰</a>
</nav>
<script>
var x = document.getElementsByTagName("nav")[0];
function toggleNav() {
   if (x.className === "") {
      x.className = " openNav";
   } else {
      x.className = "";
   }
}
document.querySelector(".hamburger").addEventListener("click", toggleNav);
</script>
</body>
</html>
The above code will produce the following output −
On resizing the window to 880px or less −
On opening the hamburger menu and then the dropdown −