code-rag-bench/online-tutorials huggingface dataset:
Overloaded method and ambiguity in C#

With method overloading, you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.
Let us see an example. In this the call would go to the method with a single parameter −
using System;

class Student {
   static void DisplayMarks(int marks1 = 90) {
      Console.WriteLine("Method with one parameter!");
   }

   static void DisplayMarks(int marks1, int marks2 = 95) {
      Console.WriteLine("Method with two parameters!");
   }

   static void Main() {
      DisplayMarks(97);
   }
}
Now let us see what creates an ambiguous call. Here the confusion is that the second method would need two arguments as defaults, whereas the first methid needs one argument to be defaulted. This creates ambiguity.
using System;

class Student {
   static void DisplayMarks(int marks1 = 90, int marks2 = 80) {
      Console.WriteLine("Method with two parameters!");
   }

   static void DisplayMarks(int marks1, int marks2 = 80, marks3 = 98) {
      Console.WriteLine("Method with three parameters!");
   }

   static void Main() {
      DisplayMarks(80);
   }
}
How to concatenate byte array in java?

You ByteArrayOutputStream to write byte arrays and get the result using its toByteArray() method.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Tester {
   public static void main(String[] args) throws IOException {
      byte[] a = { 1,2,3};
      byte[] b = { 4,5,6};
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      baos.write(a);
      baos.write(b);
      byte[] c = baos.toByteArray();
      for(int i=0; i< c.length ; i++){
         System.out.print(c[i] +" ");
      }
   }
}
1 2 3 4 5 6
Binning method for data smoothing in Python

Many times we use a method called data smoothing to make the data proper and qualitative for statistical analysis. During the smoking process we define a range also called bin and any data value within the range is made to fit into the bin. This is called the binning method. Below is an example of binning. Then we will see how we can achieve the binning method using a Python program.
Let’s take a series of numbers. Find the maximum and minimum values. Decide on the number of bins we need depending on how many data points the analysis needs. Create these groups and assign each of these numbers to this groups.The upper value is excluded and belongs to next group.
Given numbers: 12, 32, 10, 17, 19, 28, 22, 26, 29,16
Number of groups : 4
Here
Max Value: 32
Min Value: 10
So the groups are –
(10-15), (15-21), (21-27), (27-32)
On putting the numbers into bins, we get the following result −
12 -> (10-15)
32 -> (27-32)
10 -> (10-15)
17 -> (15-21)
19 -> (15-21)
28 -> (27-32)
22 -> (21-27)
26 -> (21-27)
29 -> (27-32)
16 -> (15-21)
For this program we define two functions. One for creating the bins by defining the upper and lower bounds. The other function is to assign the input values to each of the bin. Each of the bin also gets an index. We see how each of the input value is assigned to the bin and keep track of how many values go to a specific bin.
 Live Demo
from collections import Counter
def Binning_method(lower_bound, width, quantity):
   binning = []
   for low in range(lower_bound, lower_bound + quantity * width + 1, width):
      binning.append((low, low + width))
   return binning
def bin_assign(v, b):
   for i in range(0, len(b)):
      if b[i][0] <= v < b[i][1]:
         return i
the_bins = Binning_method(lower_bound=50,
   width=4,
   quantity=10)
print("The Bins: \n",the_bins)
weights_of_objects = [89.2, 57.2, 63.4, 84.6, 90.2, 60.3,88.7, 65.2, 79.8, 80.2, 93.5, 79.3,72.5, 59.2, 77.2, 67.0, 88.2, 73.5]
print("\nBinned Values:\n")
binned_weight = []
for val in weights_of_objects:
   index = bin_assign(val, the_bins)
   #print(val, index, binning[index])
   print(val,"-with index-", index,":", the_bins[index])
   binned_weight.append(index)
freq = Counter(binned_weight)
print("\nCount of values in each index: ")
print(freq)
Running the above code gives us the following result −
The Bins:
   [(50, 54), (54, 58), (58, 62), (62, 66), (66, 70), (70, 74), (74, 78), (78, 82), (82, 86), (86, 90), (90, 94)]
Binned Values:
89.2 -with index- 9 : (86, 90)
57.2 -with index- 1 : (54, 58)
63.4 -with index- 3 : (62, 66)
84.6 -with index- 8 : (82, 86)
90.2 -with index- 10 : (90, 94)
60.3 -with index- 2 : (58, 62)
88.7 -with index- 9 : (86, 90)
65.2 -with index- 3 : (62, 66)
79.8 -with index- 7 : (78, 82)
80.2 -with index- 7 : (78, 82)
93.5 -with index- 10 : (90, 94)
79.3 -with index- 7 : (78, 82)
72.5 -with index- 5 : (70, 74)
59.2 -with index- 2 : (58, 62)
77.2 -with index- 6 : (74, 78)
67.0 -with index- 4 : (66, 70)
88.2 -with index- 9 : (86, 90)
73.5 -with index- 5 : (70, 74)
Count of values in each index:
Counter({9: 3, 7: 3, 3: 2, 10: 2, 2: 2, 5: 2, 1: 1, 8: 1, 6: 1, 4: 1})
Adding new property to each document in a large MongoDB collection?

