code-rag-bench/online-tutorials huggingface dataset:
IntFunction Interface in Java with Examples

08 Oct, 2018
The IntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and produces a result of type R.
This functional interface takes in only one generic, namely:-
R: denotes the type of the output of this function
The lambda expression assigned to an object of IntFunction type is used to define its apply() which eventually applies the given operation on its only argument. It is similar to using an object of type Function<Integer, R>.
The IntFunction interface has only one function:
This method accepts an int-valued argument and gives a result of type R.
Syntax:
R apply(int value)
Parameters: This method takes in one parameter value which is an int-valued argument.
Returns: This method returns a value of type R.
Below is the code to illustrate apply() method:
Program
import java.util.function.IntFunction;  public class Main {    public static void main(String args[])    {        IntFunction<Double> ob = a -> a / 2.0;          // Using apply() method        System.out.println(ob.apply(3));    }}
1.5

Java - util package
Java 8
java-basics
java-interfaces
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
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
time.perf_counter() function in Python

In this tutorial, we are going to learn about the time.perf_counter() method.
The method time.perf_counter() returns a float value of time in seconds. Let's see an
 Live Demo
# importing the time module
import time
# printing the time
print(time.perf_counter())
If you run the above code, then you will get the following result.
263.3530349
We can use the time.perf_counter() method to find the execution time of a program. Let's see an example.
 Live Demo
# importing the time module
import time
# program to find the prime number
def is_prime(number):
   for i in range(2, number):
      if number % i == 0:
         return False
         return True
if __name__ == '__main__':
   number = 17377
   start_time = time.perf_counter()
   is_prime(number)
   end_time = time.perf_counter()
# printing the executing time by difference
print(end_time - start_time)
If you execute the above program, then you will get the following result.
0.004171799999994619
If you have any doubts in the tutorial, mention them in the comment section.
SQL Query Complexity

17 Jun, 2020
Structured Query Language (SQL) is the language that is used to query Relational Databases. A typical Relational Database consists of tables, where each table has rows and columns. Every column has data of particular type. Factor dependent on SQL query complexity.
Example –
select * 
from employee 
where id = 77
There are three different way that query could find the result –
O(1) — hash index on id, or cached result on id = 77 from previous query.O(n) – Do a full scan and look at each and every row and could not find any result.O(log(n)) – Sort the id and do a binary search.
O(1) — hash index on id, or cached result on id = 77 from previous query.
O(n) – Do a full scan and look at each and every row and could not find any result.
O(log(n)) – Sort the id and do a binary search.
The complexity of the query totally depends upon the SQL engine how it will process the query. If our employee table has 100000000000 rows of data and we need to find out the row where employee id is 77. If we scan the whole table then it would take a long time. If we sort the table and do a binary search on this table then we need about 36 lookups (log base 2 of 100000000000 is ~36) to find out our value. But to sort the table would take a while. It totally depends upon the optimiser of the sql engine.
I would recommend this if you want to know more about SQL engine query processing.
Things to keep in mind while writing good query :
Limit your result –When you can not avoid filtering down your select statement, then you can consider limiting your result. You can limit your result by using limit, topExample –select TOP 3 
from employeeselect * 
from employee limit 10
Example –
select TOP 3 
from employee
select * 
from employee limit 10
Don’t make the query to be more complex. Try to keep them simple and efficient.Example –Consider the following query:select * 
from employee 
where id = 77 or id = 85 or id = 69So, you can replace the operator by using INselect * 
from employee 
where id in (77, 85, 69)
Example –Consider the following query:
select * 
from employee 
where id = 77 or id = 85 or id = 69
So, you can replace the operator by using IN
select * 
from employee 
where id in (77, 85, 69)
select * to be avoided especially when you have a join as at least one column twice which is waste full of server, database and network resources.
Understand aggregates stop thinking about loops.Aggregates like – count, avg etc.
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript - Complementary Colors Builder

We are required to write a JavaScript function that takes in hex color as one and only input.
Our function should then find the complementary color for the color taken in as input.
Here are some input and output pairs −
getComplementaryColor('#142814') = '#ebd7eb';
getComplementaryColor('#ffffff') = '#000000';
getComplementaryColor('#3399ff') = '#cc6600';
The code for this will be −
const str1 = '#142814';
const str2 = '#ffffff';
const str3 = '#3399ff';
const getComplementaryColor = (color = '') => {
   const colorPart = color.slice(1);
   const ind = parseInt(colorPart, 16);
   let iter = ((1 << 4 * colorPart.length) - 1 - ind).toString(16);
   while (iter.length < colorPart.length) {
      iter = '0' + iter;
   };
   return '#' + iter;
};
console.log(getComplementaryColor(str1));
console.log(getComplementaryColor(str2));
console.log(getComplementaryColor(str3));
And the output in the console will be −
#ebd7eb
#000000
#cc6600
SQL - SQRT Function

SQL SQRT function is used to find out the square root of any number. You can Use SELECT statement to find out square root of any number as follows −
SQL>  select SQRT(16);
+----------+
| SQRT(16) |
+----------+
| 4.000000 |
+----------+
1 row in set (0.00 sec)
You are seeing float value here because internally SQL will manipulate square root in float data type.
You can use SQRT function to find out square root of various records as well. To understand SQRT function in more detail consider, an employee_tbl, table which is having the following records −
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id   | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|    1 | John | 2007-01-24 |                250 |
|    2 | Ram  | 2007-05-27 |                220 |
|    3 | Jack | 2007-05-06 |                170 |
|    3 | Jack | 2007-04-06 |                100 |
|    4 | Jill | 2007-04-06 |                220 |
|    5 | Zara | 2007-06-06 |                300 |
|    5 | Zara | 2007-02-06 |                350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now suppose based on the above table you want to calculate square root  of all the dialy_typing_pages, then you can do so by using the following command −
SQL> SELECT name, SQRT(daily_typing_pages)
   -> FROM employee_tbl;
+------+--------------------------+
| name | SQRT(daily_typing_pages) |
+------+--------------------------+
| John |                15.811388 |
| Ram  |                14.832397 |
| Jack |                13.038405 |
| Jack |                10.000000 |
| Jill |                14.832397 |
| Zara |                17.320508 |
| Zara |                18.708287 |
+------+--------------------------+
7 rows in set (0.00 sec)

    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Concatenation process in DFA - GeeksforGeeks

04 Jan, 2022
Prerequisite – Designing finite automata Designing a DFA for the set of string over {a, b} such that string of the language start with “a” and end with “b”. There two desired language will be formed: 
L1 = {a, aab, aabab, .......}
L2 = {b, bbab, bbabab, .......} 
In L1, starting element is “a” and in L2, ending element is b. 
State Transition Diagram for the language L1: 
This DFA accepts all the string which starts with “a”. Here, state C is the final state and B is the dead state this is called so because after getting any alphabet this state will never go to final state. 
State Transition Diagram for the language L2: 
This DFA accepts all the string ending with alphabet “b”. Here, State B is called final state. 
Now, Taking the concatenation of L1 and L2 language which gives the final result of the language which starts with “a” and end with “b”. 
State Transition Diagram of L1.L2 i.e, L1 concat L2:  
This DFA accept all the string which start with a and end with b. Here, State C is the final state and D is the dead state this is called so because after getting any input alphabet it will never go to final state. 
simmytarika5
varshagumber28
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Difference between DFA and NFA
Regular expression to ∈-NFA
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages
Java Program to Convert Celsius into Fahrenheit - GeeksforGeeks

24 Nov, 2020
Celsius scale is a temperature scale that is based on the freezing point of water at 0 °C and the boiling point of water at 100 °C. Fahrenheit scale is a temperature scale that has a freezing point of water at 32 °F and the boiling point of water at 212 °F.
Examples:
Input : 0
Output: 32
Input :-40
Output:-40

 fahrenheit=(celsius*1.8)+32
Approach:
Initializing value of celsius as 10.0 and Fahrenheit value as 0.0Calculate the Fahrenheit using the below formulaFahrenheit=(celsius*1.8)+32;Display Fahrenheit.
Initializing value of celsius as 10.0 and Fahrenheit value as 0.0
Calculate the Fahrenheit using the below formula
Fahrenheit=(celsius*1.8)+32;
Display Fahrenheit.
Below is the implementation of the above approach:
Java
// Java Program to Convert Celsius into Fahrenheitclass celsiustofahrenheit {    public static void main(String[] args)    {        // initialising        double celsius = 10.0, fahrenheit = 0.0;                // formula for conversion        fahrenheit = (celsius * 1.8) + 32;        System.out.println(            " value of temperature in fahrenheit:"            + fahrenheit);    }}
 value of temperature in fahrenheit:50.0
Time Complexity: O(1)
Space Complexity: O(1)
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
How to get the list of font family (or Name of Fonts) in Matplotlib?

o get the list of font family in Matplotlib, we can take the following steps −
Iterate fonts manager ttflist and print the names.
Iterate fonts manager afmlist and print the names.
import matplotlib.font_manager as fm
for f in fm.fontManager.ttflist:
   print(f.name)
for f in fm.fontManager.afmlist:
   print(f.name)
STIXNonUnicode
STIXGeneral
STIXSizeFiveSym
cmr10
...
...
...
Nimbus Sans L
Bitstream Charter
Nimbus Sans L
Nimbus Sans L
Can we add a column to a table from another table in MySQL?

Yes, we can add a column to a table from another table. Let us first create two tables. The query to create a table is as follows −
<FirstTable>
mysql> create table FirstTable
   -> ( 
   -> UserId int,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (1.48 sec)
Now create the second table. The query to create the second table is as follows −
<SecondTable>
mysql> create table SecondTable
   -> (
   -> UserId int,
   -> UserAge int
   -> );
Query OK, 0 rows affected (1.57 sec)
Now, add column Age to the first table. Firstly, add the Age column, then use UPDATE command to set this Age column to the UserAge column of the SecondTable. The query is as follows −
mysql> ALTER TABLE FirstTable ADD COLUMN Age TINYINT UNSIGNED DEFAULT 0;
Query OK, 0 rows affected (1.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now here is the query to update the first table to set the Age column to the UserAge column of the SecondTable. The query is as follows −
mysql> UPDATE FirstTable tbl1
   -> INNER JOIN SecondTable tbl2 ON tbl1.UserId = tbl2.UserId
   -> SET tbl1.Age = tbl2.UserAge;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
Now check the description of the first table with the help of DESC command. The query is as follows −
mysql> desc FirstTable;
The following is the output displaying that we successfully added a column from the other table −
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| UserId   | int(11)             | YES  |     | NULL    |       |
| UserName | varchar(20)         | YES  |     | NULL    |       |
| Age      | tinyint(3) unsigned | YES  |     | 0       |       |
+----------+---------------------+------+-----+---------+-------+
3 rows in set (0.53 sec)
Firebase - Queries

Firebase offers various ways of ordering data. In this chapter, we will show simple query examples. We will use the same data from our previous chapters.
To order data by name, we can use the following code.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");

playersRef.orderByChild("name").on("child_added", function(data) {
   console.log(data.val().name);
});
We will see names in the alphabetic order.
We can order data by key in a similar fashion.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");

playersRef.orderByKey().on("child_added", function(data) {
   console.log(data.key);
});
The output will be as shown below.
We can also order data by value. Let us add the ratings collection in Firebase.
Now we can order data by value for each player.
Let us consider the following example.
var ratingRef = firebase.database().ref("ratings/");

ratingRef.orderByValue().on("value", function(data) {
   
   data.forEach(function(data) {
      console.log("The " + data.key + " rating is " + data.val());
   });
   
});
The output will be as shown below.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
What is unsigned Right Shift Operator (>>>) in JavaScript?

This operator is just like the >>operator, except that the bits shifted in on the left are always zero i.e. xeroes are filled in from the left.
You can try to run the following code to learn how to work with unsigned right shift operator −
<html>
   <body>
      <script>
         var a =-14;
         var b =2; // Shift right two bits

         document.write("(a >>> b) => ");
         result =(a >>> b);
         document.write(result);
      </script>
   </body>
</html>
Merge Intervals in Python

Suppose we have a collection of intervals, we have to merge all overlapping intervals. So if the intervals are like [[1,3], [2,6], [8,10], [15,18]], then the intervals after merging will be [[1,6],[8,10],[15,18]]. This is because there were two intervals those are overlapping, the intervals are [1,3] and [2,6], these are merged to [1,6]
Let us see the steps −
if interval list length is 0, then return a blank list
sort the interval list using quicksort mechanism
stack := an empty stack, and insert intervals[0] into the stack
for i in range 1 to length of intervals – 1last_element := top element of stackif end of last_element >= first element of intervals[i], thenend of last_element = max of end of intervals[i], and end of last_elementpop element from stackpush last_element into stackelse push intervals[i] into stack
last_element := top element of stack
if end of last_element >= first element of intervals[i], thenend of last_element = max of end of intervals[i], and end of last_elementpop element from stackpush last_element into stack
end of last_element = max of end of intervals[i], and end of last_element
pop element from stack
push last_element into stack
else push intervals[i] into stack
return stack
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def merge(self, intervals):
      """
      :type intervals: List[Interval]
      :rtype: List[Interval]
      """
      if len(intervals) == 0:
         return []
      self.quicksort(intervals,0,len(intervals)-1)
      #for i in intervals:
         #print(i.start, i.end)
      stack = []
      stack.append(intervals[0])
      for i in range(1,len(intervals)):
         last_element= stack[len(stack)-1]
         if last_element[1] >= intervals[i][0]:
            last_element[1] = max(intervals[i][1],last_element[1])
            stack.pop(len(stack)-1)
            stack.append(last_element)
         else:
            stack.append(intervals[i])
      return stack
   def partition(self,array,start,end):
      pivot_index = start
      for i in range(start,end):
         if array[i][0]<=array[end][0]:
            array[i],array[pivot_index] =array[pivot_index],array[i]
            pivot_index+=1
      array[end],array[pivot_index] =array[pivot_index],array[end]
      return pivot_index
   def quicksort(self,array,start,end):
      if start<end:
         partition_index = self.partition(array,start,end)
         self.quicksort(array,start,partition_index-1)
         self.quicksort(array, partition_index + 1, end)
ob1 = Solution()
print(ob1.merge([[1,3],[2,6],[8,10],[15,18]]))
[[1,3],[2,6],[8,10],[15,18]]
[[1, 6], [8, 10], [15, 18]]
How to check if a string has at least one letter and one number in Python?

The easiest way to check this in python is to use regular expressions. In order to check if the given string has atleast one letter and one number, we use re.match(regex, string).
import re
print(bool(re.match('^(?=.*[0-9]$)(?=.*[a-zA-Z])', 'hasAlphanum123')))
print(bool(re.match('^(?=.*[0-9])(?=.*[a-zA-Z]$)', 'some string')))
True
False
The ?= syntax is used to call lookaheads in regular expressions. Lookaheads actually look ahead in the string from the current position to find matches in the given string. You can read more about them <a href="http://www.rexegg.com/regex-lookarounds.html" target="_blank">here</a>.
We can also check for one letter and one number using a simple for loop and 2 flags. 
def validateString(s):
    letter_flag = False
    number_flag = False
    for i in s:
        if i.isalpha():
            letter_flag = True
        if i.isdigit():
            number_flag = True
    return letter_flag and number_flag
print validateString('hasAlphanum23')
print validateString('some string')
This gives us the output −
True
False
Recursion - GeeksforGeeks

01 Jun, 2021
Recursion : The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.... Read More
Fun(2) = 2 * Fun(3) and Fun(3) = 2 * Fun(4) ....(i)
Fun(4) = 4 ......(ii)
From equation (i) and (ii),
Fun(2) = 2 * 2 * Fun(4)
Fun(2) = 2 * 2 * 4
Fun(2) = 16. 

So, C is the correct answer
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
SQLAlchemy Core - Creating Table
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
How to generate random strings with upper case letters and digits in Python?

You can use random.choice(list_of_choices) to get a random character. Then loop over this and get a list and finally join this list to get a string. The list of choices here is Upper case letters and digits. For example:
import string
import random
def get_random_string(length):
    random_list = []
    for i in xrange(length):
        random_list.append(random.choice(string.ascii_uppercase + string.digits))
    return ''.join(random_list)
print get_random_string(10)
This will give us the output:
'35WO8ZYKFV'
This can also be achieved in a single line:
>>> ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in xrange(10))
'35WO8ZYKFV'
In Python 3, we have a random. choices method which takes the second argument as the length of random string. It can be used to get an even shorter version:
>>> ''.join(random.choices(string.ascii_uppercase + string.digits), k=10)
'35WO8ZYKFV'
The New Line - Java | Practice | GeeksforGeeks

You are familiar with producing output using JAVA In this task, you'll be required to write three messages in three separate lines. Write Geeks for Geeks. But wait a minute!! You need to write each word of it in a separate line.
In the function printIndividualLine(), output each word of Geeks for Geeks in a separate line.
Hint: System.out.println() might be useful here!
Example:
Input:
No input

Output:
Geeks
for
Geeks

Explanation:
First word of the statment is in first line, 
next word is in next line and last is in last line.
0
kumarvishal2769718 hours ago
System.out.println("Geeks/nfor/nGeeks");
0
arpandutta5033 weeks ago
System.out.println ("Geeks/n for/n Geeks");
+1
ddarshu7713 weeks ago
Darshan K R
System.out.println("Geeks \n for \n Geeks");
+1
indhu64771 month ago
System.out.println("Geeks\nfor\nGeeks\n");
0
sachinmishraravi1 month ago
       System.out.println("Geeks");       System.out.println("for");       System.out.println("Geeks");
0
shubhambmatere1 month ago
System.out.println("Geeks\nfor\nGeeks");
0
ravi119033852 months ago
System.out.println("Geeks\nfor\nGeeks");
0
biranchidutta20043 months ago
static void printIndividualLine(){              // Your code here       System.out.println("Geeks \nfor \nGeeks");          }
0
ghodeswapnil733 months ago
System.out.println("Geeks");
System.out.println("for");
System.out.println("Geeks");
0
zakarian17s3 months ago
    static void printIndividualLine(){
        System.out.print("Geeks\nfor\nGeeks");
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Find the Kth Node from the end in a given singly Linked List using C++

A linked list is a linear data structure that has multiple nodes that are connected with each other. Each node consists of two fields Data Field and address of the next node. Let us assume we have given a singly linked list the task is to find the kth node from the end in a given singly linked list. For example,
Input −
1→2→3→4→7→8→9
K= 4
Output −
Node from the 4th Position is − 4
Explanation − Since in the given singly linked list ‘4th’ node from the end is ‘4’, we will return the output as ‘4’.
Initially, we have given a linked list that consists of nodes. Each node contains the data and address to the next node. So, to find the kth node from the end, we will take two pointers which initially points to the head of the linked list.
While iterating over the linked list, we will move one of the pointers let’s say ‘fast’, and then move the other pointer until the ‘fast’ pointer doesn't reach the end.
A Function kthNodefromTheEnd(node*head, int pos) takes the pointer to the head node and the position as a parameter and returns the node from the end.
A Function kthNodefromTheEnd(node*head, int pos) takes the pointer to the head node and the position as a parameter and returns the node from the end.
Let’s take two pointers ‘slow’ and ‘fast’ which are initially at the head.
Let’s take two pointers ‘slow’ and ‘fast’ which are initially at the head.
Iterate over the linked list and move the fast pointer.
Iterate over the linked list and move the fast pointer.
Since the ‘fast’ pointer is two steps ahead of ‘slow’ let us move both pointers until ‘fast’ reaches the end.
Since the ‘fast’ pointer is two steps ahead of ‘slow’ let us move both pointers until ‘fast’ reaches the end.
Now return the value at slow which points to the kth node from the end.
Now return the value at slow which points to the kth node from the end.
 Live Demo
#include<iostream>
using namespace std;
class node{
public:
   int data;
   node*next;
   node(int d){
      data=d;
      next=NULL;
   }
};
void insertAthead(node*&head,int d){
   node*n= new node(d);
   n->next= head;
   head=n;
}
void printList(node*head){
   while(head!=NULL){
      cout<<head->data<<"-->";
      head= head->next;
   }
}
void kthFromtheEnd(node*head, int k){
   node*slow= head;
   node*fast= head;
   for(int i=0;i<k;i++){
      fast= fast->next;
   }
   while(fast!=NULL){
      slow= slow->next;
      fast= fast->next;
   }
   cout<<"Node from the "<<k<<"th position is"<<slow->data<<endl;
}
int main(){
   node*head= NULL;
   insertAthead(head,2);
   insertAthead(head,4);
   insertAthead(head,5);
   insertAthead(head,6);
   insertAthead(head,7);
   printList(head);
   cout<<endl;
   kthFromtheEnd(head,4);
   return 0;
}
Running the above code will generate the output as,
Node from the 4th position is: 6
Explanation − The given linked list is 7→ 6→ 5→ 4→ 2→ and the kth value is ‘4’. So, the 4th node from the end is ‘6’, thus we will return ‘6’.
numpy.sqrt() in Python - GeeksforGeeks

27 Sep, 2019
numpy.sqrt(array[, out]) function is used to determine the positive square-root of an array, element-wise.
Syntax: numpy.sqrt()
Parameters:array : [array_like] Input values whose square-roots have to be determined.out : [ndarray, optional] Alternate array object in which to put the result; if provided, it must have the same shape as arr.
Returns : [ndarray] Returns the square root of the number in an array.
Code #1 :
# Python program explaining# numpy.sqrt() method   # importing numpyimport numpy as geek   # applying sqrt() method on integer numbers arr1 = geek.sqrt([1, 4, 9, 16])arr2 = geek.sqrt([6, 10, 18])  print("square-root of an array1  : ", arr1)print("square-root of an array2  : ", arr2)
square-root of an array1  :  [ 1.  2.  3.  4.]
square-root of an array2  :  [ 2.44948974  3.16227766  4.24264069]

 Code #2 :
# Python program explaining# numpy.sqrt() method   # importing numpyimport numpy as geek   # applying sqrt() method on complex numbersarr = geek.sqrt([4, -1, -5 + 9J])  print("square-root of an array  : ", arr)
square-root of an array  :  [ 2.00000000+0.j  0.00000000+1.j  1.62721083+2.76546833j]

 Code #3 :
# Python program explaining# numpy.sqrt() method   # importing numpyimport numpy as geek   # applying sqrt() method on negative element of real numbers arr = geek.sqrt([-4, 5, -6])  print("square-root of an array  : ", arr)
RuntimeWarning: invalid value encountered in sqrt
square-root of an array  :  [ nan  2.23606798  nan]

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How can we split the name string into two parts by using MySQL SUBSTRING_INDEX() function?

To make it understand, we are using the following data from a table named ‘customerdetail’.
mysql> Select * from Customerdetail;
+----------------------+----------------------+-----------+---------------------+
| Name                 | FName                | Address   | Emailid             |
+----------------------+----------------------+-----------+---------------------+
| Advik Jhamb          | Lovkesh Jhamb        | Mumbai    | Advik@gmail.com     |
| Chirag Jai Patil     | Raman Jai Patil      | Gujrat    | chirahp@yahoo.com   |
| Devansh Singh Rajput | Kishore Singh Rajput | Rajasthan | Devansh@Hotmail.com |
| Mitul Kumar Sharma   | Om Veer Sharma       | Patiala   | Mitul@gmail.com     |
+----------------------+----------------------+-----------+---------------------+
4 rows in set (0.00 sec)
Now, suppose if we want to split the name into two parts, ‘First_name’ and ‘Last_name’ then it can be done with the help of the following query −
mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1) AS First_Name, TRIM( SUBSTR(Name, LOCATE(' ', Name)) ) AS Last_Name FROM Customerdetail;
+------------+--------------+
| First_Name | Last_Name    |
+------------+--------------+
| Advik      | Jhamb        |
| Chirag     | Jai Patil    |
| Devansh    | Singh Rajput |
| Mitul      | Kumar Sharma |
+------------+--------------+
4 rows in set (0.00 sec)
From the result set of above query, it is clear that the name has been divided into two parts. It considers the middle name as a part of the last name.
Python - Assign values to initialized dictionary keys - GeeksforGeeks

06 Mar, 2020
Sometimes, while working with python dictionaries, we can have a problem in which we need to initialize dictionary keys with values. We save a mesh of keys to be initialized. This usually happens during web development while working with JSON data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using dict() + zip()The combination of above methods can be used to perform this task. In this, we allot the list values to already constructed mesh and zip() helps in mapping values as per list index.
# Python3 code to demonstrate working of # Assign values to initialized dictionary keys# using dict() + zip()    # initializing dictionary test_dict = {'gfg' : '', 'is' : '', 'best' : ''}   # Initializing list test_list = ['A', 'B', 'C']    # printing original dictionary print("The original dictionary is : " + str(test_dict))   # Assign values to initialized dictionary keys# using dict() + zip()res = dict(zip(test_dict, test_list))    # printing result  print("The assigned value dictionary is : " + str(res)) 
The original dictionary is : {'is': '', 'best': '', 'gfg': ''}
The assigned value dictionary is : {'gfg': 'C', 'best': 'B', 'is': 'A'}

 
Method #2 : Using loop + zip()This is extended way in which this task can be performed. In this, we iterate through the zipped list and assign value to dictionary.
# Python3 code to demonstrate working of # Assign values to initialized dictionary keys# using loop + zip()    # initializing dictionary test_dict = {'gfg' : '', 'is' : '', 'best' : ''}   # Initializing list test_list = ['A', 'B', 'C']    # printing original dictionary print("The original dictionary is : " + str(test_dict))   # Assign values to initialized dictionary keys# using loop + zip()for key, val in zip(test_dict, test_list):    test_dict[key] = val    # printing result  print("The assigned value dictionary is : " + str(test_dict)) 
The original dictionary is : {'is': '', 'best': '', 'gfg': ''}
The assigned value dictionary is : {'gfg': 'C', 'best': 'B', 'is': 'A'}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
PostgreSQL - NOT IN operator - GeeksforGeeks

28 Aug, 2020
The PostgreSQL NOT IN operator works exactly opposite to that of the IN operator. It is used to filter query results excluding the specified values from the list of values.
The syntax for using NOT IN operator with the WHERE clause to check against a list of values (except for the specified values) which returns a boolean value depending upon the match is as below:
Syntax: value NOT IN (value1, value2, ...)
The syntax for using NOT IN operator to return the matching values(except for the specified values) in contrast with the SELECT statement is as below:
Syntax: value NOT IN (SELECT value FROM tbl_name);
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.
Now, let’s look into a few examples.Example 1:Here we will query for all rentals where the customer_id is not 10 or 12, from the “rental” table in our sample database.
SELECT
    customer_id,
    rental_id,
    return_date
FROM
    rental
WHERE
    customer_id NOT IN (10, 12);
Output:
Example 2:Here we will query for all customers where the customer_id is not 10 or 12, from the “customer” table in our sample database.
SELECT
    customer_id,
    first_name,
    last_name
FROM
    customer
WHERE
    customer_id NOT IN (10, 12);
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - TIME Data Type
PostgreSQL - Cursor
PostgreSQL - SELECT
PostgreSQL - RENAME COLUMN
Python | Max/Min of tuple dictionary values - GeeksforGeeks

24 Oct, 2019
Sometimes, while working with data, we can have a problem in which we need to find the min/max of tuple elements that are received as values of dictionary. We may have a problem to get index wise min/max. Let’s discuss certain ways in which this particular problem can be solved.
Method #1 : Using tuple() + min()/max() + zip() + values()The combination of above methods can be used to perform this particular task. In this, we justzip together equi index values extracted by values() using zip(). Then find min/max value using respective function. Finally result is returned as index wise max/min values as a tuple.
# Python3 code to demonstrate working of# Max / Min of tuple dictionary values# Using tuple() + min()/max() + zip() + values()  # Initializing dictionarytest_dict = {'gfg' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Max / Min of tuple dictionary values# Using tuple() + min()/max() + zip() + values()res = tuple(max(x) for x in zip(*test_dict.values()))  # printing resultprint("The maximum values from each index is : " + str(res))
The original dictionary is : {'is': (8, 3, 2), 'gfg': (5, 6, 1), 'best': (1, 4, 9)}
The maximum values from each index is : (8, 6, 9)

 
Method #2 : Using tuple() + map() + values() + * operatorThis is yet another way in which this task can be performed. The difference is that we use map() instead of loop and * operator for zipping the values together.
# Python3 code to demonstrate working of# Max / Min of tuple dictionary values# Using tuple() + map() + values() + * operator  # Initializing dictionarytest_dict = {'gfg' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Max / Min of tuple dictionary values# Using tuple() + map() + values() + * operatorres = tuple(map(min, *test_dict.values()))  # printing resultprint("The minimum values from each index is : " + str(res))
The original dictionary is : {'is': (8, 3, 2), 'gfg': (5, 6, 1), 'best': (1, 4, 9)}
The minimum values from each index is : (1, 3, 1)

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to write an if-else statement in a JSP page?

The if...else block starts out as an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between the Scriptlet tags.
 Live Demo
<%! int day = 3; %>
<html>
   <head>
      <title>IF...ELSE Example</title>
   </head>
   <body>
      <% if (day == 1 || day == 7) { %>
         <p> Today is weekend</p>
      <% } else { %>
         <p> Today is not weekend</p>
      <% } %>
   </body>
</html>
The above code will generate the following result −
Today is not weekend
Bubble Sort program in C#

Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.
Let’s say our int has 5 elements −
int[] arr = { 78, 55, 45, 98, 13 };
Now, let us perform Bubble Sort.
Start with the first two elements 78 and 55. 55 is smaller than 78, so swap both of them. Now the list is −
55, 78,45,98, 13
Now 45 is less than 78, so swap it.
55, 45, 78, 98, 3
Now 98 is greater than 78, so keep as it is.
3 is less than 98, so swap it. Now the list looks like −
55, 45, 78, 3, 98
This was the first iteration. After performing all the iterations, e will get our sorted array using Bubble Sort −
3, 45, 55, 78, 93
Let us see an example with 10 elements in an array and sort it.
Live Demo
using System;
namespace BubbleSort {
   class MySort {
      static void Main(string[] args) {
         int[] arr = { 78, 55, 45, 98, 13 };
         int temp;
         for (int j = 0; j <= arr.Length - 2; j++) {
            for (int i = 0; i <= arr.Length - 2; i++) {
               if (arr[i] > arr[i + 1]) {
                  temp= arr[i + 1];
                  arr[i + 1] = arr[i];
                  arr[i] = temp;
               }
            }
         }
         Console.WriteLine("Sorted:");
         foreach (int p in arr)
            Console.Write(p + " ");
         Console.Read();
      }
   }
}
Sorted:
13 45 55 78 98
How to create and run Node.js project in VS code editor ? - GeeksforGeeks

24 Aug, 2021
Following are some simple steps in order to create a simple NodeJS project and running it in VS Code editor.
Step 1: Create an empty folder and move it into that folder from your VS Code editor, use the following command.
mkdir demo
cd demo
code .
Step 2: Now create a file app.js file in your folder as shown below.
Step 3: Installing Module: Install the modules using the following command.
npm install express
npm install nodemon
Step 4: Add these two commands which are important for running and dynamically running the code after changes made in your Node.js app respectively in package.json file.
"start": "node app.js",
"dev": "nodemon app.js"
Configuration of package.json File:
{
  "name": "demo",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.12"
  }
}
Step 5: Following will be our project structure:
Step 6: Write down the following code in app.js file.
Javascript
// Requiring moduleconst express = require('express'); // Creating express objectconst app = express(); // Handling GET requestapp.get('/', (req, res) => {    res.send('A simple Node App is '        + 'running on this server')    res.end()}) // Port Numberconst PORT = process.env.PORT ||5000; // Server Setupapp.listen(PORT,console.log(  `Server started on port ${PORT}`));
Step 7: Run the application using the following command:
npm run dev
Output:
Step 8: Now go to http://localhost:5000/ in your browser, you will see the following output: 
mridulmanochagfg
kapilkumar2001
Node.js-Misc
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to set the top position of an element with JavaScript?

To set the top position, use the top property in JavaScript. You can try to run the following code to set the top position of a div with JavaScript −
<!DOCTYPE html>
<html>
   <head>
      <style>
         #myID {
            position: absolute;
         }
      </style>
   </head>

   <body>
      <button onclick="display()">Set Top Position</button>
      <div id = "myID">
         This is demo text! This is demo text!
      </div>

      <script>
         function display() {
            document.getElementById("myID").style.top = "100px";
         }
      </script>
   </body>
</html>
How to Get Length of Array in Excel VBA?

22 Nov, 2021
We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail.
Syntax: UBound() function
UBound (arrayname, [ dimension ])
Parameters:
arrayname: required. Array variable name
dimension: optional
Returns: Return upper limit of an array dimension.
Syntax: LBound() Function
LBound (arrayname, [ dimension ])
Parameters:
arrayname : required. Array variable name
dimension : optional
Returns: Return lower limit of an array dimension
Sample Data: 
Declare Variables:
Declaring a customer array with the size of 10.
Sub oneDimArrayLength()
' Array variable Declaration
Dim customer (1 To 10) As String
Assign values to array elements
customer(1) = "ANTON"
customer(2) = "BERGS"
customer(3) = "BOLID"
customer(4) = "KOENE"
customer(5) = "FRANS"
Use UBound function to get the size of an array and Message box to display the result
'Message box to popup length of 1D array
MsgBox "Array has " & UBound(customer) & " element(s)."

End Sub
To Run VBA Code
Press Alt+F8 to popup macro window.  Select ” oneDimArrayLength” and Click Run button.
Output
VBA Code to get the length of Array (multi-dimensional array)
Declaring variables:
Declaring ProdAndCustomer multi-dimensional array size of 10 rows and 2 columns
Sub twoDimArrayLength()

' Array variable Declaration
Dim ProdAndCustomer(1 To 10, 1 To 2) As String, noOfRow As Integer, noOfCol As Integer, noOfElements As Integer
Assign values to array elements
ProdAndCustomer(1, 1) = "Alice Mutton"
ProdAndCustomer(2, 1) = "Boston Crab Meat"
ProdAndCustomer(3, 1) = "Camembert Pierrot"
ProdAndCustomer(4, 1) = "Alice Mutton"
ProdAndCustomer(5, 1) = "Ipoh Coffee"

ProdAndCustomer(1, 2) = "ANTON"
ProdAndCustomer(2, 2) = "BERGS"
ProdAndCustomer(3, 2) = "BOLID"
ProdAndCustomer(4, 2) = "BOTTM"
ProdAndCustomer(5, 2) = "FURIB"
Compute Number of Rows, Number of Columns using UBound and LBound function.  Multiply by noOfRow and noOfCol variable to get Number of elements in multi-dimensional array. 
noOfRow = UBound(ProdAndCustomer, 1) - LBound(ProdAndCustomer, 1) + 1
noOfCol = UBound(ProdAndCustomer, 2) - LBound(ProdAndCustomer, 2) + 1
noOfElements = noOfRow * noOfCol
Message box to popup result
'Message box to popup length of 1D array
MsgBox "Array has " & noOfElements & " element(s)."

End Sub
To Run VBA Code
Press Alt+F8 to popup macro window.  Select ” twoDimArrayLength” and Click Run button.
Output:
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
Macros in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to make a 3 Axis Graph using Excel?
How to Extract the Last Word From a Cell in Excel?
Introduction to Excel Spreadsheet
How to Create a Macro in Excel?
How to insert a document with date in MongoDB?

To insert a document with date in MongoDB, use Date(). Following is the syntax
“yourFieldName”:new Date(yourDateValue);
Let us create a collection with documents. Following is the query
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Larry","UserMessage":"Hi","UserMessagePostDate":new Date("2012-09-24")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cca58a629b87623db1b16")
}
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Chris","UserMessage":"Hello","UserMessagePostDate":new Date("2015-12-31")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cca71a629b87623db1b17")
}
>db.insertDocumentWithDateDemo.insertOne({"UserName":"Robert","UserMessage":"Bye","UserMessagePostDate":new Date("2019-01-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cca85a629b87623db1b18")
}
Following is the query to display all documents from a collection with the help of find() method
> db.insertDocumentWithDateDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9cca58a629b87623db1b16"),
   "UserName" : "Larry",
   "UserMessage" : "Hi",
   "UserMessagePostDate" : ISODate("2012-09-24T00:00:00Z")
}
{
   "_id" : ObjectId("5c9cca71a629b87623db1b17"),
   "UserName" : "Chris",
   "UserMessage" : "Hello",
   "UserMessagePostDate" : ISODate("2015-12-31T00:00:00Z")
}
{
   "_id" : ObjectId("5c9cca85a629b87623db1b18"),
   "UserName" : "Robert",
   "UserMessage" : "Bye",
   "UserMessagePostDate" : ISODate("2019-01-01T00:00:00Z")
}