code-rag-bench/online-tutorials huggingface dataset:
How to create a sparse matrix in R?

A sparse matrix is a type of matrix that has most of the elements equal to zero but there is no restriction for the number of zero elements. As a general criterion the number of non−zero elements are expected to be equal to the number of rows or number of columns. To create a sparse matrix in R, we can use sparseMatrix function of Matrix package.
 Live Demo
Loading Matrix package and creating a sparse matrix −
library(Matrix)
i<−c(1,5,2,4,2,2,8);j<−c(2,5,3,2,4,2,4);x<−rpois(7,2)
M1<−sparseMatrix(i,j,x=x)
M1
8 x 5 sparse Matrix of class "dgCMatrix"
[1,] . 3 . . .
[2,] . 1 3 2 .
[3,] . . . . .
[4,] . 2 . . .
[5,] . . . . 5
[6,] . . . . .
[7,] . . . . .
[8,] . . . 0 .
 Live Demo
i<−c(1,3,8,4,2,7,6,9,1,4,10);j<−c(2,5,3,2,4,2,4,5,2,7,3);x<−rpois(11,2)
M2<−sparseMatrix(i,j,x=x)
M2
10 x 7 sparse Matrix of class "dgCMatrix"
[1,] . 5 . . . . .
[2,] . . . 3 . . .
[3,] . . . . 0 . .
[4,] . 3 . . . . 3
[5,] . . . . . . .
[6,] . . . 1 . . .
[7,] . 2 . . . . .
[8,] . . 3 . . . .
[9,] . . . . 2 . .
[10,] . . 1 . . . .
 Live Demo
i<−c(1,3,8,4,2,7,6,9,1,4,10);j<−c(2,5,3,2,4,2,4,5,2,7,3);x<−rpois(11,5)
M3<−sparseMatrix(i,j,x=x)
M3
10 x 7 sparse Matrix of class "dgCMatrix"
[1,] . 7 . . . . .
[2,] . . . 8 . . .
[3,] . . . . 7 . .
[4,] . 4 . . . . 4
[5,] . . . . . . .
[6,] . . . 6 . . .
[7,] . 4 . . . . .
[8,] . . 6 . . . .
[9,] . . . . 7 . .
[10,] . . 4 . . . .
 Live Demo
i<−c(1,3,8,4,2,7,6,9,1,4,10,5,11,2,12);j<−c(2,5,3,8,6,2,4,2,4,5,2,7,3,2,1);x<−rpois(15,5)
M4<−sparseMatrix(i,j,x=x)
M4
12 x 8 sparse Matrix of class "dgCMatrix"
[1,] . 4 . 1 . . . .
[2,] . 4 . . . 5 . .
[3,] . . . . 6 . . .
[4,] . . . . 4 . . 1
[5,] . . . . . . 5 .
[6,] . . . 5 . . . .
[7,] . 2 . . . . . .
[8,] . . 9 . . . . .
[9,] . 1 . . . . . .
[10,] . 3 . . . . . .
[11,] . . 0 . . . . .
[12,] 5 . . . . . . .
 Live Demo
i<−c(1,3,8,4,2,7,6,9,1,4,10,5,11,2,12);j<−c(2,5,3,8,6,2,4,2,4,5,2,7,3,2,1);x<−round(rnorm(15),2)
M5<−sparseMatrix(i,j,x=x)
M5
12 x 8 sparse Matrix of class "dgCMatrix"
[1,] . −1.04 . −0.79 . . . .
[2,] . 0.40 . . . 2.1 . .
[3,] . . . . −1.37 . . .
[4,] . . . . 0.18 . . −0.68
[5,] . . . . . . −0.21 .
[6,] . . . −1.49 . . . .
[7,] . 0.05 . . . . . .
[8,] . . −1.86 . . . . .
[9,] . −0.49 . . . . . .
[10,] . 0.66 . . . . . .
[11,] . . −1.25 . . . . .
[12,] −0.02 . . . . . . .
Compute the median of the flattened NumPy array - GeeksforGeeks