You can use update command along with forEach() for large collection. Let us first create a collection with documents
>db.addingNewPropertyDemo.insertOne({"StudentName":"John","StudentAge":23,"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e61866324ffac2a7dc56")
}
>db.addingNewPropertyDemo.insertOne({"StudentName":"David","StudentAge":21,"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e62366324ffac2a7dc57")
}
>db.addingNewPropertyDemo.insertOne({"StudentName":"Bob","StudentAge":21,"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e62d66324ffac2a7dc58")
}
Following is the query to display all documents from a collection with the help of find() method
> db.addingNewPropertyDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca1e61866324ffac2a7dc56"),
   "StudentName" : "John",
   "StudentAge" : 23,
   "CountryName" : "US"
}
{
   "_id" : ObjectId("5ca1e62366324ffac2a7dc57"),
   "StudentName" : "David",
   "StudentAge" : 21,
   "CountryName" : "AUS"
}
{
   "_id" : ObjectId("5ca1e62d66324ffac2a7dc58"),
   "StudentName" : "Bob",
   "StudentAge" : 21,
   "CountryName" : "UK"
}
Following is the query to add new property to each document in a large collection
> db.addingNewPropertyDemo.find().forEach(function(data){ db.addingNewPropertyDemo.update({_id: data._id}, {$set: { StudentNameInUpperCase: data.StudentName.toUpperCase() }}) });
Let us check a new property is added or not
> db.addingNewPropertyDemo.find().pretty();
Following is the output displaying the new property as well
{
   "_id" : ObjectId("5ca1e61866324ffac2a7dc56"),
   "StudentName" : "John",
   "StudentAge" : 23,
   "CountryName" : "US",
   "StudentNameInUpperCase" : "JOHN"
}
{
   "_id" : ObjectId("5ca1e62366324ffac2a7dc57"),
   "StudentName" : "David",
   "StudentAge" : 21,
   "CountryName" : "AUS",
   "StudentNameInUpperCase" : "DAVID"
}
{
   "_id" : ObjectId("5ca1e62d66324ffac2a7dc58"),
   "StudentName" : "Bob",
   "StudentAge" : 21,
   "CountryName" : "UK",
   "StudentNameInUpperCase" : "BOB"
}
Look at the above sample output, StudentNameInUpperCase property is added.
PHP include Statement

PHP code in one file can be made available for use in another PHP script with the help of include statement. This feature enables modular program development by writing functions and classes once and calling wherever needed.
The include statement checks for the file in current folder by default and further in directories mentioned in include_path setting of php.ini. If file asked for is not available in current folder as well as include_path folders, PHP parser emits E_WARNING and execution of calling module continues.
The included file can access variables defined in calling module prior to inclusion. Such variables will have global scope.
In following example main php script includes test.php
 Live Demo
<?php
echo "inside main script\n";
$var1=100;
echo "now calling test.php script\n";
include "test.php";
echo "returns from test.php";
?>
//test.php
<?php
$var2=200;
//accessing $var1 from main script
echo $var1+$var2 . "\n";
?>
This will produce following result when main script is run from command line −
inside main script<br />now calling test.php script<br /><br />300<br />returns from test.php
In following example,attempt to include nonexisting file results in warning
 Live Demo
