code-rag-bench/online-tutorials huggingface dataset:
Lodash _.join() Method - GeeksforGeeks

03 Aug, 2020
The _.join() function is used to converts all elements in the array into a string separated by a separator.
Syntax:  
_.join(array, [separator=','])

Parameter: This method accepts two parameters as mentioned above and described below:
array: It is the original array from which join operation is to be performed.
separator: A string to separate each element of the array. If leave it by default array element separate by comma( , ).
Return Value: This function returns a string created by joining all the elements of the array using the separator.
Note: Install the lodash module by using command npm to install lodash before using the code given below.
Example 1: In this example, the function join() joins together the elements of the array into a string using ‘|’.
Javascript
// Requiring the lodash library let lodash = require("lodash");     // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ];     let newArray = lodash.join(array, '|'); console.log("Before Join: " + array);     // Printing newArray  console.log("After Join: " + newArray);
Output:
Example 2: In this example, the function join() joins together the elements of the array into a string using ‘, ‘ since it is the default value.
Javascript
// Requiring the lodash library let lodash = require("lodash");     // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ];     let newArray = lodash.join(array); console.log("Before Join: " + array);     // Printing newArray  console.log("After Join: " + newArray);
Output:
Example 3: In this example, the function join() joins together the elements of the array into a string using ‘ ‘ (empty string).
Javascript
// Requiring the lodash library let lodash = require("lodash");     // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ];     let newArray = lodash.join(array,''); console.log("Before Join: " + array);     // Printing newArray  console.log("After Join: " + newArray);
Output:
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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 process a simple form data using Python CGI script?

suppose there is an HTML file as below −
<form action="getData.py" method="post">
   FirstName: <input type="text" name="first_name">
   LastName: <input type="text" name="last_name">
   <input type="submit" value="go">
</form>
after submitting this form it should go to a python page named getData.py, where you should fetch the data from this HTML page and show. then below is the code for python CGI
#!C:\Python27\python.exe
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')
print("Content-type:text/html")
print
print("")
print("")
print("Hello - Second CGI Program")
print("")
print("")
print("
   Hello %s %s
   " % (first_name, last_name))
print("")
print("")
Ones and Zeroes in C++

Suppose we have a dominator of m 0s and n 1s respectively. On the other hand, there is an array with binary strings. Now our task is to find the maximum number of strings that we can generate with given m 0s and n 1s. Each 0 and 1 can be used at most once. So if the input is like Array = [“10”, “0001”, “111001”, “1”, “0”,] and m = 5 and n = 3, then the output will be 4. This is because there are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”.
To solve this, we will follow these steps −
Make a matrix of size (m + 1) x (n + 1)
ret := 0
for i in range 0 to size of strs arrayone := 0, zero := 0for j in range 0 to size of strs[i]increase one when star[i, j] is 1, or increase zero when it is 0for j in range m down to 0for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k]
one := 0, zero := 0
for j in range 0 to size of strs[i]increase one when star[i, j] is 1, or increase zero when it is 0
increase one when star[i, j] is 1, or increase zero when it is 0
for j in range m down to 0for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k]
for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k]
dp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]
ret := max of ret and dp[j,k]
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int findMaxForm(vector<string>& strs, int m, int n) {
      vector < vector <int> > dp(m + 1, vector <int>(n + 1));
      int ret = 0;
      for(int i = 0; i < strs.size(); i++){
         int one = 0;
         int zero = 0;
         for(int j = 0; j < strs[i].size(); j++){
            one += strs[i][j] == '1';
            zero += strs[i][j] == '0';
         }
         for(int j = m; j>= zero; j--){
            for(int k = n; k >= one; k--){
               dp[j][k] = max(dp[j][k], 1 + dp[j - zero][k - one]);
                  ret = max(ret, dp[j][k]);
            }
         }
      }
      return ret;
   }
};
main(){
   vector<string> v = {"10","0001","111001","1","0"};
   Solution ob;
   cout << (ob.findMaxForm(v, 5, 3));
}
["10","0001","111001","1","0"]
5
3
4
Place the image at the bottom inside a Bootstrap 4 card

