code-rag-bench/online-tutorials huggingface dataset:
Poisson Functions in R Programming

05 Oct, 2021
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions can be easily implemented in R language with the help of R’s inbuilt functions.There are four Poisson functions available in R:  
dpois
ppois
qpois
rpois
Consider a Random Variable X with Poisson distribution given as The mean of this distribution is given by The variance of such a distribution is So if there are ‘n’ which happened out of which the only k were successful when the probability of success is very less then the probability of success becomes 
This function is used for illustration of Poisson density in an R plot. The function dpois() calculates the probability of a random variable that is available within a certain range.Syntax: where,  
K: number of successful events happened in an interval mean per interval log: If TRUE then the function returns probability in form of log
Example:  
Python3
dpois(2, 3)dpois(6, 6)
Output:  
[1] 0.2240418

[1] 0.1606231
 
This function is used for the illustration of cumulative probability function in an R plot. The function ppois() calculates the probability of a random variable that will be equal to or less than a number.Syntax: where,  
K: number of successful events happened in an interval mean per interval lower.tail: If TRUE then left tail is considered otherwise if the FALSE right tail is considered log: If TRUE then the function returns probability in form of log
Example:  
Python3
ppois(2, 3) ppois(6, 6)
Output:  
[1] 0.4231901
[1] 0.6063028
 
The function rpois() is used for generating random numbers from a given Poisson’s distribution.Syntax: where,  
q: number of random numbers needed mean per interval
Example:  
Python3
rpois(2, 3)rpois(6, 6)
Output:  
[1] 2 3
[1]  6  7  6 10  9  4
 
The function qpois() is used for generating quantile of a given Poisson’s distribution. In probability, quantiles are marked points that divide the graph of a probability distribution into intervals (continuous ) which have equal probabilities.Syntax: where,  
K: number of successful events happened in an interval mean per interval lower.tail: If TRUE then left tail is considered otherwise if the FALSE right tail is considered log: If TRUE then the function returns probability in form of log
Example:  
Python3
y <- c(.01, .05, .1, .2)qpois(y, 2)qpois(y, 6)
Output:  
[1] 0 0 0 1
[1] 1 2 3 4
 
kashishsoda
R Machine-Learning
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find most used colors in image using Python

16 Oct, 2021
Prerequisite: PIL
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy-to-use library developed by Alex Clark and other contributors. We’ll be working with Pillow.
Let’s understand with step-by-step implementation:
1. Read an image
For reading the image in PIL, we use Image method.
# Read an Image
img = Image.open('File Name')
2. Convert into RGB image
img.convert('RGB')
3. Get Width and Height of Image
width, height = img.size
4. Iterate through all pixels of Image and get R, G, B value from that pixel
for x in range(0, width):
    for y in range(0, height):
        r, g, b = img.getpixel((x,y))
        print(img.getpixel((x,y)))
Output:
(155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151) ...
5. Initialize three variable
r_total = 0
g_total = 0
b_total = 0
Iterate through all pixel and add each color to different Initialized variable.
r_total = 0
g_total = 0
b_total = 0

for x in range(0, width):
    for y in range(0, height):
        r, g, b = img.getpixel((x,y))
        r_total += r
        g_total += g
        b_total += b
print(r_total, g_total, b_total)
Output:
(29821623, 32659007, 33290689)
As we can R, G & B value is very large, here we will use count variable
Initialize One More variable
count = 0
Divide total color value by count
Below is the Implementation:
Image Used – 
Python3
# Import Modulefrom PIL import Image def most_common_used_color(img):    # Get width and height of Image    width, height = img.size     # Initialize Variable    r_total = 0    g_total = 0    b_total = 0     count = 0     # Iterate through each pixel    for x in range(0, width):        for y in range(0, height):            # r,g,b value of pixel            r, g, b = img.getpixel((x, y))             r_total += r            g_total += g            b_total += b            count += 1     return (r_total/count, g_total/count, b_total/count) # Read Imageimg = Image.open(r'C:\Users\HP\Desktop\New folder\mix_color.png') # Convert Image into RGBimg = img.convert('RGB') # call functioncommon_color = most_common_used_color(img) print(common_color)# Output is (R, G, B)
Output:
# Most Used color is Blue
(179.6483313253012, 196.74100602409638, 200.54631927710844)
ruhelaa48
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Cross-Site Request Forgery(CSRF)