<?php
echo "inside main script\n";
$var1=100;
echo "now calling nosuchfile.php script\n";
include "nosuchfile.php";
echo "returns from nosuchfile.php";
?>
This will produce following result. Note that program doesn't teerminate on warning −
inside main script
now calling nosuchfile.php script
PHP Warning: include(nosuchfile.php): failed to open stream: No such file or directory in line 5
PHP Warning: include(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 5
returns from nosuchfile.php
In next example, test.php is included inside a function. Code inside included file will be treated as part of function. Hence variables in the include file will not accessible outside the function
 Live Demo
//main script
<?php
function myfunction(){
   $var1=100;
   include "test.php";
   echo $var1+$var2."\n";
}
myfunction();
echo "variable from included file outside function: $var2";
?>
//test.php included
<?php
echo "test.php called from inside function\n";
$var2=200;
return;
?>
This will produce following result when main script is run from command line−
100
test.php called from inside function
PHP Notice: Undefined variable: var2 in C:\xampp\php\testscript.php on line 9
Notice: Undefined variable: var2 in C:\xampp\php\testscript.php on line 9
variable from included file outside function
The include statement returns TRUE on success and FALSE on failure. If the include file explicitly returns an expression, it can be used by calling module for further processing.
//main script
<?php
$result=include "test.php"; // returns value
echo "retun value : $result\n";
$y=include "test1.php"; //with return only
echo "return value : $y\n";
$x=include "test2.php"; //no return statement
echo "return value : $x\n";
?>
//test.php
<?php
$var=100;
return $var;
?>
//test1.php
<?php
$var=100;
return;
?>
//test2.php
<?php
$var=100;
?>
This will produce following result −
retun value : 100
return value :
return value : 1
RxJS - Observables

An observable is a function that creates an observer and attaches it to the source where values are expected from, for example, clicks, mouse events from a dom element or an Http request, etc.
Observer is an object with callback functions, that will get called when there is interaction to the Observable, i.e., the source has interacted for an example button click, Http request, etc.
We are going to discuss following topics in this chapter −
Create Observable
Subscribe Observable
Execute Observable
The observable can be created using observable constructor and also using observable create method and by passing subscribe function as an argument to it as shown below −
import { Observable } from 'rxjs';

var observable = new Observable(
   function subscribe(subscriber) {
      subscriber.next("My First Observable")
   }
);
We have created an observable and added a message “My First Observable” using subscriber.next method available inside Observable.
We can also create Observable using, Observable.create() method as shown below −
import { Observable } from 'rxjs';
var observer = Observable.create(
   function subscribe(subscriber) {
      subscriber.next("My First Observable")
   }
);
You can subscribe to an observable as follows −
import { Observable } from 'rxjs';

var observer = new Observable(
   function subscribe(subscriber) {
      subscriber.next("My First Observable")
   }
);
observer.subscribe(x => console.log(x));
When the observer is subscribed, it will start the execution of the Observable.
This is what we see in the browser console −
An observable gets executed when it is subscribed. An observer is an object with three methods that are notified,
next() − This method will send values like a number, string, object etc.
complete() − This method will not send any value and indicates the observable as completed.
error() − This method will send the error if any.
Let us create the observable with all three notifications and execute the same.
import { Observable } from 'rxjs';
var observer = new Observable(
   function subscribe(subscriber) {
      try {
         subscriber.next("My First Observable");
         subscriber.next("Testing Observable");
         subscriber.complete();
      } catch(e){
         subscriber.error(e);
      }
   }
);
observer.subscribe(x => console.log(x), (e)=>console.log(e), 
   ()=>console.log("Observable is complete"));
In the above code, we have added, next, complete and error method.
try{
   subscriber.next("My First Observable");
   subscriber.next("Testing Observable");
   subscriber.complete();
} catch(e){
   subscriber.error(e);
}
To execute next, complete and error, we have to call the subscribe method as shown below −
observer.subscribe(x => console.log(x), (e)=>console.log(e), 
   ()=>console.log("Observable is complete"));

The error method will be invoked only if there is an error.
This is the output seen in the browser −

    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
How to count rows – count (*) and Java

The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.
select count(*) from TABLE_NAME;
Let us create a table with name cricketers_data in MySQL database using CREATE statement as shown below −
CREATE TABLE cricketers_data(
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Date_Of_Birth date,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255),
);
Now, we will insert 5 records in cricketers_data table using INSERT statements −
insert into cricketers_data values('Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into cricketers_data values('Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into cricketers_data values('Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into cricketers_data values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into cricketers_data values('Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
Following JDBC program establishes connection with MySQL and displays the number of rows in the table named cricketers_data.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Count_Example {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement object
      Statement stmt = con.createStatement();
      //Query to get the number of rows in a table
      String query = "select count(*) from Cricketers_Data";
      //Executing the query
      ResultSet rs = stmt.executeQuery(query);
      //Retrieving the result
      rs.next();
      int count = rs.getInt(1);
      System.out.println("Number of records in the cricketers_data table: "+count);
   }
}
Connection established......
Number of records in the cricketers_data table: 5
Simple Data Profiling with SQL. Before jumping in , understand the true... | by Robert de Graaf | Towards Data Science

Many organizations store their data in SQL compliant databases. It is far from unheard of for those databases to have grown organically for at least part of their lifecycle, so tables may or may not contain what their label would make you think they contain, and the quality may or may not match your expectations and be useful for your application.
In any case, the original purpose of creating the database was seldom to create a convenient well structured environment for a data scientist to use a basis for analysis. Therefore, although you are itching to migrate that data into R or Python to analyze and hopefully build a model with it, you need to figure out which data is what you need, and which of it meets basic standards of data quality to make it worth modeling with.
It’s true that major database packages have tools specifically for data profiling. However, it is also noticeable that these tools are complex to learn and sometimes seem to be a sledgehammer to crack a walnut. What’s really needed is some simple queries that can get the job done quickly.
In earlier articles in this series, we looked at quantiles in SQL, and exploratory stats on missing values in SQL. This time we will look at identifying unique values and exploring how frequently they occur.
Unique values by themselves are not difficult to identify — SQL has a built in keyword DISTINCT which limits the rows returned to those having unique values. Hence, it is trivial to discover the number of values for any row by creating a query SELECT DISTINCT col_name from Table and seeing how many rows are returned.
Simply knowing the number of unique values in a specific colum is a little useful, but possibly not as useful as knowing the number of times each value occurs in the event the variable is categorical (and multiple occurrences of most values might be a strong sign that this is a categorical value if you don’t know in advance).
This is also relatively simple, as you can put keywords such as DISTINCT into the brackets of an aggregate such as COUNT. Hence
select count(DISTINCT x) from tablegroup by x
More useful is to know the proportion of variables which are unique. This can be helpful if fields are poorly labelled, and you need to double check which columns could be unique ids — and also to avoid mistaking a field meant as a simple identifier with a field that contains information. Don’t forget that as COUNT returns an integer, you need to convert the result to get a fraction:
select cast(count(DISTINCT x) as decimal)/count(X) from table
For categorical variables, understanding the number of unique values is an important step towards understanding the overall usefulness of your overall data set.
Robert de Graaf’s book, Managing Your Data Science Projects, is out now through Apress.
Follow Robert on Twitter
Tryit Editor v3.7

CSS How To
Tryit: Cascading order
How to create an image to zoom with CSS and JavaScript?

Following is the code to create an image zoom:
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
   * {box-sizing: border-box;}
   .img{
      display: inline-block;
   }
   .img-zoom-container {
      position: relative;
   }
   .img-zoom-zoomLens {
      position: absolute;
      border: 1px solid #d4d4d4;
      width: 50px;
      height: 50px;
   }
   .myresult{
      display: inline-block;
   }
   .img-zoom-result {
      border: 1px solid #d4d4d4;
   }
</style>
</head>
<body>
<h1>Image Zoom Example</h1>
<div class="img-zoom-container">
<img class="myimage" src="https://i.picsum.photos/id/1015/536/354.jpg?hmac=x7KEhPoOftwPXIgnQoTQzNtVUqaPYwndK8n1x_9rWuM" style="width: 400px; height: 400px;">
<div class="myresult" class="img-zoom-result" style="width: 400px;height: 400px;"></div>
</div>
<h1>Hover over the image on the left to see it zoomed on right</h1>
<script>
   let imageEle = document.querySelector('.myimage');
   let resultEle = document.querySelector('.myresult');
   enlargeImage(imageEle, resultEle);
   function enlargeImage(imgEle, resultEle) {
      var zoomLens, xPos, yPos;
      zoomLens = document.createElement("DIV");
      zoomLens.setAttribute("class", "img-zoom-zoomLens");
      imgEle.parentElement.insertBefore(zoomLens, imgEle);
      xPos = resultEle.offsetWidth / zoomLens.offsetWidth;
      yPos = resultEle.offsetHeight / zoomLens.offsetHeight;
      resultEle.style.backgroundImage = `url(${imgEle.src})`;
      resultEle.style.backgroundSize = (imgEle.width * xPos) + "px " + (imgEle.height * yPos) + "px";
      zoomLens.addEventListener("mousemove", lensMoveCalculate);
      imgEle.addEventListener("mousemove", lensMoveCalculate);
      zoomLens.addEventListener("touchmove", lensMoveCalculate);
      imgEle.addEventListener("touchmove", lensMoveCalculate);
      function lensMoveCalculate(e) {
         var pos, x, y;
         pos = currentCursonPos(e);
         x = pos.x - (zoomLens.offsetWidth / 2);
         y = pos.y - (zoomLens.offsetHeight / 2);
         if (x > imgEle.width - zoomLens.offsetWidth) {x = imgEle.width - zoomLens.offsetWidth;}
         if (x < 0) {x = 0;}
         if (y > imgEle.height - zoomLens.offsetHeight) {y = imgEle.height - zoomLens.offsetHeight;}
         if (y < 0) {y = 0;}
         zoomLens.style.left = x + "px";
         zoomLens.style.top = y + "px";
         resultEle.style.backgroundPosition = "-" + (x * xPos) + "px -" + (y * yPos) + "px";
      }
      function currentCursonPos(e) {
         var a, x = 0, y = 0;
         e = e || window.event;
         a = imgEle.getBoundingClientRect();
         x = e.pageX - a.left;
         y = e.pageY - a.top;
         x = x - window.pageXOffset;
         y = y - window.pageYOffset;
         return {x : x, y : y};
      }
   }
</script>
</body>
</html>
The above code will produce the following output:
Best First Search (Informed Search)

Best first search is a traversal technique that decides which node is to be visited next by checking which node is the most promising one and then check it. For this it uses an evaluation function to decide the traversal.
This best first search technique of tree traversal comes under the category of heuristic search or informed search technique.
The cost of nodes is stored in a priority queue. This makes implementation of best-first search is same as that of breadth First search. We will use the priorityqueue just like we use a queue for BFS.
Step 1 : Create a priorityQueue pqueue.
Step 2 : insert ‘start’ in pqueue : pqueue.insert(start)
Step 3 : delete all elements of pqueue one by one.
   Step 3.1 : if, the element is goal . Exit.
   Step 3.2 : else, traverse neighbours and mark the node examined.
Step 4 : End.
This algorithm will traverse the shortest path first in the queue. In worst case scenario the algorithm takes O(n*logn) time.
Facebook Login using Python

We can use the python package called selenium to automate the interaction with webdrivers. In this article we will see the interaction between python’s selenium package and logging in to Facebook.
Selenium package is used to automate and controls web browsers activity. Out python code will need the selenium package to be installed and also a driver software known as geckodriver to be available for the program. Below are the steps to achieve this.
Install selenium in you python environment
pip install selenium
Download the geckodriver from this link. Place it in the same directory where we are going to have this python script.
Next we create the program which will import the relevant modules form the selenium package and able to open the webpage for login.
To get the id details of the input boxes for login, we can view the source code of the webpage facebook.com and find the id of the fields as follows.
The code below contains the comments that explain the purpose of the code segments.
from selenium import webdriver
#Open Firefox
browser = webdriver.Firefox()
# Go to the Facebook URL
browser.get("http://www.facebook.com")
# Enter the username and Password
uname = browser.find_element_by_id("email")
psword = browser.find_element_by_id("pass")
submit = browser.find_element_by_id("loginbutton")
# Send the details to respective fields
uname.send_keys("hello@gmail.com")
psword.send_keys("thepassword")
# Automate Click Login
submit.click()
Running the above code gives us the following result −
With the correct credentials the facebook login will happen automatically and you can see the logged in page. Selenium’s features enable this functionality.
Finding product of an array using recursion in JavaScript

We are required to write a JavaScript function that takes in an array of Integers. Our function should do the following two things −
Make use of a recursive approach.
Make use of a recursive approach.
Calculate the product of all the elements in the array.
Calculate the product of all the elements in the array.
And finally, it should return the product.
For example −
If the input array is −
const arr = [1, 3, 6, .2, 2, 5];
Then the output should be −
const output = 36;
The code for this will be −
const arr = [1, 3, 6, .2, 2, 5];
const arrayProduct = ([front, ...end]) => {
   if (front === undefined) {
      return 1;
   };
   return front * arrayProduct(end);
};
console.log(arrayProduct(arr));
And the output in the console will be −
36
Get the asymmetric difference of two sets in Java

Use removeAll() method to get the asymmetric difference of two sets.
First set −
HashSet <String> set1 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");
Second set −
HashSet <String> set2 = new HashSet <String>();
set2.add("Mat");
To get the asymmetric difference −
set1.removeAll(set2);
The following is an example that displays how to get the asymmetric difference between two sets −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> set1 = new HashSet <String>();
      HashSet <String> set2 = new HashSet <String>();
      set1.add("Mat");
      set1.add("Sat");
      set1.add("Cat");
      System.out.println("Set1 = "+ set1);
      set2.add("Mat");
      System.out.println("Set2 = "+ set2);
      set1.removeAll(set2);
      System.out.println("Asymmetric difference = "+ set1);
   }
}
Set1 = [Mat, Sat, Cat]
Set2 = [Mat]
Asymmetric difference = [Sat, Cat]
How to append a vector in a vector in C++?

