code-rag-bench/online-tutorials huggingface dataset:
abs() in Python

The abs() function in python represents the absolute value of a numeric input. The absolute value is concerned with the value or magnitude of a number instead of the sign attached to the number. It is even more useful for complex numbers where the calculation of magnitude involves many steps.
The syntax of the function is −
abs(num)
where num can be integer,floating number or a complex number.
In the below example we take all the above types of numbers and calculate their magnitude.
n = -112
print('Absolute value of a integer', abs(n))

f = -39.222
print('Absolute value of a float: ', abs(f))

c = (11 - 21j)
print('Absolute value or Magnitude of a complex number:', abs(c))
Running the above code gives us the following result:
('Absolute value of a integer', 112)
('Absolute value of a float: ', 39.222)
('Absolute value or Magnitude of a complex number:', 23.706539182259394)
Count ways to reach the n’th stair

There are n stairs. One person will go to 1'st to the n'th stair. Maximum how many stairs he/she can cross in one step is also given. With this information, we have to find possible ways to go to the n'th stairs.
Let us consider one can cross a maximum two stairs in each step. So we can find recursive relations to solve this problem. One can move to n'th stair, either from (n-1)'th stair or from (n-2)'th stair. So ways(n) = ways(n-1) + ways(n-2).
Input:
The number of stairs, say 10 the maximum number of stairs that can be jumped in one step, say 2
Output:
Enter number of stairs: 10
Enter max stair a person can climb: 2
Number of ways to reach: 89
stairClimpWays(stair, max)
Input − number of stairs, maximum stair jump in a single step.
Output − Number of possible ways to reach.
Begin
   define array count of size same as stair number
   count[0] := 1
   count[0] := 1

   for i := 2 to stair -1, do
      count[i] := 0
      for j = 1 to i and j <= max; do
         count[i] := count[i] + count[i - j]
      done
   done
   return count[stair - 1]
End
#include<iostream>
using namespace std;

int stairClimbWays(int stair, int max) {
   int count[stair];    //fill the result stair using bottom up manner
   count[0] = 1;       //when there are 0 or 1 stair, 1 way to climb
   count[1] = 1;
   
   for (int i=2; i<stair; i++) {    //for stair 2 to higher
      count[i] = 0;
      for(int j=1; j<=max && j<=i; j++)
         count[i] += count[i-j];
   }
   return count[stair-1];
}

int countWays(int stair, int max) {    //person can climb 1,2,...max stairs at a time
   return stairClimbWays(stair+1, max);
}

int main () {
   int stair, max;
   cout << "Enter number of stairs: "; cin >> stair;
   cout << "Enter max stair a person can climb: "; cin >> max;
   cout << "Number of ways to reach: " << countWays(stair, max);
}
Enter number of stairs: 10
Enter max stair a person can climb: 2
Number of ways to reach: 89
Counting occurrences of vowel, consonants - JavaScript

We are required to write a JavaScript function that takes in a string which contains English alphabet, for example −
const str = 'This is a sample string, will be used to collect some data';
The function should return an object containing the count of vowels and consonants in the string i.e. the output should be −
{ vowels: 17, consonants: 29 }
Following is the code −
const str = 'This is a sample string, will be used to collect some data';
const countAlpha = str => {
   return str.split('').reduce((acc, val) => {
      const legend = 'aeiou';
      let { vowels, consonants } = acc;
      if(val.toLowerCase() === val.toUpperCase()){
         return acc;
      };
      if(legend.includes(val.toLowerCase())){
         vowels++;
      }else{
         consonants++;
      };
      return { vowels, consonants };
   }, {
      vowels: 0,
      consonants: 0
   });
};
console.log(countAlpha(str));
This will produce the following output in console −
{ vowels: 17, consonants: 29 }
Hide content depending on screen size with Bootstrap

Use the .hidden-* class in Bootstrap to hide content depending on screen size with Bootstrap
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p class = "show">This is visible.</p>
      <p class = "hidden">This is hidden.</p>
      <h1 class = "hidden-sm bg-info">Hidden on small screen</h1>
      <h1 class = "hidden-md bg-warning">Hidden on medium screen</h1>
   </body>
</html>
Python | Test if dictionary contains unique keys and values