05 Sep, 2020
In this article, we will discuss how to compute the median of the flattened array. Median is basically that value that separates the lower half of the array with the higher half of array.
Example:
If there are odd numbers in an array.A = [1,2,3,4,5,6,7]Then the median element will be 7+1/2= 4th element of the array.Hence the Median in this array is 4.
If there are even numbers in an arrayA = [1,2,3,4,5,6,7,8]Then the median element will be average of two middle elements.Here it will be an average of 4th and 5th element of the array that is 4+1/2 =4.5.
It can be calculated using the numpy.median() function in Python. This function computes the median of the given data (array elements) along the specified axis.
Syntax:
numpy.median(arr, axis = None)
Example 1: Odd no of elements 
Python3
# importing numpy as libraryimport numpy as np    # creating 1 D array with odd no of # elementsx_odd = np.array([1, 2, 3, 4, 5, 6, 7])print("\nPrinting the Original array:")print(x_odd)  # calculating medianmed_odd = np.median(x_odd)print("\nMedian of the array that contains \odd no of elements:")print(med_odd)
Output:
Printing the Original array:
[1 2 3 4 5 6 7]

Median of the array that contains odd no of elements:
4.0

Example 2: Even no of elements: 
Python3
# importing numpy as libraryimport numpy as np    # creating 1 D array with even no of # elementsx_even = np.array([1, 2, 3, 4, 5, 6, 7, 8])print("\nPrinting the Original array:")print(x_even)  # calculating medianmed_even = np.median(x_even)print("\nMedian of the array that contains \even no of elements:")print(med_even)
Output:
Printing the Original array:
[1 2 3 4 5 6 7 8]

Median of the array that contains even no of elements:
4.5

Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Parzen Windows density estimation technique

04 Jan, 2022
Parzen Window is a non-parametric density estimation technique. Density estimation in Pattern Recognition can be achieved by using the approach of the Parzen Windows. Parzen window density estimation technique is a kind of generalization of the histogram technique. 
It is used to derive a density function, . is used to implement a Bayes Classifier. When we have a new sample feature and when there is a need to compute the value of the class conditional densities, is used. takes sample input data value and returns the density estimate of the given data sample. 
An n-dimensional hypercube is considered which is assumed to possess k-data samples. The length of the edge of the hypercube is assumed to be hn. 
 
Hence the volume of the hypercube is: Vn = hnd 
We define a hypercube window function, φ(u) which is an indicator function of the unit hypercube which is centered at origin.: φ(u) = 1 if |ui| <= 0.5 φ(u) = 0 otherwise Here, u is a vector, u = (u1, u2, ..., ud)T. φ(u) should satisfy the following:
Let 
Since, φ(u) is centered at the origin, it is symmetric. φ(u) = φ(-u)  
is a hypercube of size h centered at u0
Let D = {x1, x2, ..., xn} be the data samples.
For any would be 1 only if falls in a hypercube of side centered at .
Hence the number of data points falling in a hypercube of side h centered at x is 
Hence the estimated density function is : 
*** QuickLaTeX cannot compile formula:
 

*** Error message:
Error: Nothing to show, formula is empty

Also Since, Vn = hnd, Density Function becomes : 
would satisfy the following conditions:  
nnr223442
Computer Subject
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Strings with all given List characters

When it is required to find the strings which have all the given characters present in a list, a method is defined that takes the string as a parameter and iterates through the string, and adds the index value to it.
Below is a demonstration of the same −
print("Method definition begins...")
def convert_to_my_string(my_string):
   my_result = ""
   for index in my_string:
      my_result += index

   return my_result
print("Method definition ends...")
my_string = ['L','e','a','r','n','P','y','t','h','o','n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']

print("The list is : " )
print(my_string) 