To append a vector in a vector can simply be done by vector insert() method.
Begin
   Declare a function show().
      Pass a constructor of a vector as a parameter within show()
      function.
      for (auto const& i: input)
         Print the value of variable i.
   Declare vect1 of vector type.
      Initialize values in the vect1.
   Declare vect2 of vector type.
      Initialize values in the vect2.
   Call vect2.insert(vect2.begin(), vect1.begin(), vect1.end()) to
   append the vect1 into vect2.
   Print “Resultant vector is:”
   Call show() function to display the value of vect2.
End.
 Live Demo
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void show(vector<int> const &input) {
   for (auto const& i: input) {
      std::cout << i << " ";
   }
}
int main() {
   vector<int> v1 = { 1, 2, 3 };
   vector<int> v2 = { 4, 5 };
   v2.insert(v2.begin(), v1.begin(), v1.end());
   cout<<"Resultant vector is:"<<endl;
   show(v2);
   return 0;
}
Resultant vector is:
1 2 3 4 5
How to create a bar plot with ggplot2 using stat_summary in R?

There are multiple ways to create a bar plot in R and one such way is using stat_summary of ggplot2 package. In this function, we need to supply a function for the y-axis and to create the bars we must use geom="bar". The main thing is to decide which function should be used for y-axis values.
Consider the below data frame:
Live Demo
> x<-sample(c("Male","Female"),20,replace=TRUE)
> y<-rpois(20,5)
> df<-data.frame(x,y)
> df
    x    y