29 Apr, 2019
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it. Let’s test various ways in which this can be done.
Method #1 : Using loopsIn the Naive method to perform this particular task, we can check for each value and insert each value in list/hash in dictionary and when i’l repetition occurs, just stop the flow and return false.
# Python3 code to demonstrate# check for unique values# Using loops  # initializing dictionarytest_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # using loops# check for unique valuesflag = Falsehash_val = dict()for keys in test_dict:    if test_dict[keys] in hash_val:        flag = True        break    else :        hash_val[test_dict[keys]] = 1  # print resultprint("Does dictionary contain repetition : " + str(flag))
The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True

 
Method #2 : Using len() + set() + values()This problem can be easily solved using the combination of above three functions. The set function can be used to convert the values to set, removing duplicates and values function can be used to access the values.
# Python3 code to demonstrate# check for unique values# Using len() + set() + values()  # initializing dictionarytest_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # using len() + set() + values()# check for unique valuesflag = len(test_dict) != len(set(test_dict.values()))  # print resultprint("Does dictionary contain repetition : " + str(flag))
The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True

Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Iterator VS Generator

24 Jan, 2021
A process that is repeated more than one time by applying the same logic is called an Iteration.  In programming languages like python, a loop is created with few conditions to perform iteration till it exceeds the limit. If the loop is executed 6 times continuously, then we could say the particular block has iterated 6 times. 
Example:
Python3
a = [0, 5, 10, 15, 20]for i in a:    if i % 2 == 0:        print(str(i)+' is an Even Number')    else:        print(str(i)+' is an Odd Number')
Output:
0 is an Even Number
5 is an Odd Number
10 is an Even Number
15 is an Odd Number
20 is an Even Number
An iterator is an object which contains a countable number of values and it is used to iterate over iterable objects like list, tuples, sets, etc. Iterators are implemented using a class and a local variable for iterating is not required here, It follows lazy evaluation where the evaluation of the expression will be on hold and stored in the memory until the item is called specifically which helps us to avoid repeated evaluation. As lazy evaluation is implemented, it requires only 1 memory location to process the value and when we are using a large dataset then, wastage of RAM space will be reduced the need to load the entire dataset at the same time will not be there.
Using an iterator-
iter() keyword is used to create an iterator containing an iterable object.
next() keyword is used to call the next element in the iterable object.
After the iterable object is completed, to use them again reassign them to the same object.
Example:
Python3
iter_list = iter(['Geeks', 'For', 'Geeks'])print(next(iter_list))print(next(iter_list))print(next(iter_list))
Output:
Geeks
For
Geeks  
It is another way of creating iterators in a simple way where it uses the keyword “yield” instead of returning it in a defined function. Generators are implemented using a function. Just as iterators, generators also follow lazy evaluation. Here, the yield function returns the data without affecting or exiting the function. It will return a sequence of data in an iterable format where we need to iterate over the sequence to use the data as they won’t store the entire sequence in the memory.
Example:
Python3
def sq_numbers(n):    for i in range(1, n+1):        yield i*i    a = sq_numbers(3)  print("The square of numbers 1,2,3 are : ")print(next(a))print(next(a))print(next(a))
Output:
The square of numbers 1,2,3 are :  
1
4
9
Class is used to implement an iterator
Function is used to implement a generator.
Local Variables aren’t used here.                                         
All the local variables before the yield function are stored. 
python-basics
Difference Between
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Splitting string list by strings

05 Sep, 2019
Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let’s discuss certain way to solve this particular problem.
Method : Using loop + index() + list slicingThis task can be performed by using the above functionalities together. In this, we just loop along the pairs and get the desired indices using index(). Then list slicing is done to construct a new list of the desired slice and appended to form a new resultant list.
# Python3 code to demonstrate working of# Splitting string list by strings# using loop + index() + list slicing  # initialize listtest_list = ['gfg', 'is', 'best', "for", 'CS', 'and', 'Maths' ]  # initialize split listsplit_list = [('gfg', 'best'), ('CS', 'Maths')]  # printing original listprint("The original list is : " + str(test_list))  # printing split list print("The split list is : " + str(split_list))  # Splitting string list by strings# using loop + index() + list slicingfor start, end in split_list:        temp1 = test_list.index(start)        temp2 = test_list.index(end) + 1        test_list[temp1 : temp2] = [test_list[temp1 : temp2]]  # printing resultprint("The resultant split list is : " + str(test_list))
The original list is : ['gfg', 'is', 'best', 'for', 'CS', 'and', 'Maths']
The split list is : [('gfg', 'best'), ('CS', 'Maths')]
The resultant split list is : [['gfg', 'is', 'best'], 'for', ['CS', 'and', 'Maths']]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Fallthrough in C++