A CSRF attack forces an authenticated user (victim) to send a forged HTTP request, including the victim's session cookie to a vulnerable web application, which allows the attacker to force the victim's browser to generate request such that the vulnerable app perceives as legitimate requests from the victim.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
Here is a classic example of CSRF −
Step 1 − Let us say, the vulnerable application sends a state changing request as a plain text without any encryption.
http://bankx.com/app?action=transferFund&amount=3500&destinationAccount=4673243243

Step 2 − Now the hacker constructs a request that transfers money from the victim's account to the attacker's account by embedding the request in an image that is stored on various sites under the attacker's control −
<img src = "http://bankx.com/app?action=transferFunds&amount=14000&destinationAccount=attackersAcct#" 
   width = "0" height = "0" />
Step 1 − Let us perform a CSRF forgery by embedding a Java script into an image. The snapshot of the problem is listed below.
Step 2 − Now we need to mock up the transfer into a 1x1 image and make the victim to click on the same.
Step 3 − Upon submitting the message, the message is displayed as highlighted below.
Step 4 − Now if the victim clicks the following URL, the transfer is executed, which can be found intercepting the user action using burp suite. We are able to see the transfer by spotting it in Get message as shown below −
Step 5 − Now upon clicking refresh, the lesson completion mark is shown.
CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure.
CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure.
Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA.
Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA.
random.setstate() in Python

17 May, 2020
Random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
The setstate() method of the random module is used in conjugation with the getstate() method. After using the getstate() method to capture the state of the random number generator, the setstate() method is used to restore the state of the random number generator back to the specified state.
The setstate() method requires a state object as a parameter which can be obtained by invoking the getstate() method.
Example 1:
# import the random moduleimport random  # capture the current state# using the getstate() methodstate = random.getstate()  # print a random number of the# captured statenum = random.random()print("A random number of the captured state: "+ str(num))  # print another random numbernum = random.random()print("Another random number: "+ str(num))  # restore the captured state# using the setstate() method# pass the captured state as the parameterrandom.setstate(state)  # now printing the same random number# as in the captured statenum = random.random()print("The random number of the previously captured state: "+ str(num))
Output:
A random number of the captured state: 0.8059083574308233Another random number: 0.46568313950438245The random number of the previously captured state: 0.8059083574308233
Example 2:
# import the random moduleimport random    list1 = [1, 2, 3, 4, 5]    # capture the current state# using the getstate() methodstate = random.getstate()  # Prints list of random items of given length print(random.sample(list1, 3))   # restore the captured state# using the setstate() method# pass the captured state as the parameterrandom.setstate(state)  # now printing the same list of random# itemsprint(random.sample(list1, 3)) 
Output:
[5, 2, 4]
[5, 2, 4]
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Quickly merging two sorted arrays using std::merge() in C++ STL

13 Jun, 2022
C++ program to merge two sorted arrays of length ‘n’ and ‘m’ respectively in sorted order.
Examples:
Input: A[] = {3, 6, 9}
       B[] = {2, 7, 11}
Output: C[] = {2, 3, 6, 7, 9, 11}

Input: A[] = {1, 1, 3, 6, 9}
       B[] = {1, 2, 7, 11, 11}
Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11}

We have discussed other approaches in below postsMerge two sorted arrays with O(1) extra spaceMerge two sorted arrays
We can quickly merge two sorted arrays using std::merge present algorithm header file.
Below is the implementation using std :: merge
// C++ program to merge two sorted arrays// std::merge()#include <iostream>#include <algorithm>using namespace std;  // Driver codeint main(){    int A[] = {1, 1, 9};    int n = sizeof(A)/sizeof(A[0]);      int B[] = {2, 7, 11, 11};    int m  = sizeof(B)/sizeof(B[0]);      // Merging in sorted order    int C[m + n];    merge(A, (A + n), B, (B + m), C);      // Print the merged array.    for (int i = 0; i < (m + n); i++)        cout << C[i] << " ";      return 0;}
Output:
1 1 2 7 9 11 11 