1 Female 3
2 Male 3
3 Female 7
4 Male 3
5 Female 8
6 Female 5
7 Male 11
8 Male 6
9 Male 5
10 Female 3
11 Female 2
12 Female 7
13 Male 6
14 Female 5
15 Male 3
16 Male 6
17 Female 9
18 Female 6
19 Female 8
20 Female 3
Loading ggplot2 package and creating bar plot using stat_summary:
> library(ggplot2)
> ggplot(df,aes(x,y))+stat_summary(fun="mean",geom="bar")
Nested Routing in React.js

import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom';
import Category from './Category';
class App extends Component {
   render() {
      return (
         <div>
            <nav className="navbar navbar-light">
               <ul className="nav navbar-nav">
                  <li><Link to="/">Main Page</Link></li>
                  <li><Link to="/users">Users</Link></li>
               </ul>
            </nav>
            <Switch>
               <Route exact path="/" component={MainPage}/>
               <Route path="/users" component={Users}/>
            </Switch>
         </div>
      );
   }
}
export default App;
We have two components here MainPage and Users. MainPage is our main component which is mapped using exact keyword and path as ‘/’
The User component is where we will have the nested routing. The actual nesting will be implemented inside the Users component. Here in app.jsx file we will have only the parent link to the Users component.
import React from 'react';
import { Link, Route } from 'react-router-dom';
const Users = ({ match }) => {
   return(
      <div>
         <ul>
            <li><Link to={`${match.url}/David`}>David</Link></li>
            <li><Link to={`${match.url}/Steve`}>Steve</Link></li>
            <li><Link to={`${match.url}/John`}>John</Link></li>
         </ul>
         <Route path={`${match.path}/:name`} render= {({match}) =>( <div><h3> {match.params.name} </h3></div>)}/>
      </div>
   )
}
export default Users;
The match object contains the path /users and :name attribute contains the nesting for particular user. We have also created the Link components in Users for navigating to specific users.
Note the use of render attribute on Route path in Users component. Render is executing the function to display user.
Reverse Only Letters in Python