13 Jan, 2021
Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart ...etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line. Due to this when any case is matched with the specified value then control falls through to subsequent cases until a break statement is found. In C++, the error is not found on fallthrough but in languages like Dart, an error occurs whenever a fallthrough occurs.
It is not always necessary to avoid fallthrough, but it can be used as an advantage as well.
Program 1:
Below is the program to illustrate how fall-through occurs:
C++
// C++ program to illustrate// Fallthrough in C++#include <iostream>using namespace std;  // Driver Codeint main(){    int n = 2;      // Switch Cases    switch (n) {    case 1: {        cout << "this is one \n";    }    case 2: {        cout << "this is two \n";    }    case 3: {        cout << "this is three \n";    }    default: {        cout << "this is default \n";    }    }      return 0;}
this is two 
this is three 
this is default

Explanation: In the above code, there is no break statement so after matching with the 2nd case the control will fall through and the subsequent statements will also get printed.
How to Avoid Fall Through?
To avoid Fall through, the idea is to use a break statement after each and every case so that after matching it goes out of the switch statement and control goes to the statement next to the switch statement.
Program 2:
Below is the program to illustrate how to avoid the fall through:
C++
// C++ program to illustrate how to// avoid fall through#include <iostream>using namespace std;  // Driver Codeint main(){    int n = 2;      // Switch Cases    switch (n) {    case 1: {        cout << "this is one \n";        break;    }      case 2: {        cout << "this is two \n";          // After this break statement        // the control goes out of        // the switch statement        break;    }    case 3: {        cout << "this is three \n";        break;    }    default: {        cout << "this is default \n";        break;    }    }      return 0;}
this is two

CPP-Basics
CPP-Control-Flow
cpp-switch
C++
C++ Programs
CPP-Control-Flow
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Draw Chess Board Using Turtle in Python

01 Aug, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
For drawing Chess Board following steps are used :
Import turtle and making an object.
Set screen size and turtle position.
Define a method to draw a square
Call the method 8 times under another loop for 8 times with alternative color.
Hide the turtle object.
Below is the implementation :
python3
# import turtle packageimport turtle    # create screen objectsc = turtle.Screen()   # create turtle objectpen = turtle.Turtle()   # method to draw squaredef draw():     for i in range(4):    pen.forward(30)    pen.left(90)     pen.forward(30)          # Driver Codeif __name__ == "__main__" :          # set screen    sc.setup(600, 600)           # set turtle object speed    pen.speed(100)           # loops for board    for i in range(8):             # not ready to draw      pen.up()             # set position for every row      pen.setpos(0, 30 * i)             # ready to draw      pen.down()             # row      for j in range(8):               # conditions for alternative color        if (i + j)% 2 == 0:          col ='black'               else:          col ='white'               # fill with given color        pen.fillcolor(col)               # start filling with colour        pen.begin_fill()               # call method        draw()        # stop filling        pen.end_fill()           # hide the turtle    pen.hideturtle()           # This code is contributed by Deepanshu Rustagi.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add padding to a tkinter widget only on one side ?

15 Mar, 2021
In this article, we will discuss the procedure of adding padding to a Tkinter widget only on one side. Here, we create a widget and use widget.grid() method in tkinter to padding the content of the widget. For example, let’s create a label and use label.grid() method. Below the syntax is given:
label1 = Widget_Name(app, text="text_to_be_written_in_label")
label1.grid(
    padx=(padding_from_left_side, padding_from_right_side), 
    pady=(padding_from_top, padding_from_bottom))
Steps Needed: 
First, import the library tkinter
from tkinter import *
Now, create a GUI app using tkinter
app= Tk()
Next, give a title to the app.
app.title(“Name of GUI app”)
Then, create the widget by replacing the #Widget Name with the name of the widget (such as Label, Button, etc.).
l1 =Widget_Name(app, text="Text we want to give in widget")
Moreover, give the padding where we want to give it.
l1.grid(padx=(padding from left side, padding from right side),
    pady=(padding from top, padding from bottom))