In general, syntax of merge() is
// Merges elements from aFirst to aLast and bFirst
// to bLast into a result and returns iterator pointing
// to first element of result
OutputItr merge(InputItr1 aFirst, InputItr1 aLast,
                InputItr2 bFirst, InputItr2 bLast,
                OutputItr result);

We can use it for array of user defined objects
also by overloading < operator.

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
How to create a transparent iframe ?

14 Jul, 2020
The <iframe> tag is an inline frame. It is used to embed another HTML page within the current HTML page.
Syntax:
<iframe src = "URL"></iframe>
A transparent iframe can be made by setting its background to transparent.
body {
    background-color : transparent;
}

And, the allowtransparency attribute of “iframe” is to be set as “true”.
<iframe src = "URL" allowtransparency = "true"></iframe>
Example:
HTML code:<!DOCTYPE html><html>  <body>    <div style="background: green;             padding: 30px;">                      <iframe src="iframe.html"             allowtransparency="true">            Alternate content        </iframe>    </div></body>  </html>
<!DOCTYPE html><html>  <body>    <div style="background: green;             padding: 30px;">                      <iframe src="iframe.html"             allowtransparency="true">            Alternate content        </iframe>    </div></body>  </html>
iframe.html<!DOCTYPE html><html>  <body style=    "background-color: transparent;     text-align: center;     color: #ffffff;">          <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p></body>  </html>
<!DOCTYPE html><html>  <body style=    "background-color: transparent;     text-align: center;     color: #ffffff;">          <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p>    <p>geeksforgeeks</p></body>  </html>
Output:
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Python PIL | logical_xor() and invert() method - GeeksforGeeks

06 Nov, 2019
PIL.ImageChops.logical_xor() method applies Logical XOR between two images. At least one of the images must have mode “1”.
Image 1:Image2:
Syntax: PIL.ImageChops.logical_xor(image1, image2)
Parameters:image1: first imageimage2: second image
Return Type: Image
# Importing Image and ImageChops module from PIL package  from PIL import Image, ImageChops      # creating a image1 object im1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG") .convert("1")     # creating a image2 object im2 = Image.open(r"C:\Users\sadow984\Desktop\x5.PNG") .convert("1")     # applying logical_xor method im3 = ImageChops.logical_xor(im1, im2)      im3.show() 
Output:
PIL.ImageChops.invert() method invert an image (channel).
Syntax: PIL.ImageChops.invert(image)
Parameters:image1: image
Return Type: Image
# Importing Image and ImageChops module from PIL package  from PIL import Image, ImageChops      # creating a image1 object im1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG")     # applying invert method im3 = ImageChops.invert(im1)      im3.show() 
Output:
nidhi_biet
Image-Processing
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to create headings in HTML page?

HTML provides 6 tags to create headings i.e. h1, h2, h3, h4, h5 and h6. Use any of the heading tags <h1> to <h6> and every tag will give you the different size of the heading. The <h1>tag defines the most important heading and <h6> defines the least important heading.
Just keep in mind that you should use these tags inside <body>...</body> tags.
You can try to run the following code to create different headings in an HTML page
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Headings</title>
   </head>

   <body>
      <h1>This is heading 1</h1>
      <h2>This is heading 2</h2>
      <h3>This is heading 3</h3>
      <h4>This is heading 4</h4>
      <h5>This is heading 5</h5>
      <h6>This is heading 6</h6>
   </body>
</html>
How to compare two dates with JavaScript?