To place the image at the bottom inside a card, use the card-img-bottom class.
Firstly, set the card body and then use the <img> tag to add an image. The following code snippet is added inside the card class −
<div class="card-body">
  <h4 class="card-title">Quantitative Aptitude</h4>
  <p class="card-text">For Entrance Exams</p>
  <a href="#" class="btn btn-primary">Sample Questions</a>
</div>
<img class="card-img-bottom" src="Image-Source " alt="Alt-Text" style="width:100%">
The following is an example to learn how to place image at the bottom inside a card in Bootstrap 4 −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

<div class="container">
  <h3>Quantitative Aptitude Questions Answers</h3>
  <div class="card" style="width:400px">
    <div class="card-body">
      <h4 class="card-title">Quantitative Aptitude</h4>
      <p class="card-text">For Entrance Exams</p>
      <a href="#" class="btn btn-primary">Sample Questions</a>
    </div>
    <img class="card-img-bottom" src="https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg" alt="QA" style="width:100%">
  </div>
</div>

</body>
</html>
Python - Mirror Image of String - GeeksforGeeks

02 Sep, 2020
Given a String, perform its mirror imaging, return “Not Possible” if mirror image not possible using english characters.
Input : test_str = ‘boid’Output : doibExplanation : d replaced by b and vice-versa as being mirror images.
Input : test_str = ‘gfg’Output : Not PossibleExplanation : Valid Mirror image not possible.
Method : Using loop + loopup dictionary
This is one way in which this task can be performed. In this, we construct lookup dictionary for all valid mirrorable english characters, then perform task of access from them.
Python3
# Python3 code to demonstrate working of # Mirror Image of String# Using Mirror Image of String  # initializing stringstest_str = 'void'  # printing original stringprint("The original string is : " + str(test_str))  # initializing mirror dictionarymir_dict = {'b':'d', 'd':'b', 'i':'i', 'o':'o', 'v':'v', 'w':'w', 'x':'x'}res = ''  # accessing letters from dictionaryfor ele in test_str:    if ele in mir_dict:        res += mir_dict[ele]          # if any character not present, flagging to be invalid     else:        res = "Not Possible"        break  # printing result print("The mirror string : " + str(res)) 
The original string is : void
The mirror string : voib

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
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?
Python Program to find sum of array - GeeksforGeeks

22 Oct, 2020
Given an array of integers, find the sum of its elements.
Examples :
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50

Method 1:
# Python 3 code to find sum # of elements in given array def _sum(arr):           # initialize a variable    # to store the sum    # while iterating through    # the array later    sum=0          # iterate through the array    # and add each element to the sum variable    # one at a time    for i in arr:        sum = sum + i              return(sum)   # driver function arr=[] # input values to list arr = [12, 3, 4, 15]   # calculating length of array n = len(arr)   ans = _sum(arr)   # display sum print ('Sum of the array is ', ans)   # This code is contributed by Himanshu Ranjan 
Sum of the array is  34

Method 2:
# Python 3 code to find sum # of elements in given array# driver functionarr = []  # input values to listarr = [12, 3, 4, 15]  # sum() is an inbuilt function in python that adds # all the elements in list,set and tuples and returns# the value ans = sum(arr)  # display sumprint ('Sum of the array is ',ans)  # This code is contributed by Dhananjay Patil 
Sum of the array is  34

Please refer complete article on Program to find sum of elements in a given array for more details!
avsadityavardhan
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Iterate over characters of a string in Python
Python | Convert a list into a tuple
Python Program for factorial of a number
Python | Check if a variable is string
Python | Convert set into a list
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python Program for Bubble Sort
Python program to find largest number in a list
How to clone a GitHub repository?