For instance, if we want to give the padding from the top side only, then enter the padding value at the specified position, and leave the remaining as zero. It will give the padding to a widget from one side only, i.e., top.
l1.grid(padx=(0, 0), pady=(200, 0))
Finally, make the loop for displaying the GUI app on the screen.
app.mainloop( )
It will give the output as follows:
Example 1: Padding at left-side to a widget
Python
# Python program to add padding# to a widget only on left-side  # Import the library tkinterfrom tkinter import *  # Create a GUI appapp = Tk()  # Give title to your GUI appapp.title("Vinayak App")  # Maximize the window screenwidth = app.winfo_screenwidth()height = app.winfo_screenheight()app.geometry("%dx%d" % (width, height))  # Construct the label in your appl1 = Label(app, text='Geeks For Geeks')  # Give the leftmost paddingl1.grid(padx=(200, 0), pady=(0, 0))  # Make the loop for displaying appapp.mainloop()
Output:
Example 2: Padding from top to a widget
Python
# Python program to add padding# to a widget only from top  # Import the library tkinterfrom tkinter import *  # Create a GUI appapp = Tk()  # Give title to your GUI appapp.title("Vinayak App")  # Maximize the window screenwidth = app.winfo_screenwidth()height = app.winfo_screenheight()app.geometry("%dx%d" % (width, height))  # Construct the button in your appb1 = Button(app, text='Click Here!')  # Give the topmost paddingb1.grid(padx=(0, 0), pady=(200, 0))  # Make the loop for displaying appapp.mainloop()
Output:
Picked
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create pandas dataframe from lists using dictionary

13 Dec, 2018
Creating pandas data-frame from lists using dictionary can be achieved in multiple ways.
Method #1: Using pandas.DataFrame
With this method in Pandas we can transform a dictionary of list to a dataframe.
# importing pandas as pdimport pandas as pd  # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],        'degree': ["MBA", "BCA", "M.Tech", "MBA"],        'score':[90, 40, 80, 98]}  df = pd.DataFrame(dict)  df
Output: 
Method #2: Using from_dict() function.
# importing pandas as pdimport pandas as pd  # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],        'degree': ["MBA", "BCA", "M.Tech", "MBA"],        'score':[90, 40, 80, 98]}  df = pd.DataFrame.from_dict(dict)  df
Output:With the use of this function, we get some flexibility in arranging our data, such as the orientation of data, data type and name of the columns can be entered as parameter in the function.
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List addAll() Method in Java with Examples

02 Jan, 2019
This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
Syntax:
boolean addAll(Collection c)
Parameters: This function has a single parameter, i.e, Collection c, whose elements are to be appended to the list.
Returns: It returns true if the elements of specified list is appended and list changes.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type arraylist        List<Integer> l = new ArrayList<>();        l.add(10);        l.add(15);        l.add(20);        System.out.println(l);          // Initializing a collection to be appended to list        ArrayList<Integer> arr = new ArrayList<Integer>();        arr.add(100);        arr.add(200);        arr.add(300);        System.out.println(arr);          l.addAll(arr);          System.out.println(l);    }}
[10, 15, 20]
[100, 200, 300]
[10, 15, 20, 100, 200, 300]

Program 2: Below is the code to show implementation of list.addAll() using Linkedlist.
// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a list of type Linkedlist        List<Integer> l = new LinkedList<>();        l.add(10);        l.add(15);        l.add(20);        System.out.println(l);          // Initializing a collection to be appended to list        ArrayList<Integer> arr = new ArrayList<Integer>();        arr.add(100);        arr.add(200);        arr.add(300);        System.out.println(arr);          l.addAll(arr);          System.out.println(l);    }}
[10, 15, 20]
[100, 200, 300]
[10, 15, 20, 100, 200, 300]

Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Initializing a List in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java
TypeScript | Array splice() Method

18 Jun, 2020
The Array.splice() is an inbuilt TypeScript function which is used to change the content of an array, adding new elements while removing old elements.Syntax: 
array.splice(index, howMany, [element1][, ..., elementN]); 
Parameter: This method accept three parameter as mentioned above and described below: 
index : This parameter is the index at which to start changing the array.
howMany : This parameter is the integer indicating the number of old array elements to remove.
element1, ..., elementN : This parameter is the elements to add to the array.
Return Value: This method returns the extracted array. Below example illustrate the  Array splice() method in TypeScriptJS:Example 1: 
JavaScript
<script>    // Driver code    var arr = [ 11, 89, 23, 7, 98 ];       // use of splice() method     var removed = arr.splice(2, 0, 11);           // printing    console.log(removed);</script>
Output: 
[]