Suppose we have a string S, we have to find the reversed string where all characters that are not a letter will not change their positions and all letters reverse their positions. So if the given string is "a-bC-dEf-ghIj", then output will be "j-Ih-gfE-dCba"
To solve this, we will follow these steps −
We will use the regular expression library to solve this
if S is empty, then return S
str := an empty string, index1 := 0 and index2 := length of S – 1
while index1 < length of Sif index2 >= 0 and S[index1] is alphabet and S[index2] is alphabetstr := str + S[index2]decrease index2 by 1, and increase index1 by 1else if S[index1] is alphabet then decrease index2 by 1else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1else decrease index2 by 1, and increase index1 by 1
if index2 >= 0 and S[index1] is alphabet and S[index2] is alphabetstr := str + S[index2]decrease index2 by 1, and increase index1 by 1
str := str + S[index2]
decrease index2 by 1, and increase index1 by 1
else if S[index1] is alphabet then decrease index2 by 1
else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1
else decrease index2 by 1, and increase index1 by 1
return str
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def reverseOnlyLetters(self, S):
      if not S:
         return S
      str_= ""
      index1 = 0
      index2 = len(S)-1
      while index1<len(S):
         #print(index1,index2)
         if index2>=0 and S[index1].isalpha() and S[index2].isalpha():
            str_+=S[index2]
            index2 -= 1
            index1 += 1
         elif S[index1].isalpha():
            index2-=1
         elif not S[index1].isalpha():
            str_+=S[index1]
            index1+=1
         else:
            index2 -= 1
            index1 += 1
      return str_
ob1 = Solution()
print(ob1.reverseOnlyLetters("a-bC-dEf-ghIj"))
"a-bC-dEf-ghIj"
"j-Ih-gfE-dCba"
Performing inverse binary thresholding on an image using OpenCV

In this program, we will perform inverse binary thresholding on an image using openCV. Thresholding is a process in which the value of each pixel is changed in relation to a threshold value.
The pixel is given a certain value if it is less than the threshold and some other value if it is greater than the threshold. In inverse binary thresholding, if the value of the pixel is less than the threshold, it will be given a maximum value i.e. white. If it is greater than the threshold, it will be assigned 0, i.e., black.
Step 1: Import cv2.
Step 2: Define threshold and max_val.
Step 3: Pass these parameters in the cv2.threshold value and specify the type of thresholding you want to do.
Step 4: Display the output.
import cv2

image = cv2.imread('testimage.jpg')
threshold_value = 120
max_val = 255

ret, image = cv2.threshold(image, threshold_value, max_val, cv2.THRESH_BINARY_INV)
cv2.imshow('InverseBinaryThresholding', image)
The ret variable in the program simply returns the threshold value. For any pixels having value smaller than the threshold value, they are replaced by max_val, i.e., 255.
C++ Program to Implement Quick Sort with Given Complexity Constraint