Cloning a repository involves downloading a copy of the source code from source control. In other words, cloning is creating a copy of an existing repository. Consider an example where multiple users are working on a project. This feature can be used by the users to create a development copy.
If you have a GitHub repository, you need to first invite collaborators into the repository. Each collaborator will then clone the repository into their local machines.
Locally they will work with this cloned repository, make local changes and perform commits on it. Once they are ready to share their changes with others in the team, they will push the commits to the central repository.
In order to clone a repository, we need to follow the steps given below −
Copy the URL from the text box shown above and paste this into your git bash terminal using the below command.
$ git clone {repo_rul}
This will create a folder in your machine with the same name as that of the project.
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo
$ git clone https://github.com/kannan/sample.git
Cloning into 'sample'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo
$ ls
sample/
Change the current working directory to the project folder and execute the git log command as shown below
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo
$ cd sample/

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo/sample (main)
$ git log --oneline --all --graph
* b494547 (HEAD -> main, origin/main, origin/HEAD) Initial commit
In the above output, origin is the name given by git for the remote tracking branch (i.e., the source branch that was cloned). origin/main and origin/HEAD are remote tracking branches. In order to view the details of the remote tracking branch use the following command
$ git remote -v
origin https://github.com/kannan/sample.git (fetch)
origin https://github.com/kannan/sample.git (push)
-v means verbose so this will list the details of the remote tracking branches.
Alert for unsaved changes in form in JavaScript

Following is the code to display an alert for form’s unsaved changes in JavaScript −
 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;
   }
   input {
      margin: 10px;
   }
</style>
</head>
<body onbeforeunload="return pageUnload()">
<h1>Alert for unsaved changes in form</h1>
<form>
Username <input type="text" />
<br />
Password <input type="password" /><br />
<button type="submit">SUBMIT</button>
</form>
<br />
<script>
   function pageUnload() {
      return "The data on this page will be lost if you leave";
   }
</script>
</body>
</html>
If we click on the reload button then the following warning will be shown −
ReactJS - State Management

State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter.
State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state.
A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it’s state. As the state of the clock component changes every second, the clock’s render() method will be called every second and the render() method show the current time using it’s current state.
The simple representation of the state is as follows −
{ 
   date: '2020-10-10 10:10:10' 
}

Let us create a new Clock component later in this chapter.
Here,
State management API
State management API
Stateless component
Stateless component
State management using React Hooks
State management using React Hooks
Component Life cycle
Component Life cycle
Component life cycle using React Hooks
Component life cycle using React Hooks
Layout in component
Layout in component
Pagination
Pagination
Material UI
Material UI

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    60 Lectures 
     4.5 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    17 Lectures 
     2 hours 

 Mohd Raqif Warsi
 Print
 Add Notes
 Bookmark this page
Program to find minimum changes required for alternating binary string in Python

Suppose we have a binary string s. Let us consider an operation where we can flip one bit. The string s is called alternating string if no two adjacent characters are same. We have to find the minimum number of operations needed to make s alternating.
So, if the input is like s = "11100011", then the output will be 3 because if we flip bits at position 1, 4 and 7, then, it will be "10101010", then all are alternating.
To solve this, we will follow these steps −
change := 0
change := 0
even_1 := 0, even_0 := 0
even_1 := 0, even_0 := 0
odd_1 := 0, odd_0 := 0
odd_1 := 0, odd_0 := 0
for i in range 0 to size of s - 1, doif i is even, thenif s[i] is same as '1', theneven_1 := even_1 + 1otherwise,even_0 := even_0 + 1otherwise,if s[i] is same as '1', thenodd_1 := odd_1 + 1otherwise,odd_0 := odd_0 + 1
for i in range 0 to size of s - 1, do
if i is even, thenif s[i] is same as '1', theneven_1 := even_1 + 1otherwise,even_0 := even_0 + 1
if i is even, then
if s[i] is same as '1', theneven_1 := even_1 + 1
if s[i] is same as '1', then
even_1 := even_1 + 1
even_1 := even_1 + 1
otherwise,even_0 := even_0 + 1
otherwise,
even_0 := even_0 + 1
even_0 := even_0 + 1
otherwise,if s[i] is same as '1', thenodd_1 := odd_1 + 1otherwise,odd_0 := odd_0 + 1
otherwise,
if s[i] is same as '1', thenodd_1 := odd_1 + 1
if s[i] is same as '1', then
odd_1 := odd_1 + 1
odd_1 := odd_1 + 1
otherwise,odd_0 := odd_0 + 1
otherwise,
odd_0 := odd_0 + 1
odd_0 := odd_0 + 1
if (even_1+odd_0) > (even_0+odd_1), thenchange := even_0 + odd_1
if (even_1+odd_0) > (even_0+odd_1), then
change := even_0 + odd_1
change := even_0 + odd_1
otherwise,change := even_1 + odd_0
otherwise,
change := even_1 + odd_0
change := even_1 + odd_0
return change
return change
Let us see the following implementation to get better understanding &minnus;
 Live Demo