Example 2: 
JavaScript
<script>    // Driver code    var arr = ["G", "e", "e", "k", "s", "f", "o",                "r", "g", "e", "e", "k", "s"];     var val;       // use of splice() method     val = arr.splice(0,5);    console.log( val );    console.log( arr );</script>
Output: 
[ 'G', 'e', 'e', 'k', 's' ]
[ 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' ]

 
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Scala Set foreach() method with example

18 Oct, 2019
The foreach() method is utilized to apply the given function to all the elements of the set.
Method Definition: def foreach(f: (A) => Unit): Unit
Return Type: It returns all the elements of the set after applying the given function to each of them.
Example #1:
// Scala program of foreach() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(3, 7, 12, 9, 21)                   // Applying foreach method         s1.foreach(x => println(x))           } } 
21
9
12
7
3

Example #2:
// Scala program of foreach() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(1, 2, 3, 4, 5)                   // Applying foreach method         s1.foreach(x => println(x + " times " + x + " = " + x*x))           } } 
5 times 5 = 25
1 times 1 = 1
2 times 2 = 4
3 times 3 = 9
4 times 4 = 16

Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Lambda Expression in Scala
Scala Singleton and Companion Objects
How to Install Scala with VSCode?
Inheritance in Scala
Search Element in a Dictionary using Javascript

We'll implement the get method that searches a given key in the dictionary. 
get(key) {
   if(this.hasKey(key)) {
      return this.container[key];
   }
   return undefined;
}
Again, JS objects are very much implemented like dictionaries, hence have most of the functionality we can use directly without any more code needed. This is also heavily optimized, so you don't have to worry about the runtime of the function.
You can test this using − 
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

console.log(myMap.get("key1"))
console.log(myMap.get("key2"))
console.log(myMap.get("key3"))
This will give the output −
value1
value2
undefined
In ES6, you have the same functionality using the get method. For example, 
const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);

console.log(myMap.get("key1"))
console.log(myMap.get("key2"))
This will give the output −
value1
value2
C++ Program to Check Whether a Number is Palindrome or Not

A palindrome number remains the same if its digits are reversed i.e its value does not change. A palindrome number can also be called symmetric. For example: The numbers 12321, 1551, 11 etc are palindromes as they do not change even if their digits are reversed.
A program that checks if a number is palindrome or not is as follows.
 Live Demo
#include<iostream>
using namespace std;
void palindrome(int num) {
   int rev=0,val;
   val = num;
   while(num > 0) {
      rev = rev * 10 + num % 10;
      num = num / 10;
   }
   if(val==rev)
   cout<<val<<" is a palindrome"<<endl;
   else
   cout<<val<<" is not a palindrome"<<endl;
}
int main() {
   palindrome(12321);
   palindrome(1234);
   return 0;
}
12321 is a palindrome
1234 is not a palindrome
In the above program, the function palindrome finds out if the number is palindrome or not. The function takes one parameter i.e num. Before any process takes place, a duplicate of num is made i.e val. The value of num is reversed and stored in rev.
This is shown by the following code snippet −
int rev=0,val;
val = num;
while(num > 0) {
   rev = rev * 10 + num % 10;
   num = num / 10;
}
After this, the value of rev is compared to val and not num. This is because the value of num is 0 by now. If rev is equal to val, then the number is a palindrome and this is printed, else the number is not a palindrome.
This can be seen in the following code snippet.
if(val==rev)
cout<<val<<" is a palindrome"<<endl;
else
cout<<val<<" is not a palindrome"<<endl;
HTML - <ilayer> Tag

The HTML <ilayer> tag is used to create a layer that occupies space in the containing text flow. Subsequent content is placed after the space occupied by the <ilayer>.
This is in contrast to the <layer> tag, which creates a layer above the containing text flow, allowing subsequent content to be placed under the layer just created.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML ilayer Tag</title>
   </head>

   <body>
      This <ilayer top = "4">word</ilayer> is shifted down, while this 
         <ilayer left = "10">one</ilayer> is shifted over. With a negative value, 
         words can be moved <ilayer top = "-4">up</ilayer> and to the 
         <ilayer left = "-10">left</ilayer>.
   </body>

</html>
This will produce the following result −
The result will only work on Netscape 4.
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <ilayer> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Array.prototype.find() method in JavaScript.