print("The resultant string is : ")
print(convert_to_my_string(my_string))
Method definition begins...
Method definition ends...
The list is :
['L', 'e', 'a', 'r', 'n', 'P', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']
The resultant string is :
LearnPythoncoolfun
A method named ‘convert_to_my_string’ is defined that takes a string as a parameter.
A method named ‘convert_to_my_string’ is defined that takes a string as a parameter.
An empty string is defined.
An empty string is defined.
The original parameter is iterated over, and the element is added to the empty string.
The original parameter is iterated over, and the element is added to the empty string.
This is returned as output.
This is returned as output.
Outside the method, a list of characters is defined and is displayed on the console.
Outside the method, a list of characters is defined and is displayed on the console.
The method is called by passing every character to it.
The method is called by passing every character to it.
The result is displayed as the output on the console.
The result is displayed as the output on the console.
response.headers – Python requests

01 Mar, 2020
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.headers out of a response object. response.headers returns a dictionary of response headers. To check more about headers, visit – Different HTTP Headers
To illustrate use of response.headers, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
# import requests moduleimport requests  # Making a get requestresponse = requests.get('https://api.github.com')  # print responseprint(response)  # print headers of responseprint(response.headers)
Save above file as request.py and run using
Python request.py

Check that headers at the start of the output, it shows the different headers. Headers are used for different purposes such as Authentication/ Passing and retrieving data from the server, etc.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lex program to identify the identifier

30 Apr, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lex in the C programming language.
In C, an identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover digits can come after.
Example:
gfg : valid identifier
123 : invalid identifier
_abc12 : valid identifier
#abc : invalid identifier

Let’s see the lex program to determine whether input is an identifier or not.
/*lex code to determine whether input is an identifier or not*/% {#include <stdio.h>    %}      / rule section % %    // regex for valid identifiers    ^[a - z A - Z _][a - z A - Z 0 - 9 _] * printf("Valid Identifier");  // regex for invalid identifiers^[^a - z A - Z _] printf("Invalid Identifier");.;% %      main(){    yylex();}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Top 10 Programming Languages to Learn in 2022
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
How to Add External JAR File to an IntelliJ IDEA Project?
How to navigate on path by button click in react router ?
Define multipart form data
How to Install Git in VS Code?
reflect.Field() Function in Golang with Examples

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Field() Function in Golang is used to get the i’th field of the struct v. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) Field(i int) Value

Parameters: This function does not accept any parameters.
Return Value: This function returns the i’th field of the struct v.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Field() Function    package main   import (    "fmt"    "reflect")   // Main functionfunc main() {       tt:= reflect.StructOf([]reflect.StructField{        {            Name: "Height",            Type: reflect.TypeOf(0.0),            Tag:  `json:"height"`,        },        {            Name: "Name",            Type: reflect.TypeOf("abc"),            Tag:  `json:"name"`,        },    })       fmt.Println(tt.NumField())       //use of Field() method    fmt.Println(tt.Field(0))    fmt.Println(tt.Field(1))   }    
Output:
2
{Height  float64 json:"height" 0 [0] false}
{Name  string json:"name" 8 [1] false}

Example 2:
// Golang program to illustrate// reflect.Field() Function      package main     import (    "fmt"    "reflect")   type temp struct {      ord      int    cId int}   // function to use the // Field() method func useKind(val interface{}) {         // Kind() function is used    // to find the kind    if reflect.ValueOf(val ).Kind() == reflect.Struct {        v := reflect.ValueOf(val )        fmt.Println("Number of fields", v.NumField())        for i := 0; i < v.NumField(); i++ {            fmt.Printf("Field: %d \t type: %T \t value: %v\n",                                    i, v.Field(i), v.Field(i))        }    }      }    // Main function func main() {      val := temp {        ord: 1,        cId: 513,    }    useKind(val)   }   
Output:
Number of fields 2
Field: 0      type: reflect.Value      value: 1
Field: 1      type: reflect.Value      value: 513

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | dropzone Attribute

19 Jul, 2019
The dropzone attribute in HTML is used to specify whether the dragged data copied, moved, or linked when it is dropped on any element. This attribute is new in HTML5.
Syntax:
<element dropzone = "move | link | copy">
Attribute Value:
move: This attribute is used to drag the data and drop it into new location.
copy:This attribute is used to copy the drag data into new location.
link: This attribute is used to drop the data will result into original data.
Example:
<!DOCTYPE html> <html>   <head>      <title>ruby tag</title>      <style>          body {              text-align:center;          }          h1 {              color:green;          }       </style>   </head>   <body>      <h1>GeeksforGeeks</h1>      <h2> dropzone attribute</h2>      <div dropzone="copy">GFG</div>      <div dropzone="move">GFG</div>      <div dropzone="link">GFG</div>   </body></html>
Output:
Note: The dropzone attribute doesn’t support by the popular browsers.
HTML-Attributes
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Properties containsKey(value) method in Java with Examples

23 May, 2019
The containsKey(value) method of Properties class is used to check if this Properties object contains any mapping of this Key for any key present in it. It takes this value to be compared as parameter and returns a boolean value as result.
Syntax:
public Object containsKey(Object value)
Parameters: This method accepts a parameter value which is the key to be searched in this Properties.
Returns: This method returns a boolean value stating the result whether this key is present in this Properties object or not.
Below programs illustrate the containsKey(value) method:
Program 1:
// Java program to demonstrate// containsKey(value) method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();        properties.put("Pen", 10);        properties.put("Book", 500);        properties.put("Clothes", 400);        properties.put("Mobile", 5000);          // Print Properties details        System.out.println("Current Properties: "                           + properties.toString());          // Check if Pen is present or not        // using containsKey()        System.out.println("Is Pen present: "                           + properties.containsKey("Pen"));    }}
Current Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
Is Pen present: true

Program 2:
// Java program to demonstrate// containsKey(value) method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();          properties.put(1, "100RS");        properties.put(2, "500RS");        properties.put(3, "1000RS");          // print Properties details        System.out.println("Current Properties: "                           + properties.toString());          // Check if 5 is present or not        // using containsKey()        System.out.println("Is 5 present: "                           + properties.containsKey(5));    }}
Current Properties: {3=1000RS, 2=500RS, 1=100RS}
Is 5 present: false

References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#containsKey-java.lang.Object-
nidhi_biet
Java - util package
Java-Functions
Java-Properties
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stacked Bar Chart in R - GeeksforGeeks

17 Feb, 2021

A stacked bar chart extends the standard bar chart from looking at numeric values across one categorical variable to two. Each bar in a standard bar chart is divided into a number of sub-bars stacked end to end, each one corresponding to a level of the second categorical variable. This article discusses how one can be created using R.
The function used here to create a stacked bar chart is barplot().
Syntax: barplot(H,xlab,ylab,main, names.arg,col)
Parameters:
H: is a vector or matrix containing numeric values used in a bar chart.
xlab: is the label for the x-axis.
ylab: is the label for the y-axis.
main: is the title of the bar chart.
names.arg: is a vector of names appearing under each bar.
col: is used to give colors to the bars in the graph.
Returns: a barplot.
Approach
Create data
Pass the data to the barplot() function
Pass appropriate arguments to the function
Display plot
Example:
R
 

 
 










dat <- read.table(text = "A   B   C   D   E   F    G 
1 10 80 30 90 70 60  90 
2 20 50 70 50 40 10  40 
3 60 80 80 60  60 30 160 
4 20 40 70 80 20 10  70", header = TRUE) 
  
barplot(as.matrix(dat))






Output:
Example 2: 
R
 

 
 










dat <- read.table(text ="ProdA ProdB ProdC ProdD 
1 110 50 60 70  
2 120 50 80 65", header= TRUE) 
  
barplot(as.matrix(dat),col=c("gold3","red"))






Output:

Picked


R-Charts


R-Graphs


R-plots


R Language

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
What is the difference between size and capacity of a Vector in Java?

The size of a vector represents the number of components in the vector. The capacity of a vector represents the maximum number of elements the vector can hold.
Example:
import java.util.*;

public class VectorDemo {
   public static void main(String args[]) {
      Vector v = new Vector(3, 2);
      System.out.println("Initial size: " + v.size());
      System.out.println("Initial capacity: " + v.capacity());
      v.addElement(new Integer(1));
      v.addElement(new Integer(2));
      v.addElement(new Integer(3));
      v.addElement(new Integer(4));
      System.out.println("Capacity after four additions: " + v.capacity());
      v.addElement(new Double(5.45));
      System.out.println("Current capacity: " + v.capacity());
      v.addElement(new Double(6.08));
      v.addElement(new Integer(7));
      System.out.println("Current capacity: " + v.capacity());
      v.addElement(new Float(9.4));
      v.addElement(new Integer(10));
      System.out.println("Current capacity: " + v.capacity());
      v.addElement(new Integer(11));
      v.addElement(new Integer(12));
      System.out.println("First element: " + (Integer)v.firstElement());
      System.out.println("Last element: " + (Integer)v.lastElement());
      if(v.contains(new Integer(3)))
      System.out.println("Vector contains 3.");
      Enumeration vEnum = v.elements();
      System.out.println("\nElements in vector:");
      while(vEnum.hasMoreElements())
      System.out.print(vEnum.nextElement() + " ");
      System.out.println();
   }
}
Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
HTML | <area> coords Attribute

08 Jun, 2021
The <area> coords attribute is used to specify the coordinate of an area in an image-map. It is used with shape attribute to specify the size, shape, and placement of an area. (0, 0) is the coordinate of the top-left corner.Syntax:  
<area coords="value">
Attribute Values:  
x1, y1, x2, y2: It specifies the coordinate of top-left (x1, y1) and bottom-right (x2, y2) corner of the rectangle.
x, y, radius: It specifies the center coordinates (x, y) and radius (radius) of circle.
x1, y1, x2, y2, .., xn, yn: It specifies the coordinates of polygon. If the first and last coordinate pairs are not the same, the browser will add the last coordinate pair to close the polygon.
Example:  
html
<!DOCTYPE html><html> <head>    <title>        HTML area coords Attribute    </title></head> <body style="text-align:center;">    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190227165729/area11.png"        alt="alt_attribute" width="300" height="119"        class="aligncenter" usemap="#shapemap" />     <map name="shapemap">                 <!-- area tag contained image. -->        <area shape="poly" coords="59, 31, 28, 83, 91, 83" href="https://media.geeksforgeeks.org/wp-content/uploads/20190227165802/area2.png"        alt="Triangle">                 <area shape="circle" coords="155, 56, 26" href="https://media.geeksforgeeks.org/wp-content/uploads/20190227165934/area3.png"        alt="Circle">                 <area shape="rect" coords="224, 30, 276, 82" href="https://media.geeksforgeeks.org/wp-content/uploads/20190227170021/area4.png"        alt="Square">    </map></body> </html>                   
Output:  
Before click on specific clickable area:  
After click on specific clickable area:  
Supported Browsers: The browser supported by <area> coords attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera
 
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MuleSoft - DataWeave Language

DataWeave is basically a MuleSoft expression language. It is mainly used for accessing and transforming the data received through a Mule application. Mule runtime is responsible for running the script and expressions in our Mule application, DataWeave is strongly integrated with Mule runtime.
Following are some important features of DataWeave language −
Data can be transformed from one format to another very easily. For example, we can transform application/json to application/xml. The input payload is as follows −
{
   "title": "MuleSoft",
   "author": " tutorialspoint.com ",
   "year": 2019
}
Following is the code in DataWeave for transform −
%dw 2.0
output application/xml
---
{
   order: {
      'type': 'Tutorial', 
      'title': payload.title, 
      'author': upper(payload.author), 
      'year': payload.year
   }
}
Next, the output payload is as follows −
<?xml version = '1.0' encoding = 'UTF-8'?>
<order>
   <type>Tutorial</type>
   <title>MuleSoft</title>
   <author>tutorialspoint.com</author>
   <year>2019</year>
</order>

The transform component can be used for creating scripts that performs both simple as well as complex data transformations.
We can access and use core DataWeave functions on parts of the Mule event that we need as most of the Mule message processors support DataWeave expressions.
We need to satisfy the following prerequisites before using DataWeave scripts on our computer −
Anypoint Studio 7 is required to use Dataweave scripts.
Anypoint Studio 7 is required to use Dataweave scripts.
After installing Anypoint Studio, we need to set up a project with a Transform Message component in order to use DataWeave scripts.
After installing Anypoint Studio, we need to set up a project with a Transform Message component in order to use DataWeave scripts.
In order to use DataWeave scrip, we need to follow the steps below −
Step 1
First, we need to set up a new project, as we did in the previous chapter, by using File → New → Mule Project.
Step 2
Next, we need to provide the name of the project. For this example, we are giving the name, Mule_test_script.
Step 3
Now, we need to drag the Transform Message component from Mule Palette tab into canvas. It is shown as below −
Step 4
Next, in the Transform Message component tab, click on Preview to open Preview pane. We can expand the source code area by clicking the empty rectangle next to Preview.
Step 5
Now, we can start scripting with DataWeave language.
Following is the simple example of concatenating two strings into one −
The above DataWeave script is having a key-value pair ({ myString: ("hello" ++ "World") }) which will concatenate two strings into one.
set cbegin() and cend() function in C++ STL

20 Nov, 2020
The set::cbegin() is a built-in function in C++ STL which returns a constant iterator pointing to the first element in the container. The iterator cannot be used to modify the elements in the set container. The iterators can be increased or decreased to traverse the set accordingly. 
Syntax: 
constant_iterator set_name.cbegin()

Parameters: The function does not accept any parameters.
Return value: The function returns a constant iterator pointing to the first element in the container. 
Program to demonstrate the set::cbegin() method.
C++
// C++ program to demonstrate the// set::cbegin() function#include <bits/stdc++.h>using namespace std;int main(){     int arr[] = { 14, 12, 15, 11, 10 };     // initializes the set from an array    set<int> s(arr, arr + 5);     // prints all elements in set    for (auto it = s.cbegin(); it != s.cend(); it++)        cout << *it << " ";     return 0;}
10 11 12 14 15




 
set::cend() is a built-in function in C++ STL which returns a constant iterator pointing to the position past the last element in the container. The iterator cannot be used to modify the elements in the set container. The iterators can be increased or decreased to traverse in the set accordingly. 
Syntax: 
constant_iterator set_name.cend()

Parameters: The function does not accept any parameters.
Return value: The function returns a constant iterator pointing to the position past the last element in the container in the container. 
Program to demonstrate the set::cend() method.
C++
// C++ program to demonstrate the// set::cend() function#include <bits/stdc++.h>using namespace std;int main(){     int arr[] = { 14, 12, 15, 11, 10 };     // initializes the set from an array    set<int> s(arr, arr + 5);     // prints all elements in set    for (auto it = s.cbegin(); it != s.cend(); it++)        cout << *it << " ";     return 0;}
10 11 12 14 15




 
 
arorakashish0911
CPP-Functions
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Inheritance in C++
vector erase() and clear() in C++
C++ Classes and Objects
The C++ Standard Template Library (STL)
Substring in C++
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
How do I convert an integer to binary in JavaScript?

To convert an integer to binary in JavaScript, divide the integer by 2 and store the remainder.
Following is the code −
function convertDecimalToBinary(value) {
   var binaryValues = [];
   var counter = 0;
   while (value > 0) {
      binaryValues[counter++] = parseInt(value % 2);
      value = parseInt(value / 2);
   }
   for (var j = counter - 1; j >= 0; j--)
      process.stdout.write(binaryValues[j] + "");
}
convertDecimalToBinary(5);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo255.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo255.js
101
Python – Lambda function to find the smaller value between two elements

28 Nov, 2021
The lambda function is an anonymous function. It can have any number of arguments but it can only have one expression.
Syntax lambda arguments : expression
In this article, we will learn how to find the smaller value between two elements using the Lambda function.
Example:
Input : 2 5
Output : 2

Input : 7 5
Output : 5
Python3
# lambda function to return minimum of# two elements a, b are the arguments and# min() method is the expression here.get_min = lambda a, b : min(a,b)  print(get_min(5, 8))
Output:
5
Explanation: The a,b are passed to the lambda function and min() method is used as an expression to return the minimum element.
Python3
# lambda function to return minimum of two elements# a, b are the arguments and ternary# operator is used to compare two elementsget_min = lambda a, b : a if a < b else b  print(get_min(5, 8))
Output:
5
Explanation: a, b are the arguments and ternary operator is used for comparing two elements
Python3
# Two lambda functions will be stored# in tuple such that 1st element is b# and 2nd element will be b.# if [a<b] is true it return 1 and# element with index 1 will print# else if [a<b] is false it return 0,# so element with index 0 will printa = 5b = 8print((lambda: b, lambda: a)[a < b]())
Output:
5
Explanation: 
Two lambda functions will be stored in a tuple such that 1st element is b and 2nd element will be b. if [a<b] is true it return 1 and element with index 1 will print else if [a<b] is false it return 0, so element with index 0 will print.
Picked
python-lambda
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
CSS ::first-letter Selector

19 Oct, 2021
The ::first-letter selector CSS Pseudo-element is used to apply the style to the first letter of the first line of a block-level element, the condition is it should not be preceded by other content ( such as images or inline tables).
Syntax:
 ::first-letter {
    // CSS Property
}
Accepted Properties:
background properties
border properties
clear
color properties
float
font properties
line-height
margin properties
padding properties
text-decoration
text-transform
vertical-align (only if the float is ‘none’)
Example: This example illustrates the use of the ::first-letter selector where the color & font-size property is used to style the first letter.
HTML
<!DOCTYPE html><html><head>    <style>    p::first-letter {        font-size: 250%;        color: green;    }    </style></head>  <body style="text-align: center;">    <h1 style="color:green;">        CSS ::first-letter selector    </h1>    <p>Geeks classes is an extensive classroom programme.</p>  </body></html>
Output:
Supported Browsers: The browser supported by ::first-letter selector are listed below: 
Google Chrome 1.0
Firefox 1.0
Microsoft Edge 12.0
Safari 1.0
Opera 7.0 Partial from 3.5
Internet Explorer 9.0 Partial from 5.5
simranarora5sos
bhaskargeeksforgeeks
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
C++ Bitwise Operators

Try the following example to understand all the bitwise operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this program.
#include <iostream>
using namespace std;

main() {
   unsigned int a = 60;	  // 60 = 0011 1100  
   unsigned int b = 13;	  // 13 = 0000 1101
   int c = 0;           

   c = a & b;             // 12 = 0000 1100
   cout << "Line 1 - Value of c is : " << c << endl ;

   c = a | b;             // 61 = 0011 1101
   cout << "Line 2 - Value of c is: " << c << endl ;

   c = a ^ b;             // 49 = 0011 0001
   cout << "Line 3 - Value of c is: " << c << endl ;

   c = ~a;                // -61 = 1100 0011
   cout << "Line 4 - Value of c is: " << c << endl ;

   c = a << 2;            // 240 = 1111 0000
   cout << "Line 5 - Value of c is: " << c << endl ;

   c = a >> 2;            // 15 = 0000 1111
   cout << "Line 6 - Value of c is: " << c << endl ;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Python | Replace rear word in String - GeeksforGeeks

29 Nov, 2019
Sometimes, while working with String list, we can have a problem in which we need to replace the most rear i.e last word of string. This problem has many application in web development domain. Let’s discuss different ways in which this problem can be solved.
Method #1 : Using split() + join()This is one way in which we can perform this task. In this, we break elements into parts and then return the last value and perform the addition of new element using join().
# Python3 code to demonstrate working of# Rear word replace in String# using split() + join()  # initializing string test_str = "GFG is good"  # printing original string print("The original string is : " + test_str)  # initializing replace string rep_str = "best"  # Rear word replace in String# using split() + join()res =  " ".join(test_str.split(' ')[:-1] + [rep_str])  # printing resultprint("The String after performing replace : " + res)
The original string is : GFG is good
The String after performing replace : GFG is best

 
Method #2 : Using rfind() + join()The combination of these functions can also be used to perform this task. In this, we perform the task of extracting the last word of string using rfind() and join() is used to perform replace.
# Python3 code to demonstrate working of# Rear word replace in String# using rfind() + join()  # initializing string test_str = "GFG is good"  # printing original string print("The original string is : " + test_str)  # initializing replace string rep_str = "best"  # Rear word replace in String# using rfind() + join()res = test_str[: test_str.rfind(' ')] + ' ' + rep_str  # printing resultprint("The String after performing replace : " + res)
The original string is : GFG is good
The String after performing replace : GFG is best

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Tryit Editor v3.7

Tryit: The class selector
How to debug a core in C/C++?

A process dumps core when it is terminated by the operating system due to a fault in the program. The most typical reason this occurs is that the program accessed an invalid pointer value like NULL or some value out of its memory area. As part of that process, the operating system tries to write our information to a file to allow us to analyze what happened.
This core can be used as follows to diagnose and debug our program −
The core is dumped to the /proc/sys/kernel directory by default. To debug a core, the program must be compiled with the -g option. Once you have the core run gdb −
$ gdb  nameOfExecutable core
This will open the core in gdb and now you can proceed with your debugging. If you don't know how to use gdb, you can use this link to learn more: https://www.ibm.com/developerworks/library/l-gdb/
tiffcp - Unix, Linux Command

By default,
tiffcp will copy all the understood tags in a
TIFF directory of an input
file to the associated directory in the output file.


tiffcp can be used to reorganize the storage characteristics of data
in a file, but it is explicitly intended to not alter or convert
the image data content in any way.

tiffcp -c lzw a.tif b.tif result.tif


To convert a G3 1d-encoded
TIFF to a single strip of G4-encoded data the following might be used:

tiffcp -c g4 -r 10000 g3.tif g4.tif


To extract a selected set of images from a multi-image
TIFF file, the file name may be immediately followed by a ’,’
separated list of image directory indices.  The first image
is always in directory 0.  Thus, to copy the 1st and 3rd
images of image file "album.tif" to "result.tif":

tiffcp album.tif,0,2 result.tif


Given file "CCD.tif" whose first image is a noise bias
followed by images which include that bias,
subtract the noise from all those images following it
(while decompressing) with the command:

tiffcp -c none -b CCD.tif CCD.tif,1, result.tif


If the file above were named "CCD,X.tif", the "-,=" option would
be required to correctly parse this filename with image numbers,
as follows:

tiffcp -c none -,=% -b CCD,X.tif CCD,X%1%.tif result.tif

pal2rgb (1)
pal2rgb (1)
tiffinfo (1)
tiffinfo (1)
tiffcmp (1)
tiffcmp (1)
tiffmedian (1)
tiffmedian (1)
tiffsplit (1)
tiffsplit (1)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
jQuery - insertBefore( selector ) Method

The insertBefore( selector ) method inserts all of the matched elements before another, specified, set of elements.
Here is the simple syntax to use this method −
selector.insertBefore( selector )

Here is the description of all the parameters used by this method −
selector − Content before which the selected element(s) is inserted.
selector − Content before which the selected element(s) is inserted.
Following is a simple example a simple showing the usage of this method. This inserts division element with ID of "source" before an element which is begin clicked.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").click(function () {
               $("#source").insertBefore(this);
            });
         });
      </script>
		
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
	
   <body>
      <p>Click on any square below to see the result:</p>
		
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
      <div class = "div" id = "source"></div>
   </body>