def solve(s):
   change = 0
   even_1 = 0
   even_0 = 0
   odd_1 = 0
   odd_0 = 0
   for i in range(len(s)):
      if(i%2 == 0):
         if(s[i]=='1'):
            even_1 +=1
         else:
            even_0 +=1
      else:
         if(s[i] == '1'):
            odd_1 +=1
         else:
            odd_0 +=1
   if((even_1+odd_0)>(even_0+odd_1)):
      change = even_0 + odd_1
   else:
      change = even_1 + odd_0
   return change

s = "11100011"
print(solve(s))
"11100011"
3
\limits - Tex Command

\limit - Used to set limits above/below any token of class OP.
{ \limit }
\limit command is used to set limits above/below any token of class OP.

\int_a^b f(x)\,dx

∫abf(x)dx


\int\limits_a^b f(x)\,dx

∫abf(x)dx


\mathop{x}\limits_0^1

x01



\int_a^b f(x)\,dx

∫abf(x)dx


\int_a^b f(x)\,dx
\int\limits_a^b f(x)\,dx

∫abf(x)dx


\int\limits_a^b f(x)\,dx
\mathop{x}\limits_0^1

x01


\mathop{x}\limits_0^1

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Python - Custom Lower bound a List - GeeksforGeeks

11 Oct, 2020
Given a list, assign a custom lower-bound value to it.
Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 3 Output : [5, 7, 8, 3, 3, 5, 3] Explanation : All elements less than 3, assigned 3.
Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5 Output : [5, 7, 8, 5, 5, 5, 5] Explanation : All elements less than 5, assigned 5. 
Method #1: Using list comprehension
In this, we check for each element if it’s lower than lower-bound, if yes, then assign the decided lower-bound to that element.
Python3
# Python3 code to demonstrate working of # Custom Lowerbound a List# Using list comprehension  # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1]  # printing original listprint("The original list is : " + str(test_list))  # initializing LowerboundK = 4   # checking for elements and assigning Lowerboundsres = [ele if ele >= K else K for ele in test_list]  # printing result print("List with Lowerbounds : " + str(res))
The original list is : [5, 7, 8, 2, 3, 5, 1]
List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]

Method #2 : Using list comprehension + max()
In this, we perform comparison using max(), assign max of the element, or the lower-bound as decided.
Python3
# Python3 code to demonstrate working of # Custom Lowerbound a List# Using list comprehension + max()  # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1]  # printing original listprint("The original list is : " + str(test_list))  # initializing LowerboundK = 4   # max() is used to compare for Lowerboundres = [max(ele, K) for ele in test_list]  # printing result print("List with Lowerbounds : " + str(res))
The original list is : [5, 7, 8, 2, 3, 5, 1]
List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]

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 | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Can we override a protected method in Java?

Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.
class A {
   protected void protectedMethod() {
      System.out.println("superclass protected method");
   }
}
class B extends A {
   protected void protectedMethod() {
      System.out.println("subclass protected method");
   }
}
public class Test {
   public static void main(String args[]) {
      B b = new B();
      b.protectedMethod();
   }
}
subclass protected method
What are member functions of a class in C#?

A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on an object of the class of which it is a member, and has access to all the members of a class for that object.
The following is an example of a member function −
public void setLength( double len ) {
   length = len;
}
public void setBreadth( double bre ) {
   breadth = bre;
}
The following is an example showing how to access member functions in C#.
 Live Demo
using System;

namespace BoxApplication {
   class Box {
      private double length; // Length of a box
      private double breadth; // Breadth of a box
      private double height; // Height of a box

      public void setLength( double len ) {
         length = len;
      }

      public void setBreadth( double bre ) {
         breadth = bre;
      }

      public void setHeight( double hei ) {
         height = hei;
      }

      public double getVolume() {
         return length * breadth * height;
      }
   }