Quick sort is based on divide-and-conquer. The average time complexity of this algorithm is O(n*log(n)) but the worst case complexity is O(n^2). To reduce the chances of the worst case here Quicksort is implemented using randomization.
Begin
   pivot = h
   Index = l
   start = l and end = h
   while start < end do
      while a[start] <= pivot AND start < end do
         start = start +1
      done
      while a[end] > pivot do
         end = end – 1
      done
      if start < end then
         swap a[start] with a[end]
      done
      a[low] = a[end]
      a[end] = pivot
   return end
End
Begin
   n = rand()
   pivot = l + n%(h-l+1);
   Swap a[h] with a[pivot]
   return Partition(a, l, h)
End
Begin
   int pindex;
   If (l<h)
      pindex = RandomPivotPartition(a, l, h)
      QuickSort(a, l, pindex-1)
      QuickSort(a, pindex+1, h)
   return 0
End
#include<iostream>
#include<cstdlib>

using namespace std;

void swap(int *a, int *b) {
   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
}

int Partition(int a[], int l, int h) {
   int pivot, index, i;
   index = l;
   pivot = h;
   for(i = l; i < h; i++) {
      if(a[i] < a[pivot]) {
         swap(&a[i], &a[index]);
         index++;
      }
   }
   swap(&a[pivot], &a[index]);
   return index;
}
int RandomPivotPartition(int a[], int l, int h) {
   int pvt, n, temp;
   n = rand();
   pvt = l + n%(h-l+1);
   swap(&a[h], &a[pvt]);
   return Partition(a, l, h);
}
int QuickSort(int a[], int l, int h) {
   int pindex;
   if(l < h) {
      pindex = RandomPivotPartition(a, l, h);
      QuickSort(a, l, pindex-1);
      QuickSort(a, pindex+1, h);
   }
   return 0;
}
int main() {
   int n, i;
   cout<<"\nEnter the number of data element to be sorted: ";
   cin>>n;
   int arr[n];
   for(i = 0; i < n; i++) {
      cout<<"Enter element "<<i+1<<": ";
      cin>>arr[i];
   }
   QuickSort(arr, 0, n-1);
   cout<<"\nSorted Data ";
   for (i = 0; i < n; i++)
      cout<<"->"<<arr[i];
   return 0;
}
Enter the number of data element to be sorted: 4 Enter element 1: 3
Enter element 2: 4
Enter element 3: 7
Enter element 4: 6
Sorted Data ->3->4->6->7
What are finalizers in C#?

Finalizers in C# are used to destruct instances of classes. With that, you can also use it to release resources.
Here are some of the key points about Finalizers −
Only one finalizer is allowed for a class
You cannot inherit or overload Finalizers
A finalizer cannot have parameters
Finalizers invoke automatically
Finalizers in C# are declared like destructors. Let’s say the class name is Demo, therefore, the following would be our finalizer −
~Demo() {
   //
}
The finalizer declaration is prefixed with a tilde before the class name.
Python | Find elements within range in numpy - GeeksforGeeks

12 Mar, 2019
Given numpy array, the task is to find elements within some specific range. Let’s discuss some ways to do the task. Method #1: Using np.where()
# python code to demonstrate# finding elements in range# in numpy arrayimport numpy as np  ini_array = np.array([1, 2, 3, 45, 4, 7, 810, 9, 6])  # printing initial arrayprint("initial_array : ", str(ini_array));  # find elements in range 6 to 10result = np.where(np.logical_and(ini_array>= 6, ini_array<= 10))  # printing resultprint("resultant_array : ", result)
initial_array :  [  1   2   3  45   4   7 810   9   6]
resultant_array :  (array([5, 7, 8]),)

 Method #2: Using numpy.searchsorted()
# Python code to demonstrate# finding elements in range# in numpy array  import numpy as np  ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6])  # printing initial arrayprint("initial_array : ", str(ini_array));    # find elements in range 6 to 10start = np.searchsorted(ini_array, 6, 'left')end = np.searchsorted(ini_array, 10, 'right')result = np.arange(start, end)  # printing resultprint("resultant_array : ", result)
initial_array :  [ 1  2  3 45  4  7  9  6]
resultant_array :  [5 6 7]

 Method #3: Using *
# Python code to demonstrate# finding elements in range# in numpy array  import numpy as np  ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6])  # printing initial arrayprint("initial_array : ", str(ini_array));    # find elements in range 6 to 10result = ini_array[(ini_array>6)*(ini_array<10)]  # printing resultprint("resultant_array : ", result)
initial_array :  [ 1  2  3 45  4  7  9  6]
resultant_array :  [7 9]

Python numpy-program
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 ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Firebase - Event Types

Firebase offers several different event types for reading data. Some of the most commonly used ones are described below.
The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all the data including children.
This event type will be triggered once for every player and every time a new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");

playersRef.on("child_added", function(data, prevChildKey) {
   var newPlayer = data.val();
   console.log("name: " + newPlayer.name);
   console.log("age: " + newPlayer.age);
   console.log("number: " + newPlayer.number);
   console.log("Previous Player: " + prevChildKey);
});
We will get the following result.
If we add a new player named Bob, we will get the updated data.
This event type is triggered when the data has changed.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");