To compare two dates with JavaScript, create two dates object and get the recent date. You can try to run the following code to compare two dates.
 Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         var date1, date2;
         date1 = new Date();
         document.write(date1);
         date2 = new Date( "Dec 15, 2014 21:20:15" );
         document.write("<br>"+date2);
         if (date1 > date2) {
            document.write("<br>Date1 is the recent date.");
         } else {
            document.write("<br>Date 2 is the recent date.");
         }
      </script>
   </body>
</html>
Sat Dec 15 2018 11:08:06 GMT+0530 (India Standard Time)
Mon Dec 15 2014 21:20:15 GMT+0530 (India Standard Time)
Date1 is the recent date.
Difference between Private and Public IP addresses

Private IP Address and Public IP Address are used to uniquely identify a machine on the internet. Private IP address is used with a local network and public IP address is used outside the network. Public IP address is provided by ISP, Internet Service Provider.
Following are the important differences between Private IP Address and Public IP Address.
10.0.0.0 – 10.255.255.255,
172.16.0.0 – 172.31.255.255,
192.168.0.0 – 192.168.255.255
CICS - DELETE

DELETE command is used to delete a record that is present in a file. Prior to this command, the record must be read with a READ UPDATE command. The parameters are same as described before. The syntax of Delete command is as follows −
EXEC CICS DELETE
   FILE('name')
END-EXEC.

Following is the syntax to delete a record directly without reading it with Update option −
EXEC CICS DELETE
   FILE('name')
   RIDFLD(data-value)
END-EXEC.
Following is the example for Group Delete. This can be done using Generic option, where all the records that satisfy the generic criteria will be deleted. NUMREC will hold the number of records deleted. The field mentioned here should be a S9(4) comp.
IDENTIFICATION DIVISION.                                         
PROGRAM-ID. HELLO.                                               
DATA DIVISION. 
WORKING-STORAGE SECTION.
01 WS-STD-REC-LEN    PIC S9(4) COMP.
01 WS-STD-KEY-LEN    PIC S9(4) COMP.
01 WS-STD-REC-KEY    PIC 9(3).
01 WS-STD-REC        PIC X(70).
01 WS-NUM-REC-DEL    PIC S9(4).
PROCEDURE DIVISION.
MOVE '11'       TO WS-STD-REC-KEY.
MOVE 2          TO WS-STD-KEY-LEN.
EXEC CICS READ
   FILE ('FL001')
   RIDFLD (WS-STD-REC-KEY)
   KEYLENGTH (WS-STD-KEY-LEN)
   GENERIC
   NUMREC (WS-NUM-REC-DEL)
END-EXEC.
The following table shows the list of exceptions that arise during a DELETE statement −
NOTOPEN
File is not open.
NOTFND
Record that is being searched doesn't exist in the dataset (DELETE with RIDFLD).
NOTAUTH
If the user does not have enough permissions to use the file.
INVREQ
Rewrite without prior READ with UPDATE.
FILENOTFOUND
File entry is not made in FCT.
 Print
 Add Notes
 Bookmark this page
VBScript Do..While statement

A Do..While loop is used when we want to repeat a set of statements as long as the condition is true. The Condition may be checked at the beginning of the loop or at the end of the loop.
The syntax of a Do..While loop in VBScript is −
Do While condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop           

The below example uses Do..while loop to check the condition at the beginning of the loop. The statements inside the loop are executed only if the condition becomes True.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">        
         Do While i < 5
            i = i + 1
            Document.write("The value of i is : " & i)
            Document.write("<br></br>")
         Loop         
      </script>
   </body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 1

The value of i is : 2

The value of i is : 3

The value of i is : 4

The value of i is : 5

There is also an alternate Syntax for Do..while loop which checks the condition at the end of the loop. The Major difference between these two syntax is explained below with an example.
Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop While condition

The below example uses Do..while loop to check the condition at the end of the loop. The Statements inside the loop are executed atleast once even if the condition is False.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">        
         i = 10  
         Do      
            i = i + 1
            Document.write("The value of i is : " & i)
            Document.write("<br></br>")
         Loop While i<3 'Condition is false.Hence loop is executed once.
         
      </script>
   </body>