   class Boxtester {
      static void Main(string[] args) {
         Box Box1 = new Box(); // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;

         // Declare Box2 of type Box
         // box 1 specification
         Box1.setLength(8.0);
         Box1.setBreadth(9.0);
         Box1.setHeight(7.0);

         // box 2 specification
         Box2.setLength(18.0);
         Box2.setBreadth(20.0);
         Box2.setHeight(17.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         Console.ReadKey();
      }
   }
}
Volume of Box1 : 504
Volume of Box2 : 6120
Complexity Cheat Sheet for Python Operations - GeeksforGeeks

24 Feb, 2022
Prerequisite: List, Dictionaries, Sets 
Python built-in data structures like list, sets, dictionaries provide a large number of operations making it easier to write concise code but not being aware of their complexity can result in unexpected slow behavior of your python code. 
For example: 
A simple dictionary lookup Operation can be done by either :  
if key in d:
or
if dict.get(key)
The first has a time complexity of O(N) for Python2, O(1) for Python3 and the latter has O(1) which can create a lot of difference in nested statements. 
Important points:  
Lists are similar to arrays with bidirectional adding and deleting capability.Dictionaries and Set use Hash Tables for insertion/deletion and lookup operations.
Lists are similar to arrays with bidirectional adding and deleting capability.
Dictionaries and Set use Hash Tables for insertion/deletion and lookup operations.
This Cheat sheet can be referred for choosing operations that are efficient with respect to time. 
 
For more information, refer to Internal working of list in Python. 
Note: Tuples have the same operations (non-mutable) and complexities. 
 
Note: Defaultdict has operations same as dict with same time complexity as it inherits from dict. 
 
 
For more information, refer to Internal working of Set in Python 
Note: Frozen sets have the same operations (non-mutable) and complexities. 
 
kk773572498
kvtoraman
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
OpenCV - Alpha blending and masking of images - GeeksforGeeks

16 Mar, 2021
Alpha blending is the process of overlaying a foreground image on a background image.
We take these two images to blend :
gfg.png
apple.jpeg
Steps :
First, we will import OpenCV.
We read the two images that we want to blend.
The images are displayed.
We have a while loop that runs while the choice is 1.
Enter an alpha value.
Use cv2.addWeighted() to add the weighted images.
We display and save the image as alpha_{image}.png.
To continue and try out more alpha values, press 1. Else press 0 to exit.
Python3
import cv2  img1 = cv2.imread('gfg.png')img2 = cv2.imread('apple.jpeg')  img2 = cv2.resize(img2, img1.shape[1::-1])  cv2.imshow("img 1",img1)  cv2.waitKey(0)  cv2.imshow("img 2",img2)  cv2.waitKey(0)  choice = 1  while (choice) :      alpha = float(input("Enter alpha value"))      dst = cv2.addWeighted(img1, alpha , img2, 1-alpha, 0)      cv2.imwrite('alpha_mask_.png', dst)      img3 = cv2.imread('alpha_mask_.png')      cv2.imshow("alpha blending 1",img3)      cv2.waitKey(0)      choice = int(input("Enter 1 to continue and 0 to exit"))
Outputs:
alpha = 0.8
alpha = 0.5
Alpha masking:
We can create a black and white mask from an image with a transparent background.
Python3
import cv2im = cv2.imread("spectacles.png", cv2.IMREAD_UNCHANGED)_, mask = cv2.threshold(im[:, :, 3], 0, 255, cv2.THRESH_BINARY)cv2.imwrite('mask.jpg', mask)
Output:
OpenCV
Picked
Python-OpenCV
Python
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
Class getEnclosingMethod() method in Java with Examples - GeeksforGeeks

27 Jan, 2022
The getEnclosingMethod() method of java.lang.Class class is used to get the enclosing methods of this class. The method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method. Else this method returns null.Syntax:  
public Method getEnclosingMethod()
Parameter: This method does not accept any parameter.Return Value: This method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method. Else this method returns null.Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getEnclosingMethod() method.Example 1: 
Java
// Java program to demonstrate getEnclosingMethod() method import java.util.*; public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {         // returns the Class object for this class        Class myClass = Class.forName("Test");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the enclosing methods of myClass        // using getEnclosingMethod() method        System.out.println("EnclosingMethod of myClass: "                           + myClass.getEnclosingMethod());    }}
Class represented by myClass: class Test
EnclosingMethod of myClass: null
 
Example 2: 
Java
// Java program to demonstrate getEnclosingMethod() method import java.util.*; class Main {     public Object obj;     public Object func()    {        class Arr {        };        return new Arr();    }     public static void main(String[] args)        throws ClassNotFoundException    {        Main t = new Main();         // returns the Class object        Class myClass = t.func().getClass();         // Get the enclosing constructors of myClass        // using getEnclosingConstructor() constructor        System.out.println("getEnclosingMethod of myClass: "                           + myClass.getEnclosingMethod());    }}
EnclosingConstructor of myClass: public java.lang.Object Main.func()
 
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnclosingMethod– 
saurabh1990aror
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Overriding in Java
Lazy Loading in ReactJS

In this article, we will learn how to lazily load the pages of our application to make our React application more optimized.
React apps are bundled with the preinstalled bundlers like webpack before making the React application to be production ready. When this bundled project is loaded, it loads the whole source code at once, even those pages which are rarely visited by the user. So, to prevent the entire loading of the application at once, we use the concept of lazy loading to decrease the DOM load time and to increase the speed of the application.
const OtherComponent = React.lazy(() => import('./OtherComponent'));
Here, OtherComponent is the component which is going to be lazily loaded.
In this example, we will build a Routing application which lazily loads the component.
App.jsx
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react -router-dom';

const About = lazy(() => import('./About'));

const App = () => (
   <Router>
   <Suspense fallback={<div>Loading...</div>}>
   <Switch>
   <Route path="/about" component={About} />
   <Route
      path="/"
      exact
      render={() => (
      <div>
         <h1>This is the main page</h1>
         <a href="/about">Click here</a>
      </div>
      )}
   />
   </Switch>
   </Suspense>
   </Router>
);
export default App;
About.js
import React from 'react';

const About = () => {
   return (
      <div>
         <h1>This is the about section</h1>
      </div>
   );
};
export default About;
In the above example, when the user clicks on the 'click here' button. the about.js script is lazily loaded and the DOM is updated accordingly.
This will produce the following result.
Java Program to check whether a file exists or not

The method java.io.File.exists() is used to check whether a file exists or not. This method returns true if the file specified by the abstract path name exists and false if it does not exist.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("File exists? " + file.exists());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
File exists? true
Now let us understand the above program.
The method java.io.File.exists() is used to check whether the file exists or not and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows −
try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("File exists? " + file.exists());
} catch(Exception e) {
   e.printStackTrace();
}
Select a row of series or dataframe by given integer index - GeeksforGeeks