The Array.prototype.find() method returns the first element value that satisfy a given
condition in an array.
Following is the code for the Array.prototype.find() method −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .find {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Array Find() example</h1>
<div class="find"></div>
<button class="fillArr">CLICK HERE</button>
<h3>Click on the above button to find lion among the animals</h3>
<script>
   function findLion(animal) {
      return animal === "lion";
   }
   let fillEle = document.querySelector(".find");
   let arr = ["cow", "lion", "bull", "tiger"];
   fillEle.innerHTML = arr;
   document.querySelector(".fillArr").addEventListener("click", () => {
      fillEle.innerHTML = arr.find(findLion);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “CLICK HERE” button −
Python | Convert number to list of integers - GeeksforGeeks

26 Jan, 2019
The interconversion of data types is a problem that is quite common in programming. Sometimes we need to convert a single number to list of integers and we don’t wish to spend several lines of codes doing it. Hence having ways to perform this task using shorthands comes handy. Let’s discuss ways in which this can be performed.
Method #1 : Using list comprehensionList comprehension can be used as a shorthand to the longer format of naive method. In this method, we convert the number to string and then extract its each character and re convert it to integer.
# Python3 code to demonstrate # conversion of number to list of integers# using list comprehension  # initializing number num = 2019  # printing number print ("The original number is " + str(num))  # using list comprehension# to convert number to list of integersres = [int(x) for x in str(num)]  # printing result print ("The list from number is " + str(res))
Output:
The original number is 2019
The list from number is [2, 0, 1, 9]
 Method #2 : Using map()map function can be used to perform the following task converting each of the string converted number to the desired integer value to be reconverted to the list format.
# Python3 code to demonstrate # conversion of number to list of integers# using map()  # initializing number num = 2019  # printing number print ("The original number is " + str(num))  # using map()# to convert number to list of integersres = list(map(int, str(num)))  # printing result print ("The list from number is " + str(res))
Output:
The original number is 2019
The list from number is [2, 0, 1, 9]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python?
How to convert empty values to NA in an R data frame?

When our data has empty values then it is difficult to perform the analysis, we might to convert those empty values to NA so that we can understand the number of values that are not available. This can be done by using single square brackets.
Consider the below data frame that has some empty values −
> x1<-c(rep(c(1,2,3),times=5),"","","",2,1)
> x2<-rep(c(2,4,"",4,""),each=4)
> x3<-rep(c(5,4,2,""),times=c(2,5,3,10))
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 1 2 5
2 2 2 5
3 3 2 4
4 1 2 4
5 2 4 4
6 3 4 4
7 1 4 4
8 2 4 2
9 3 2
10 1 2
11 2
12 3
13 1 4
14 2 4
15 3 4
16 4
17
18
19 2
20 1
Converting empty values to NA −
> df[df == ""]<-NA
> df
x1 x2 x3
1 1 2 5
2 2 2 5
3 3 2 4
4 1 2 4
5 2 4 4
6 3 4 4
7 1 4 4
8 2 4 2
9 3 <NA> 2
10 1 <NA> 2
11 2 <NA> <NA>
12 3 <NA> <NA>
13 1 4 <NA>
14 2 4 <NA>
15 3 4 <NA>
16 <NA> 4 <NA>
17 <NA> <NA> <NA>
18 <NA> <NA> <NA>
19 2 <NA> <NA>
20 1 <NA> <NA>
Redeclaration of global variable in C - GeeksforGeeks

28 May, 2017
Consider the below two programs:
// Program 1int main(){   int x;   int x = 5;   printf("%d", x);   return 0; }
Output in C:
redeclaration of ‘x’ with no linkage
// Program 2int x;int x = 5;  int main(){   printf("%d", x);   return 0; }
Output in C:
5
In C, the first program fails in compilation, but second program works fine. In C++, both programs fail in compilation.
C allows a global variable to be declared again when first declaration doesn’t initialize the variable.
The below program fails in both C also as the global variable is initialized in first declaration itself.
int x = 5;int x = 10;  int main(){   printf("%d", x);   return 0;}
Output:
 error: redefinition of ‘x’
This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Variable Declaration and Scope
cpp-storage-classes
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
Enumeration (or enum) in C
std::string class in C++
Exception Handling in C++
Java Examples - Retrieve Table Contents

How to retrieve contents of a table using JDBC connection?
Following example uses getString, getInt & executeQuery methods to fetch & display the contents of the table.
import java.sql.*;

public class jdbcResultSet {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      } catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      try {
         Connection con = DriverManager.getConnection(
            "jdbc:derby://localhost:1527/testDb","username", "password");
         
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
         System.out.println("id  name    job");
         
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String job = rs.getString("job");
            System.out.println(id+"   "+name+"    "+job);
         }
      } catch(SQLException e) {
         System.out.println("SQL exception occured" + e);
      }
   }
}
The above code sample will produce the following result. The result may vary.
id  name   job
1   alok   trainee
2   ravi   trainee

 Print
 Add Notes
 Bookmark this page