</html>
When the above code is executed, it prints the following output in the console.
The value of i is : 11


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
K-th Smallest Prime Fraction in C++

Suppose we have one sorted list, there is 1 and some prime numbers, now for every p < q in the list, we will consider fraction p/q, then we have to find which is the kth smallest fraction. We have to return an array as answer, so ans[0] will be p and ans[1] will be q.
So if the input is like [1,3,5,7], and k = 2, then the answer will be 1/5, as the fractions are 1/3, 1/5, 1/7, 3/5, 3/7, 5/7, the second smallest is 1/5.
To solve this, we will follow these steps −
Define Data, this will take a, b and a/b
Define an array ret of size 2
n := size of A
define one priority queue pq
for initialize i := 0, when i < n, update (increase i by 1), do −insert Data(A[0], A[i], 0) into pq
insert Data(A[0], A[i], 0) into pq
while K is non-zero, do −temp = top element of pqdelete element from pqif K is same as 0, then −ret[0] := a of tempret[1] := b of tempreturn retif temp.idx + 1 < n, then −idx := idx of temp + 1insert Data(A[idx], temp.b, idx) into pqdecrease K by 1
temp = top element of pq
delete element from pq
if K is same as 0, then −ret[0] := a of tempret[1] := b of tempreturn ret
ret[0] := a of temp
ret[1] := b of temp
return ret
if temp.idx + 1 < n, then −idx := idx of temp + 1insert Data(A[idx], temp.b, idx) into pq
idx := idx of temp + 1
insert Data(A[idx], temp.b, idx) into pq
decrease K by 1
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
struct Data{
   double val, a, b;
   int idx;
   Data(double a, double b, int c){
      val = a / b;
      this->a = a;
      this->b = b;
      idx = c;
   }
};
struct Comparator{
   bool operator()(Data a, Data b){
      return !(a.val < b.val);
   }
};
class Solution {
public:
   vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
      vector <int> ret(2);
      int n = A.size();
      priority_queue <Data, vector <Data>, Comparator> pq;
      for(int i = 0; i < n; i++){
         pq.push(Data(double(A[0]), double(A[i]), 0));
      }
      while(K--){
         Data temp = pq.top();
         pq.pop();
         if(K == 0){
            ret[0] = temp.a;
            ret[1] = temp.b;
            return ret;
         }
         if(temp.idx + 1 < n){
            int idx = temp.idx + 1;
            pq.push(Data(double(A[idx]), double(temp.b), idx));
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,3,5,7};
   print_vector(ob.kthSmallestPrimeFraction(v, 2));
}
{1,3,5,7}
2
[1, 5, ]
How to convert a Drawable to a Bitmap in Android using Kotlin?

This example demonstrates how to convert a Drawable to a Bitmap in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   android:padding="4dp"
   tools:context=".MainActivity">
<ImageView
   android:id="@+id/imageView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" />
<Button
   android:id="@+id/btnConvert"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="Convert Drawable to Bitmap" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val imageView: ImageView = findViewById(R.id.imageView)
      val btnConvert: Button = findViewById(R.id.btnConvert)
      btnConvert.setOnClickListener {
         val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
         imageView.setImageBitmap(bitmap)
         Toast.makeText(applicationContext, "Image converted to Bitmap",
         Toast.LENGTH_SHORT).show()
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
\overline - Tex Command

\overline - Used to create overline symbol over the argument.
{ \overline #1}
\overline command draws overline symbol over the argument.

\overline{AB}

AB ̄


\overline a

a ̄


\overline{\text{a long argument}}

a long argument ̄



\overline{AB}

AB ̄


\overline{AB}
\overline a

a ̄


\overline a
\overline{\text{a long argument}}

a long argument ̄


\overline{\text{a long argument}}

    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
Lodash | _.sampleSize() Method - GeeksforGeeks

08 May, 2020
The _.sampleSize() method is used to give an array of n random elements from the given array.
Syntax:
_.sampleSize(array, n)
Parameters: This method accept two parameters as mentioned above and described below:
array: This parameter holds the sample collection.
n: This parameter holds the number of elements to sample.
Return Value: This method returns an array of n random elements.
Example 1:
const _ = require('lodash');  let x = [1, 2, 7, 10, 13, 15];  let result = _.sampleSize(x, 2);  console.log(result);
Here, const _ = require('lodash') is used to import the lodash library into the file.
Output:
[10, 13]
Example 2:
const _ = require('lodash');  let x = ['mango', 'apple', 'banana', 'orange', 'grapes'];  let result = _.sampleSize(x, 3);  console.log(result);
Output:
[ 'grapes', 'orange', 'banana' ]

Example 2:
const _ = require('lodash');  let x = [1, 'a', {'name': 'sampleSize'}, [1, 2, 3]];  let result = _.sampleSize(x, 3);  console.log(result);
Output:
[ { name: 'sampleSize' }, 'a', 1 ]

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#sampleSize
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer 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?
delete() and free() in C++

The delete operator is used to deallocate the memory. User has privilege to deallocate the created pointer variable by this delete operator.
Here is the syntax of delete operator in C++ language,
delete pointer_variable;
Here is the syntax to delete the block of allocated memory,
delete[ ] pointer_variable;
Here is an example of delete operator in C++ language,
 Live Demo
#include <iostream>
using namespace std;
int main () {
   int *ptr1 = NULL;
   ptr1 = new int;
   float *ptr2 = new float(299.121);
   int *ptr3 = new int[28];
   *ptr1 = 28;
   cout << "Value of pointer variable 1 : " << *ptr1 << endl;
   cout << "Value of pointer variable 2 : " << *ptr2 << endl;
   if (!ptr3)
   cout << "Allocation of memory failed\n";
   else {
      for (int i = 10; i < 15; i++)
      ptr3[i] = i+1;
      cout << "Value of store in block of memory: ";
      for (int i = 10; i < 15; i++)
      cout << ptr3[i] << " ";
   }
   delete ptr1;
   delete ptr2;
   delete[] ptr3;
   return 0;
}
Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of store in block of memory: 11 12 13 14 15
In the above program, three pointer variables are declared as ptr1, ptr2 and ptr3. The pointer variables ptr1 and ptr2 are initialized with the value using new() and ptr3 is storing the allocated block of memory by new() function.
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
Elements of array are printed by user and sum of elements is printed. To delete the allocated memory; delete ptr1, delete pt2 and delete[] ptr3 are used.
delete ptr1;
delete ptr2;
delete[] ptr3;
The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of pointer which means it still points the same memory location.
Here is the syntax of free() in C language,
void free(void *pointer_name);
Here,
pointer_name − Any name given to the pointer.
Here is an example of free() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   free(p);
   return 0;
}
Enter elements of array : 32 23 21 28
Sum : 104
In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated.
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
The elements of array are given by the user and sum of their values are printed. The code to free the pointer is as follows −
free(p);
Python - Column deletion from list of lists

In a list of lists an element at the same index of each of the sublist represents a column like structure. In this article we will see how we can delete a column from a list of lists. Which means we have to delete the element at the same index position from each of the sublist.
We use the pop method which removes the element at a particular position. A for loop is designed to iterate through elements at specific index and removes them using pop.
 Live Demo
# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]

# printing original list
print("Given list \n",listA)

# Apply pop
[i.pop(2) for i in listA]

# Result
print("List after deleting the column :\n ",listA)
Running the above code gives us the following result −
Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]
In this approach we use the del function which is similar to above approach. We mention the index at which the column has to be deleted.
 Live Demo
# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]

# printing original list
print("Given list \n",listA)

# Apply del
for i in listA:
del i[2]

# Result
print("List after deleting the column :\n ",listA)
Running the above code gives us the following result −
Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]
Count values from comma-separated field in MySQL?