28 Jul, 2020
Dataframe.iloc[]  is used to select a row of series/dataframe by given integer index. Let’s Create a Data Frame:
Code:
Python3
# import pandas libraryimport pandas as pd   # Create the dataframe df = pd.DataFrame({'ID': ['114', '345',                         '157788', '5626'],                 'Product': ['shirt', 'trousers',                           'tie', 'belt'],                 'Price': [1200, 1500,                         600, 352],                 'Color': ['White','Black',                          'Red', 'Brown'],                 'Discount': [10, 10,                            10, 10]})   # Show the dataframedf
Output:
Now, Selecting a row of series/dataframe by a given integer index:Example 1: Selecting the first row only.
Python3
# select first row # from the dataframedf.iloc[0]
Output:  
Example 2: Selecting  0,1,2  rows.
Python3
# select 0, 1, 2 rows#from the dataframedf.iloc[0 : 3]
Output: 
Example 3: Selecting rows from 0 to 2 and columns 0 to 1.
Python3
# selecting rows from 0 to# 2 and columns 0 to 1df.iloc[0 : 3, 0 : 2]
Output:  
Example 4: Selecting all rows and columns from 0 to 3. 
Python3
# selecting all rows and # columns from 0 to 3df.iloc[ : , 0 : 4]
Output: 
Example 5: Selecting all rows and 2nd column.
Python3
# selecting all rows and # 3rd columndf.iloc[ : , 2]
Output: 
Python pandas-dataFrame
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
How do we print a variable at the MongoDB command prompt?