</html>
This will produce following result −
Click on any square below to see the result −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Binding Function with double click with Tkinter ListBox - GeeksforGeeks

21 Apr, 2020
Prerequisites: Python GUI – tkinter, Python | Binding function in Tkinter
Tkinter in Python is GUI (Graphical User Interface) module which is widely used for creating desktop applications. It provides various basic widgets to build a GUI program.
To bind Double click with Listbox we use Binding functions in Python and then we execute the required actions based on the item selected in Listbox.Below is the implementation:
from tkinter import *   def go(event):    cs = Lb.curselection()          # Updating label text to selected option    w.config(text=Lb.get(cs))          # Setting Background Colour    for list in cs:                  if list == 0:            top.configure(background='red')        elif list == 1:            top.configure(background='green')        elif list == 2:            top.configure(background='yellow')        elif list == 3:            top.configure(background='white')      top = Tk()top.geometry('250x275')top.title('Double Click')   # Creating ListboxLb = Listbox(top, height=6)# Inserting items in ListboxLb.insert(0, 'Red')Lb.insert(1, 'Green')Lb.insert(2, 'Yellow')Lb.insert(3, 'White')   # Binding double click with left mouse# button with go functionLb.bind('<Double-1>', go)Lb.pack()   # Creating Edit box to show selected optionw = Label(top, text='Default')w.pack()top.mainloop()
Output:
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Updating boolean value in MySQL?