playersRef.on("child_changed", function(data) {
   var player = data.val();
   console.log("The updated player name is " + player.name);
});
We can change Bob to Maria in Firebase to get the update.
If we want to get access of deleted data, we can use child_removed event type.
var playersRef = firebase.database().ref("players/");

playersRef.on("child_removed", function(data) {
   var deletedPlayer = data.val();
   console.log(deletedPlayer.name + " has been deleted");
});
Now, we can delete Maria from Firebase to get notifications.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Difference Between Identifier and Variable

In this post, we will understand the difference between an identifier and a variable.
All of them are not variables.
All of them are not variables.
They are used to name a variable, a function, a class, a structure, a union.
They are used to name a variable, a function, a class, a structure, a union.
It is created to give a unique name to an entity.
It is created to give a unique name to an entity.
They can consist of alphabets, digits, and underscores.
They can consist of alphabets, digits, and underscores.
There is no punctuation or special symbol, except the underscore.
There is no punctuation or special symbol, except the underscore.
It can be upper case or lower case.
It can be upper case or lower case.
It can start with lower case letter, upper case letter or an underscore.
It can start with lower case letter, upper case letter or an underscore.
It helps locate the name of the entity which is defined along with a keyword.
It helps locate the name of the entity which is defined along with a keyword.
enum geeks_artiles_in {Jan=1, Feb, Mar, Apr, May, June, July}
It is used to give a name to a memory location.
It is used to give a name to a memory location.
It holds a value.
It holds a value.
The names of variables are different.
The names of variables are different.
They help allot a unique name to a specific memory location.
They help allot a unique name to a specific memory location.
int a = 6;
JavaScript String - match() Method

This method is used to retrieve the matches when matching a string against a regular expression.
Use the following syntax to use the match() method.
string.match( param )

param − A regular expression object.
If the regular expression does not include the g flag, it returns the same result as regexp.exec(string).
If the regular expression does not include the g flag, it returns the same result as regexp.exec(string).
If the regular expression includes the g flag, the method returns an Array containing all the matches.
If the regular expression includes the g flag, the method returns an Array containing all the matches.
Try the following example.
<html>
   <head>
      <title>JavaScript String match() Method</title>
   </head>
   
   <body> 
      <script type = "text/javascript">
         var str = "For more information, see Chapter 3.4.5.1";
         var re = /(chapter \d+(\.\d)*)/i;
         var found = str.match( re );         
         document.write(found ); 
      </script>      
   </body>
</html>
Chapter 3.4.5.1,Chapter 3.4.5.1,.1


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
What is the difference between Func delegate and Action delegate in C#?

A delegate is a type that represents references to methods with a particular parameter list and return type. When we instantiate a delegate, we can associate its instance with any method with a compatible signature and return type. We can invoke (or call) the method through the delegate instance.
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.
Below is the Func delegate with two input and an output parameter.
Func<string, string, string > Append;
 Live Demo
using System;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         Func<string, string, string> func = Append;
         string fullName = func("Michael", "Jackson");
         Console.WriteLine(fullName);
         Console.ReadLine();
      }
      static string Append(string firstName, string lastName) {
         return firstName + lastName;
      }
   }
}
MichaelJackson
Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
Below is the Func delegate with two input and an output parameter.
Func<string, string,> Print;
using System;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         Action func = AppendPrint;
         func("Michael", "Jackson");
         Console.ReadLine();
      }
      static void AppendPrint(string firstName, string lastName) {
         string fullName = firstName + lastName;
         Console.WriteLine($"{fullName}");
      }
   }
}
The output of the above code is
MichaelJackson
PHP | imagecreatefrombmp() Function - GeeksforGeeks

29 Jan, 2020
The imagecreatefrombmp() function is an inbuilt function in PHP which is used to create a new image from file or URL.
Syntax:
resource imagecreatefrombmp( string $filename )
Parameters: This function accepts a single parameter $filename which holds the name or URL of a file.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
Below given programs illustrate the imagecreatefrombmp() function in PHP:
Program 1: Viewing a bmp file in browser.
<?php  // Load the BMP image$im = imagecreatefrombmp('https://media.geeksforgeeks.org/wp-content/uploads/20200122193540/g4gbmp.bmp');  // Output the image to browserheader('Content-type: image/bmp');  imagebmp($im);imagedestroy($im);?>
Output:
Program 2: This program converting the bitmap into png.
<?php  // Load the BMP image$im = imagecreatefrombmp('https://media.geeksforgeeks.org/wp-content/uploads/20200122193540/g4gbmp.bmp');  // Convert it to a PNG file, press Ctrl + S to save the new png imageheader('Content-type: image/png');  imagepng($im);imagedestroy($im);?>
Output:
Reference: https://www.php.net/manual/en/function.imagecreatefrombmp.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?