In order to print a variable at the MongoDB command prompt, use the following syntax
//Declaring and Initializing a variable.
var anyVariableName=yourValue;
//To print the above variable.
yourVariableName;
Or
print(yourVariableName);
Following is how you can declare and initialize a variable at the MongoDB command prompt
> var myIntegerValue=20;
Print a variable at the MongoDB command prompt:
> myIntegerValue
This will produce the following output
20
You can also use print(). Following is the query
> print(myIntegerValue);
This will produce the following output
20
Let us see another example. Following is the query to declare and initialize a string variable at MongoDB shell.
> var myStringValue="Hello MongoDB!!!";
Following is the query to print a variable at the MongoDB command prompt.
> myStringValue
This will produce the following output
Hello MongoDB!!!
You can also use print(). Following is the query
> print(myStringValue);
This will produce the following output
Hello MongoDB!!!
GATE | GATE-CS-2007 | Question 45 - GeeksforGeeks

28 Jun, 2021
What is the time complexity of the following recursive function:
int DoSomething (int n) {  if (n <= 2)    return 1;  else      return (DoSomething (floor(sqrt(n))) + n);}
(A) (n)(B) (nlogn)(C) (logn)(D) (loglogn)(A) A(B) B(C) C(D) DAnswer: (D)Explanation: See Question 5 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/Quiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
HTML DOM Range insertNode() Method - GeeksforGeeks

07 Jul, 2020
The insertNode() method inserts a node at the start of the Range.
The updated Range consists of new inserted node before the Range of the last Range content.
Syntax:
range.insertNode( newNode );
Parameters: This method accepts single parameter as mentioned above and described below:
newNode: The Node to be inserted at the starting of the range.
Return value: This method does not return any value.
Example: This example shows how to insert a node before the range content using insertNode() method. To Clarify, changes in range content, we had console logged the new range in string text using toString() method.
HTML
<!DOCTYPE html><html>  <head>    <title>        HTML DOM range insertNode() method    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <p>Range Content</p>      <button onclick="insert()">        Click Here to insert the Node    </button>          <p id="element">Node element </p>      <script>        var range = document.createRange();        range.selectNode(document            .getElementsByTagName("p").item(0));                  const element = document            .getElementById('element');          console.log("Before Button Click:",                             range.toString());          function insert() {            range.insertNode(element);            console.log("After  Button Click:",                             range.toString());        }    </script></body>  </html>
Output:
Before Click the Button:
Before Click the Button:
After Click the Button:
After Click the Button:
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
Internet Explorer
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
HTML-Methods
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Java | Exception Handling | Question 4 - GeeksforGeeks