To update boolean value, you can use SET. Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, isMarried boolean
   );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(isMarried) values(false);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(isMarried) values(true);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(isMarried) values(true);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(isMarried) values(false);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-----------+
| Id | isMarried |
+----+-----------+
|  1 |         0 |
|  2 |         1 |
|  3 |         1 |
|  4 |         0 |
+----+-----------+
4 rows in set (0.00 sec)
Following is the query to update boolean value −
mysql> update DemoTable set isMarried = !isMarried where Id=4;
Query OK, 1 row affected (0.17 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us display the table records once again −
mysql> select *from DemoTable;
This will produce the following output. Here, we updated the boolean value for Id 4 −
+----+-----------+
| Id | isMarried |
+----+-----------+
|  1 |         0 |
|  2 |         1 |
|  3 |         1 |
|  4 |         1 |
+----+-----------+
4 rows in set (0.00 sec)
Look at the above sample output, the row with Id 4 has been updated.
How to get documents by tags in MongoDB?

You can use $elemMatch operator for this. Let us create a collection with documents
> db.getDocumentsByTagsDemo.insertOne({"Tags":["Tag-1", "Tag-2", "Tag-3"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb4d5d628fa4220163b79")
}
> db.getDocumentsByTagsDemo.insertOne({"Tags":["Tag-2", "Tag-4", "Tag-5"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb4d5d628fa4220163b7a")
}
> db.getDocumentsByTagsDemo.insertOne({"Tags":["Tag-6", "Tag-4", "Tag-3"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb4d6d628fa4220163b7b")
}
Following is the query to display all documents from a collection with the help of find() method
> db.getDocumentsByTagsDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b79"),
   "Tags" : [
      "Tag-1",
      "Tag-2",
      "Tag-3"
   ]
}
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"),
   "Tags" : [
      "Tag-2",
      "Tag-4",
      "Tag-5"
   ]
}
{
   "_id" : ObjectId("5c9eb4d6d628fa4220163b7b"),
   "Tags" : [
      "Tag-6",
      "Tag-4",
      "Tag-3"
   ]
}
Following is the query to get documents by tags
> db.getDocumentsByTagsDemo.find({Tags: { $elemMatch: { $eq: "Tag-2" } }}).pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b79"),
   "Tags" : [
      "Tag-1",
      "Tag-2",
      "Tag-3"
   ]
}
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"),
   "Tags" : [
      "Tag-2",
      "Tag-4",
      "Tag-5"
   ]
}
Following is the query to find specific tags only
> db.getDocumentsByTagsDemo.find({Tags: "Tag-5"}).pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"),
   "Tags" : [
      "Tag-2",
      "Tag-4",
      "Tag-5"
   ]
}