Predicting the Price of the Beyond Meat Stock Using Random Forest in Python | by Sadrach Pierre, Ph.D. | Towards Data Science

In this post we will predict the price of the Beyond Meat stock using random forest. Beyond Meat is a producer of plant-based meat substitutes and was founded by Ethan Brown in Los Angeles in 2009.
First thing we can do is import the necessary libraries. We will be using the yahoo finance API, seaborn, matplotlib, pandas, numpy, and sklearn:
import yfinance as yfimport seaborn as snsimport numpy as npimport pandas as pd from sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt
If you don’t have the python wrapper for the yahoo finance API installed you can type the following in a command line:
pip install yfinance
We can pull the last five months of ‘BYND’ stock data from Yahoo finance and print the first five rows. We will pull data from May 5, 2019 to November 2, 2019:
data = yf.Ticker('BYND')df = data.history(period="max",  start="2019-05-01", end="2019-11-02")print(df.head())
We can plot the open prices using seaborn. We also use matpltlib to modify the seaborn plot. In order to plot the time series we need to convert the date strings into datetime objects:
sns.set()df[‘timestamp’] = df.indexdf[‘timestamp’] = pd.to_datetime(df[‘timestamp’])sns.lineplot(df[‘timestamp’], df['Open'])plt.ylabel("Open Price")
Next thing we can do is calculate the daily returns using the open and close daily prices and plot the results:
df[‘returns’] = (df[‘Close’]-df[‘Open’])/df[‘Open’]sns.lineplot(df[‘timestamp’], df['returns'])plt.ylabel("Returns")
Next we define a variable that specifies how far out we want to predict. Let’s predict 3 days out. We also create a new prediction column which is the target variable shifted up by the 3 days. Here our target variable will be the closing price :
forecast_out = 3df[‘prediction’] = df[[‘Close’]].shift(-forecast_out)X = np.array(df['Close']).reshape(-1,1)X = X[:-forecast_out]y = np.array(df['prediction'])y = y[:-forecast_out]
Next we split our data for training and testing, define a random forest object and train our model:
reg = RandomForestRegressor(n_estimators = 300, max_depth =300, random_state = 42)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 7)reg.fit(X_train, y_train)print("Performance (R^2): ", reg.score(X_test, y_test))
Our model has R2 = 0.84, which isn’t too bad. Thank you for reading and happy machine learning! The code from this post is available on GitHub.
Python | Scipy integrate.quadrature() method - GeeksforGeeks

23 Jan, 2020
With the help of scipy.integrate.quadrature() method, we can get the computation of definite integral using fixed tolerance gaussian quadrature by using scipy.integrate.quadrature() method.
Syntax : scipy.integrate.quadrature(func, a, b)
Return : Return gaussian quadrature approximation to integral.
Example #1 :In this example we can see that by using scipy.integrate.quadrature() method, we are able to get the gaussian quadrature approximation to integral function from limit a to b by using this method.
# import scipy.integrate.from scipy import integrate  gfg = lambda x: x**8 + x**4  # using scipy.integrate.quadrature() methodgeek = integrate.quadrature(gfg, 0.0, 1.8)  print(geek)
Output :
25.81905715199999
Example #2 :
# import scipy.integrate.from scipy import integrate  gfg = lambda x: x**2 + 2 * x + 4  # using scipy.integrate.quadrature() methodgeek = integrate.quadrature(gfg, 0.0, 4.0)  print(geek)
Output :
53.33333333333333
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Laravel - Guest User Gates

The Guest User Gates feature is an add-on to the latest 5.7 version released in September 2018. This feature is used to initiate the authorization process for specific users.
In Laravel 5.6, there was a procedure where it used to return false for unauthenticated users. In Laravel 5.7, we can allow guests to go authorization checks by using the specific nullable type hint within the specified controller as given below −
<?php
Gate::define('view-post', function (?User $user) {
   // Guests
});