28 Jun, 2021
class Base extends Exception {}class Derived extends Base  {}  public class Main {  public static void main(String args[]) {   // some other stuff   try {       // Some monitored code       throw new Derived();    }    catch(Base b)     {        System.out.println("Caught base class exception");     }    catch(Derived d)  {        System.out.println("Caught derived class exception");     }  }} 
(A) Caught base class exception(B) Caught derived class exception(C) Compiler Error because derived is not throwable(D) Compiler Error because base class exception is caught before derived classAnswer: (D)Explanation: See Catching base and derived classes as exceptions
Following is the error in below program
Main.java:12: error: exception Derived has already been caught
    catch(Derived d)  { System.out.println("Caught derived class exception"); } 
Quiz of this Question
Exception Handling
Java-Exception Handling
Java Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Constructors | Question 5
Java | Functions | Question 1
Java | final keyword | Question 1
Java | Inheritance | Question 8
Java | Arrays | Question 1
Java | Operators | Question 1
Java | Operators | Question 3
Java | Inheritance | Question 7
Java | Functions | Question 4
Java | Inheritance | Question 5
How to write a running C code without main()?

Here we will see, one program can be written without main or not? The answer is yes. We can write program, that has no main() function.
In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true. From the system’s perspective it is not true. So the system at first calls the _start(), this sets up the environment, then main is called.
To execute this program we have to use this option ‘-nostartfiles’.
#include <stdio.h>
extern void _exit(register int);
int _start() {
   printf("Program without main\n");
      _exit(0);
}
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc test_prog.c -nostartfiles
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out
Program without main
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$
How can I remove items out of a Python tuple?

Tuples in python are immutable. If you want to remove items out of a Python tuple, you can use index slicing to leave out a particular index. For example,
a = (1, 2, 3, 4, 5)
b = a[:2] + a[3:]
print(b)
This will give the output:
(1, 2, 4, 5)
Or you can convert it to a list, remove the item and convert back to a tuple. For example,
a = (1, 2, 3, 4, 5)
ls_a = list(a)
del ls_a[2]

b = tuple(ls_a)
print(b)
This will give the output:
(1, 2, 4, 5)
GATE CS 2021 | Set 2 - GeeksforGeeks

18 Oct, 2021
Pen : Write :: Knife : _______ 
From the above graph we obtained following information- 
Year    Cost/Unit   Cost Price    Number of Units
1             3              300             100
2             2              400             200
3             1              300             300
Let selling price of year 2 = SP2 and Selling price of year3 = SP3
Given that-
Taxes for year 2 = 13% of SP2 = 0.13SP2
Taxes for year 3 = 15% of SP3 = 0.15SP3
Cost per unit of year 3 = 1
(Cost per unit of year 2)/2 = 1
So now Cost / unit of year 2 = 2*1 = 2
Net profit formula now = Selling Price - (Cost Price + (Tax% x selling price )
For year 2
296 = SP2- (200*2 + 0.13*SP2)
SP2 = 696*100/87
SP2 = 800
For year 3
210 = SP3 - (300*1+0.15*SP3)
SP3 = 510*100/85
SP3 = 600
Required Ratio 800/600= 4/3 (Correct Option A)
Observation I: S is taller than R.
Observation II: Q is the shortest of all.
Observation III: U is taller than only one student.
Observation IV: T is taller than S but is not the tallest.
 __ __ __ __ U Q 
P T S R U Q 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Hash Functions and list/types of Hash functions
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
Python Data Structures and Algorithms
Java Examples - Display text in different fonts

How to display text in different fonts?
Following example demonstrates how to display text in different fonts using setFont() method of Font class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JPanel {
   String[] type = { "Serif","SansSerif"}; 
   int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
   String[] stylenames = { "Plain", "Italic", "Bold", "Bold & Italic" };
   
   public void paint(Graphics g) {
      for (int f = 0; f < type.length; f++) { 
         for (int s = 0; s < styles.length; s++) { 
            Font font = new Font(type[f], styles[s], 18);
            g.setFont(font); 
            String name = type[f] + " " + stylenames[s];
            g.drawString(name, 20, (f * 4 + s + 1) * 20); 
         }
      }
   }
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      f.setContentPane(new Main());
      f.setSize(400,400);
      f.setVisible(true);
   }
}
The above code sample will produce the following result.
Different font names are displayed in a frame.

The following is an another sample example to display text in different fonts
import java.awt.*;
import javax.swing.*;

public class Main extends JComponent {
   String[] dfonts;
   Font[] font;
   static final int IN = 15;
   public Main() {
      dfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
       font = new Font[dfonts.length];
   }
   public void paintComponent(Graphics g) {
      for (int j = 0; j < dfonts.length; j += 1) {
         if (font[j] == null) {
            font[j] = new Font(dfonts[j], Font.PLAIN, 16);
         } 
         g.setFont(font[j]);
         int p = 15;
         int q = 15+ (IN * j);
         g.drawString(dfonts[j],p,q);
      } 
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("Different Fonts");
      frame.getContentPane().add(new JScrollPane(new Main()));
      frame.setSize(350, 650);
      frame.setVisible(true);
   }
} 
 Print
 Add Notes
 Bookmark this page
Frequency of vowels and consonants in JavaScript

We are required to write a JavaScript function that takes in a string which contains English
alphabets. The function should return an object containing the count of vowels and consonants
in the string.
Therefore, let’s write the code for this function −
The code for this will be −
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));
The output in the console will be −
{ vowels: 17, consonants: 29 }