You can count values from comma-separated field using CHAR_LENGTH() method from MySQL. The syntax is as follows −
SELECT *, (CHAR_LENGTH(yourColumnName) - CHAR_LENGTH(REPLACE(yourColumnName, ',','')) + 1) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table CountValuesCommaSeparated
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> CommaSeparatedValue text,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.76 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('101,104,1900,46675,7895');
Query OK, 1 row affected (0.16 sec)

mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('1010,18949,37465');
Query OK, 1 row affected (0.21 sec)

mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('2010,1201,2743874,7485');
Query OK, 1 row affected (0.42 sec)

mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('4757,457587,48586,378575,3874765,487565');
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from CountValuesCommaSeparated;
The following is the output −
+----+-----------------------------------------+
| Id | CommaSeparatedValue                     |
+----+-----------------------------------------+
| 1  | 101,104,1900,46675,7895                 |
| 2  | 1010,18949,37465                        |
| 3  | 2010,1201,2743874,7485                  |
| 4  | 4757,457587,48586,378575,3874765,487565 |
+----+-----------------------------------------+
4 rows in set (0.00 sec)
Here is the query to count values from comma separated fields:
mysql> select *,
   -> (CHAR_LENGTH(CommaSeparatedValue) -
CHAR_LENGTH(REPLACE(CommaSeparatedValue, ',', '')) + 1) as TotalValue
   -> from CountValuesCommaSeparated;