By using a nullable type hint the $user variable will be null when a guest user is passed to the gate. You can then make decisions about authorizing the action. If you allow nullable types and return true, then the guest will have authorization. If you don’t use a nullable type hint, guests will automatically get the 403 response for Laravel 5.7, which is displayed below −
The difference between 403 and 404 error is that 404 is displayed when user tries to access the unknown resource or URL and 403 error as mentioned in the snapshot above is displayed if unauthorized user accesses the website.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
Splitting an object into an array of objects in JavaScript

Suppose, we have an object like this −
const obj = {
   "value 0": "value",
   "value 1": "value",
   "value 2": "value",
   "value 3": "value",
   "value 4": "value",
   "value 5": "value",
   "value 6": "value",
   "value 7": "value",
   "value 8": "value",
   "value 9": "value"
};
We are required to write a JavaScript function that takes in one such object. The function should return a new array of objects in which each key/value pair is separated into its own separate object.
The code for this will be −
const obj = {
   "value 0": "value",
   "value 1": "value",
   "value 2": "value",
   "value 3": "value",
   "value 4": "value",
   "value 5": "value",
   "value 6": "value",
   "value 7": "value",
   "value 8": "value",
   "value 9": "value"
};
const separateObject = obj => {
   const res = [];
   const keys = Object.keys(obj);
   keys.forEach(key => {
      res.push({
         key: obj[key]
      });
   });
   return res;
};
console.log(separateObject(obj));
And the output in the console will be −
[
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' },
   { key: 'value' }
]
How to a plot stem plot in Matplotlib Python?

To plot a stem plot in Matplotlib, we can use stem() method. It creates vertical lines from a baseline to the Y-coordinate and places a marker at the tip.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create a stem plot using stem() method.
Set the marker face color with red color.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(0.1, 2 * np.pi, 41)
y = np.exp(np.sin(x))

markerline, stemlines, baseline = plt.stem(x, y, linefmt='grey', markerfmt='*', bottom=1.1)

markerline.set_markerfacecolor('red')

plt.show()
Output of Java Program | Set 2 - GeeksforGeeks

18 May, 2021
Predict the output of the following Java programs. 
Question 1: 
Java
package main; class Base {    public void Print()    {        System.out.println("Base");    }} class Derived extends Base {    public void Print()    {        System.out.println("Derived");    }} class Main {    public static void DoPrint(Base o)    {        o.Print();    }    public static void main(String[] args)    {        Base x = new Base();        Base y = new Derived();        Derived z = new Derived();        DoPrint(x);        DoPrint(y);        DoPrint(z);    }}
Output: 
Base
Derived
Derived
Predicting the first line of output is easy. We create an object of type Base and call DoPrint(). DoPrint calls the print function and we get the first line.
DoPrint(y) causes the second line of output. Like C++, assigning a derived class reference to a base class reference is allowed in Java. Therefore, the expression Base y = new Derived() is a valid statement in Java. In DoPrint(), o starts referring to the same object as referred by y. Also, unlike C++, functions are virtual by default in Java. So, when we call o.print(), the print() method of Derived class is called due to run time polymorphism present by default in Java. 
DoPrint(z) causes the third line of output, we pass a reference of Derived type and the print() method of Derived class is called again. The point to note here is: unlike C++, object slicing doesn’t happen in Java. Because non-primitive types are always assigned by reference. 
Question 2:  
Java
package main; // filename Main.javaclass Point {    protected int x, y;     public Point(int _x, int _y)    {        x = _x;        y = _y;    }} public class Main {    public static void main(String args[])    {        Point p = new Point();        System.out.println("x = " + p.x + ", y = " + p.y);    }}
Output: 
Compiler Error
In the above program, there are no access permission issues because the Point and Main are in the same package and protected members of a class can be accessed in other classes of the same package. The problem with the code is: there is no default constructor in Point. 
Like C++, if we write our own parameterized constructor then Java compiler doesn’t create the default constructor. So there are following two changes to Point class that can fix the above program. 
Remove the parameterized constructor.Add a constructor without any parameter.
Remove the parameterized constructor.
Add a constructor without any parameter.
Java doesn’t support default arguments, so that is not an option.Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above. 
BHAVY_PRATAP
saurabh1990aror
Java-Output
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Arrow operator -> in C/C++ with Examples
Output of Java Program | Set 1
delete keyword in C++
Output of C Programs | Set 1
Different ways to copy a string in C/C++