The following is the output −
+----+-----------------------------------------+------------+
| Id | CommaSeparatedValue                     | TotalValue |
+----+-----------------------------------------+------------+
|  1 | 101,104,1900,46675,7895                 |          5 |
|  2 | 1010,18949,37465                        |          3 |
|  3 | 2010,1201,2743874,7485                  |          4 |
|  4 | 4757,457587,48586,378575,3874765,487565 |          6 |
+----+-----------------------------------------+------------+
4 rows in set (0.00 sec)
Convert Sorted Array to Binary Search Tree in Python

Suppose we have one sorted array A. We have to generate one height-balanced binary search. In this problem, a height-balanced binary tree is actually a binary tree in which the depth of the two subtrees of every node never differs by more than 1. Suppose the array is like [-10, -3, 0, 5, 9]. So one possible output will be like: [0, -3, 9, -10, null, 5]
To solve this, we will follow these steps.
If A is empty, then return Null
find the mid element, and make it root
Divide the array into two sub-arrays, left part of the mid element, and right part of the mid element
recursively perform the same task for the left subarray and right subarray.
Let us see the following implementation to get a better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
         else:
            temp.left = TreeNode(0)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         if data is not None:
            temp.right = TreeNode(data)
      else:
         temp.right = TreeNode(0)
      break
   else:
      que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
def height(root):
   if root is None:
      return 0
   else :
      # Compute the height of left and right subtree
      l_height = height(root.left)
      r_height = height(root.right)
      #Find the greater one, and return it
      if l_height > r_height :
         return l_height+1
      else:
         return r_height+1
def print_given_level(root, level):
   if root is None:
      return
   if level == 1:
      print(root.data,end = ',')
   elif level > 1 :
      print_given_level(root.left , level-1)
      print_given_level(root.right , level-1)
def level_order(root):
   print('[', end = '')
   h = height(root)
   for i in range(1, h+1):
      print_given_level(root, i)
   print(']')
class Solution(object):
   def sortedArrayToBST(self, nums):
      """
      :type nums: List[int]
      :rtype: TreeNode
      """
      if not nums:
         return None
      mid = nums[len(nums)//2]
      root = TreeNode(mid)
      root.left = self.sortedArrayToBST(nums[:len(nums)//2])
      root.right = self.sortedArrayToBST(nums[len(nums)//2 +1 :])
      return root
nums = [-10,-3,0,5,9]
ob1 = Solution()
bst = ob1.sortedArrayToBST(nums)
level_order(bst)
nums = [-10,-3,0,5,9]
[0,-3,9,-10,5,]
Groovy - findAll()

It finds all values in the receiving object matching the closure condition.
List findAll(Closure closure)

The condition to be met by the collection element is specified in the closure that must be some Boolean expression.
The find method returns a list of all values found as per the expression.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      def lst = [1,2,3,4];
      def value;
		
      value = lst.findAll{element -> element > 2}
      value.each {println it}
   } 
}
When we run the above program, we will get the following result −
3 
4 


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
C++ Functional Library - modulus

It is a modulus function object class and binary function object class whose call returns the result of the modulus operation between its two arguments (as returned by operator %).
Following is the declaration for std::modulus.
template <class T> struct modulus;
template <class T> struct modulus;
T − It is a type of the arguments and return type of the functional call.
none
noexcep − It doesn't throw any exceptions.
In below example explains about std::modulus.
#include <iostream>
#include <functional>
#include <algorithm>

int main () {
   int numbers[]={1,20,1003,42,56};
   int remainders[5];
   std::transform (numbers, numbers+5, remainders, std::bind2nd(std::modulus<int>(),2));
   for (int i=0; i<5; i++)
      std::cout << numbers[i] << " is " << (remainders[i]==0?"even":"odd") << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
1 is odd
20 is even
1003 is odd
42 is even
56 is even

 Print
 Add Notes
 Bookmark this page
Can we create an object for an interface in java?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.
Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.
In the following example we an interface with name MyInterface and a class with name InterfaceExample.
In the interface we have an integer filed (public, static and, final) num and abstract method demo().
From the class we are trying to − create an object of the interface and print the num value.
 Live Demo
interface MyInterface{
   public static final int num = 30;
   public abstract void demo();
}
public class InterfaceExample implements MyInterface {
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      MyInterface interfaceObject = new MyInterface();
      System.out.println(interfaceObject.num);
   }
}
On compiling, the above program generates the following error
InterfaceExample.java:13: error: MyInterface is abstract; cannot be instantiated
   MyInterface interfaceObject = new MyInterface();
^
1 error
To access the members of an interface you need to implements it and provide implementation to all the abstract methods of it.
 Live Demo
interface MyInterface{
   public int num = 30;
   public void demo();
}
public class InterfaceExample implements MyInterface {
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.demo();
      System.out.println(MyInterface.num);
   }
}
This is the implementation of the demo method
30
How to detect orientation change in layout in android?

This example demonstrates how do I detect orientation change in layout in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Hello World!"
   android:textSize="24sp"
   android:textStyle="bold"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   @Override
   public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
         Toast.makeText(MainActivity.this, "Landscape Mode", Toast.LENGTH_SHORT).show();
      } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
         Toast.makeText(MainActivity.this, "Portrait Mode", Toast.LENGTH_SHORT).show();
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity" android:configChanges="orientation|screenSize">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Tryit Editor v3.7

Tryit: HTML elements
How to check if all the values in a numpy array are non-zero?

In this program, we have to check whether all the values in a numpy array are zero or not. If all the elements are non-zero, the output is 'True'. Otherwise, the output is 'False'.
The most important Step before implementing the algorithm for this program is to install numpy. Following is the command for installing numpy from command prompt:
pip install numpy
Input:
[1,2,3,4]
Output:
True
Input:
[0,1,2,3]
Output:
False
We shall use the numpy built-in function called 'all(input_array)'. This function checks every number in the array. If the number is non-zero, the function returns 'True'. All non-zero elements are evaluated as 'True', while 0's are evaluated as 'False'.
Step 1: Import numpy.Step 2: Define a numpy array using np.array()Step 3: Pass this array as a parameter to np.all()Step 4: Stop.
Step 1: Import numpy.
Step 2: Define a numpy array using np.array()
Step 3: Pass this array as a parameter to np.all()
import numpy as np

array1 = np.array([1,2,3,4])
array2 = np.array([0,1,2,3])

print("Array 1: ", array1)
print("Array2: ", array2)
print("\nArray 1 is non-zero: ", np.all(array1))
print("Array 2 is non-zero: ", np.all(array2))
Array 1: [1 2 3 4]