code-rag-bench/online-tutorials huggingface dataset:
Apex - Arrays

Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java.
Below is the representation of an Array of Products −
Index 0 − HCL
Index 1 − H2SO4
Index 2 − NACL
Index 3 − H2O
Index 4 − N2
Index 5 − U296
<String> [] arrayOfProducts = new List<String>();

Suppose, we have to store the name of our Products – we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index.
//Defining array
String [] arrayOfProducts = new List<String>();

//Adding elements in Array
arrayOfProducts.add('HCL');
arrayOfProducts.add('H2SO4');
arrayOfProducts.add('NACL');
arrayOfProducts.add('H2O');
arrayOfProducts.add('N2');
arrayOfProducts.add('U296');

for (Integer i = 0; i<arrayOfProducts.size(); i++) {
   //This loop will print all the elements in array
   system.debug('Values In Array: '+arrayOfProducts[i]);
}
You can access any element in array by using the index as shown below −
//Accessing the element in array
//We would access the element at Index 3
System.debug('Value at Index 3 is :'+arrayOfProducts[3]);

    14 Lectures 
     2 hours 

 Vijay Thapa

    7 Lectures 
     2 hours 

 Uplatz

    29 Lectures 
     6 hours 

 Ramnarayan Ramakrishnan

    49 Lectures 
     3 hours 

 Ali Saleh Ali

    10 Lectures 
     4 hours 

 Soham Ghosh

    48 Lectures 
     4.5 hours 

 GUHARAJANM
 Print
 Add Notes
 Bookmark this page
Sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms

19 Mar, 2021
Given the number of terms i.e. n. Find the sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms.Examples:  
Input : 2
Output : 0.65934

Input : 3
Output : 0.665334
 
Lets denote the sum by S: Using the formula , we have [since r<1]Hence the required sum is Below is the implementation:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesfloat sumOfSeries(int n){    return (0.666) * (1 - 1 / pow(10, n));} // Driver codeint main(){    int n = 2;    cout << sumOfSeries(n);}
// java program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n termsimport java.io.*; class GFG{    // function which return the    // the sum of series    static double sumOfSeries(int n)    {        return (0.666) * (1 - 1 /Math. pow(10, n));    }              // Driver code    public static void main (String[] args)    {        int n = 2;        System.out.println ( sumOfSeries(n));             }} // This code is contributed by vt_m
# Python3 program to find# sum of 0.6, 0.06, 0.006,# 0.0006, ...to n termsimport math # function which return# the sum of seriesdef sumOfSeries(n):    return ((0.666) *            (1 - 1 / pow(10, n))); # Driver coden = 2;print(sumOfSeries(n)); # This code is contributed by mits
// C# program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n termsusing System; class GFG {         // function which return the    // the sum of series    static double sumOfSeries(int n)    {        return (0.666) * (1 - 1 /Math. Pow(10, n));    }         // Driver code    public static void Main ()    {        int n = 2;                 Console.WriteLine( sumOfSeries(n));             }} // This code is contributed by vt_m
<?php// PHP program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms // function which return the// the sum of seriesfunction sumOfSeries($n){    return (0.666) * (1 - 1 /                pow(10, $n));} // Driver code$n = 2;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// javascript program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms // function which return the// the sum of seriesfunction sumOfSeries( n){    return (0.666) * (1 - 1 / Math.pow(10, n));} // Driver Codelet n = 2 ;   document.write(sumOfSeries(n).toFixed(5)) ;    // This code is contributed by aashish1995 </script>
Output:  
0.65934
 
jit_t
Mithun Kumar
aashish1995
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB – Maximum operator ( $max )

19 Apr, 2020
MongoDB provides different types of field update operators to update the values of the fields in the documents and the maximum operator ( $max ) is one of them. This operator updates the field with the specified value if the specified value is greater than the current value.
This operator will compare the values of different data types according to the BSON comparison order.
You can also use this operator in embedded/nested documents using dot notation.
You can use this operator in methods like update(), updateOne() etc. according to your requirements.
If the given field does not exists, then this operator will create field and set the value of that field.
Syntax:
{ $max: { field1: value1, field2: value2 ... } }
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are comparing values(or numbers) of the salary fields with the specified value, i.e., 5000. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 5000.
db.contributor.update({name: "Mohit"}, {$max: {salary: 5000}})
If the current value of the salary field is less than the specified value, then this operator will not update the value of the salary field with the specified value, i.e., 4000.
db.contributor.update({name: "Mohit"}, {$max: {salary: 4000}})
In this example, we are comparing values(or numbers) of the rank fields with the specified value, i.e., 30. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 30.
db.contributor.update({name: "Priya"}, {$max: {"personal.rank": 30}})
If the current value of the rank field is less than the specified value, then this operator will not update the value of the rank field with the specified value, i.e., 13.
db.contributor.update({name: "Priya"}, {$max: {"personal.rank": 13}})
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Retain Numbers in String

03 Jul, 2020
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the removal of all the characters other than integers. This kind of problem can have application in many data domains such as Machine Learning and web development. Let’s discuss certain ways in which this task can be performed.
Input : test_str = ‘G4g is No. 1’Output : 41
Input : test_str = ‘Gfg is No. 1’Output : 1
Method #1 : Using list comprehension + join() + isdigit()The combination of above functions can be used to solve this problem. In this, we perform the task of extracting integers using isdigit(), list comprehension is used for iteration and join() is used to perform join of numbers filtered.
# Python3 code to demonstrate working of # Retain Numbers in String# Using list comprehension + join() + isdigit()  # initializing stringtest_str = 'G4g is No. 1 for Geeks 7'  # printing original stringprint("The original string is : " + str(test_str))  # Retain Numbers in String# Using list comprehension + join() + isdigit()res = "".join([ele for ele in test_str if ele.isdigit()])  # printing result print("String after integer retention : " + str(res)) 
The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

 
Method #2 : Using regex()The solution of problem can also be found by using regex. In this, we formulate appropriate regex to filter only numbers from string.
# Python3 code to demonstrate working of # Retain Numbers in String# Using regex()import re  # initializing stringtest_str = 'G4g is No. 1 for Geeks 7'  # printing original stringprint("The original string is : " + str(test_str))  # Retain Numbers in String# Using regex()res = re.sub(r'[^\d]+', '', test_str)   # printing result print("String after integer retention : " + str(res)) 
The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2005 | Question 86

28 Jun, 2021
Consider the following expression grammar. The seman­tic rules for expression calculation are stated next to each grammar production.
 E → number      E.val = number. val
    | E '+' E      E(1).val = E(2).val + E(3).val
    | E '×' E     E(1).val = E(2).val × E(3).val 
Assume the conflicts in Part (a) of this question are resolved and an LALR(1) parser is generated for parsing arithmetic expressions as per the given grammar. Consider an expression 3 × 2 + 1. What precedence and associativity properties does the generated parser realize?(A) Equal precedence and left associativity; ex­pression is evaluated to 7(B) Equal precedence and right associativity; ex­pression is evaluated to 9(C) Precedence of ‘×’ is higher than that of ‘+’, and both operators are left associative; expression is evaluated to 7(D) Precedence of ‘+’ is higher than that of ‘×’, and both operators are left associative; expression is evaluated to 9Answer: (B)Explanation: Answer is B as the productions belong to the same non-terminal and since YACC resolves by shift over reduce, the associativity will be right associative.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Raw String Literal in C++

22 May, 2022
A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ‘ \n, \t, or \” ‘ of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”.
The syntax for Raw string Literal:
R "delimiter( raw_characters )delimiter" // delimiter is the end of logical entity
Here, delimiter is optional and it can be a character except the backslash{ / }, whitespaces{  }, and parentheses { () }.
These raw string literals allow a series of characters by writing precisely its contents like raw character sequence. 
Example:
Ordinary String Literal 
"\\\\n"
Raw String Literal 
  \/-- Delimiter
R"(\\n)"
     /\-- Delimiter
Difference between an Ordinary String Literal and a Raw String Literal:
Example of Raw String Literal:
CPP
// C++ program to demonstrate working of raw string literal#include <iostream>using namespace std; // Driver Codeint main(){    // A Normal string    string string1 = "Geeks.\nFor.\nGeeks.\n";     // A Raw string    string string2 = R"(Geeks.\nFor.\nGeeks.\n)";     cout << string1 << endl;     cout << string2 << endl;     return 0;}
Geeks.
For.
Geeks.

Geeks.\nFor.\nGeeks.\n
This article is contributed by MAZHAR IMAM KHAN. 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 if you want to share more information about the topic discussed above. 
Akanksha_Rai
anshikajain26
harsh_shokeen
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Virtual Function in C++
Proper Ways to Pass Environment Variables in JSON for cURL POST | by Xu LIANG | Towards Data Science

The best practice is using a data generation function. Scrolling to the bottom for the detail.
When we build an API-based web (front-end and back-end separated), we usually want to see what the HTTP client is sending or to inspect and debug webhook requests. There are two approaches:
Build an API server by ourselves
Use a fake mock API server
In this post, we choose the second approach and use RequestBin.
The usage is super simple. The mock API server will be ready after clicking the button.
Run the below command to make a POST request:
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d '{ "property1":"value1", "property2":"value2" }'
Refresh the web and confirm the status:
Run printenv will show the environment variable:
$ printenvLC_TERMINAL=iTerm2COLORTERM=truecolorTERM=xterm-256colorHOME=/Users/smap10...
We want to replace the value of property1 with TERM variable:
$ curl -X POST https://requestbin.io/1bk0un41  -H "Content-Type: application/json" -d '{ "property1":"$TERM", "property2":"value2" }'
But it seems TERM is not recognized as an environment variable.
$ curl -X POST https://requestbin.io/1bk0un41  -H "Content-Type: application/json" -d '{ "property1":"'"$TERM"'", "property2":"value2" }'
We can see the result is what we want.
The Outermost layer uses double-quotes. And add escaping mark for each double quote in the JSON data part.
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d "{ \"property1\":\"$TERM\", \"property2\":\"value2\" }"
This method can save us from all sort of headaches concerning shell quoting and makes it easier to read and maintain.
generate_post_data(){  cat <<EOF{  "property1":"$TERM",   "property2":"value2"}EOF}
Add the function to curl:
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d "$(generate_post_data)"
Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu.com
Understanding And Using REST APIs
How to include environment variable in bash line CURL?
Using curl POST with variables defined in bash script functions
What is correct syntax to create Python dictionary?

A Python dictionary object is a collection of key-value pairs. Each item in a dictionary consists of a value associated with key. The association is defined by putting : between them. Such key-value pairs, separated by comma and included within curly brackets, forms a dictionary object.
Key component of item must be an immutable object and unique in the collection. Value component may be repeated and can be of any data type.
>>> D1={"name":"Raaj", "age":23, "subjects":["Phy", "Che", "maths"],"GPA":8.5}
Conditional Rendering in ReactJS

In this article, we are going to see how to conditionally render a component based on some conditions in a React application
In ReactJS, we can render only the desired components based on certain given conditions by using the if-else statements or by using the logical && operator of JavaScript. When the provided condition is satisfied, then React will match the UI and update it accordingly.
In this example, we will build a React application that has an App component as a parent component which will conditionally re-render the Form component and update the UI accordingly.
App.jsx
import React, { useState } from 'react';
const App = () => {
   const [isLogin, setIsLogin] = useState(true);
   return (
      <div>
      <div>Username: Tutorialspoint</div>
      <div onClick={() => setIsLogin((prev) => !prev)}>
      {isLogin ? <Form login /> : <Form logout />}
      </div>
      </div>
   );
};

const Form = ({ login, logout }) => {
   return (
      <div>
      {login ? (
      <>
         <input placeholder="Email" />
         <input placeholder="Password" />
         <button>Login</button>
      </>
      ) : null}
      {logout ? (
         <button>Logout</button>
      ) : null}
      </div>
   );
};
export default App;
App.jsx
import React, { useState } from 'react';
const App = () => {
   const [isLogin, setIsLogin] = useState(true);
   return (
      <div>
      <div>Username: Tutorialspoint</div>
      <div onClick={() => setIsLogin((prev) => !prev)}>
      {isLogin ? <Form login /> : <Form logout />}
      </div>
      </div>
   );
};

const Form = ({ login, logout }) => {
   return (
      <div>
      {login && (
      <>
         <input placeholder="Email" />
         <input placeholder="Password" />
         <button>Login</button>
      </>
      )}
      {logout && (
         <button>Logout</button>
      )}
      </div>
   );
};
export default App;
Tryit Editor v3.7 - Show Java

class MyPackageClass { 
  public static void main(String[] args) { 
    System.out.println("This is my package!");
C++ Program to Implement Bit Array

This is a C++ program to implement Bit Array. A Bit Array is an array data structures that compactly stores data. It is basically used to implement a simple data structure.
Functions and pseudocodes:
Begin
   Function getBit(int val,int pos)
   singleBit->b = 0
   if(pos == 0)
      singleBit->b = val & 1
   else
      singleBit->b = ( val & (1 << pos ) ) >> pos
      return singleBit
   Function setBit(BitArr *bt,B *bit,int pos)
      bt->bVal[pos] = bit
      return bt
   Function getVal(BitArr *bArray)
   initialize val = 0
   initialize bVal = 0
   bVal = bArray->bVal[0]->b
   val= val|bVal
   for i = 1 to B_A_LENGTH-1
      bVal = bArray->bVal[i]->b
      bVal =bVal << i
      val=val | bVal
      return val
   done
End.
 Live Demo
#include <iostream>
#include <string>
using namespace std;
#define B_A_LENGTH 4
typedef struct {
   unsigned int b : 1;
} B;
class BitArr {
   private:
   B **bVal;
   public:
   BitArr() {
      bVal = new B* [B_A_LENGTH];
   }
   B *getBit(int val,int pos) {
      B *singleBit = new B;
      singleBit->b = 0;
      if(pos == 0) {
         singleBit->b = val & 1;
      } else {
         singleBit->b = ( val & (1 << pos ) ) >> pos;
      }
      return singleBit;
   }
   BitArr *setBit(BitArr *bt,B *bit,int pos) {
      bt->bVal[pos] = bit;
      return bt;
   }
   int getVal(BitArr *bArray) {
      int val = 0;
      unsigned int bVal = 0;
      bVal = bArray->bVal[0]->b;
      val |= bVal;
      for(int i = 1; i < B_A_LENGTH; i++) {
         bVal = bArray->bVal[i]->b;
         bVal <<= i;
         val |= bVal;
      }
      return val;
   }
};
int main() {
   int v;
   cout<<"Enter 4 bit integer value (0 - 8): ";
   cin>>v;
   BitArr bt, *samplebt;
   samplebt = new BitArr;
   for (int i = 0; i < B_A_LENGTH; i++) {
      samplebt = bt.setBit(samplebt, bt.getBit(v, i), i);
      cout<<"Bit of "<<v<<" at positon "<<i<<": "<<"\n"<<bt.getBit(v, i)->b<<endl;
   }
   cout<<"The value is: "<<bt.getVal(samplebt)<<endl;
   return 0;
}
Enter 4 bit integer value (0 - 8): 6Bit of 6 at positon 0:
0
Bit of 6 at positon 1:
1
Bit of 6 at positon 2:
1
Bit of 6 at positon 3:
0
The value is: 6
C program to print the length of a String using %n format specifier - GeeksforGeeks

11 Oct, 2019
Given string str. The task is to find the length of the string using %n format specifier
Examples:

Input: Geeks For Geeks
Output: 15

Input: Geeks
Output: 5

Appropach:
To find the length of string, we use special format specifier “%n” in printf function. In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.
Below is the implementation of the above approach:
// C program to print// the length of a String// using %n format specifier  #include <stdio.h>  // Driver codeint main(){    char str[100] = "Geeks for Geeks";    int len = 0;      printf("%s%n", str, &len);    printf(" = %d", len);      return 0;}
Geeks for Geeks = 15

C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Longest Common Subsequence | DP-4
Reverse a string in Java
Write a program to print all permutations of a given string
KMP Algorithm for Pattern Searching
C++ Data Types
Java Examples - Split PDF into Many

How to split a PDF in to many using Java.
Following is an example program to split a PDF in to many using Java.
import org.apache.pdfbox.multipdf.Splitter; 
import org.apache.pdfbox.pdmodel.PDDocument;  

import java.io.File; 
import java.io.IOException; 

import java.util.List; 
import java.util.Iterator;  

public class SplittingPDF { 
   public static void main(String[] args) throws IOException { 
      
      //Loading an existing PDF document 
      File file = new File("C:/pdfBox/splitpdf_IP.pdf"); 
      PDDocument doc = PDDocument.load(file); 

      //Instantiating Splitter class 
      Splitter splitter = new Splitter(); 
      
      //splitting the pages of a PDF document 
      List<PDDocument> Pages = splitter.split(doc); 

      //Creating an iterator 
      Iterator<PDDocument> iterator = Pages.listIterator();         

      //Saving each page as an individual document 
      int i = 1; 
      
      while(iterator.hasNext()){ 
         PDDocument pd = iterator.next(); 
         pd.save("C:/pdfBox/splitOP"+ i++ +".pdf");             
      } 
      System.out.println("PDF splitted");     
   } 
}
 
 Print
 Add Notes
 Bookmark this page
How to provide shadow effect in a Plot using path_effect attribute in Matplotlib

In order to provide path effects like shadow effect in a plot or a graph, we can use the path_effect attribute.
For example, let’s see how we can use the path_effect attribute in Matplotlib add a shadow effect to a sigmoid function.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patheffects import PathPatchEffect, SimpleLineShadow, Normal
Now let us define the size of the figure and plot the sigmoid function,
plt.style.use('seaborn-deep')
plt.subplots(figsize=(10,10))
Let us define the datapoints for the plot,
x = np.linspace(-10, 10, 50)
y = 1+ np.exp(-x))
Let us define the shadow property in the plot,
plt.plot(x, y, linewidth=8, color='blue', path_effects=
[SimpleLineShadow(), Normal()])
#Show the Plot
plt.show()
How to add one polynomial to another using NumPy in Python? - GeeksforGeeks

29 Aug, 2020
In this article, Let’s see how to add one polynomial to another. Two polynomials are given as input and the result is the addition of two polynomials.
The polynomial p(x) = C3 x2 + C2 x + C1  is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}. 
Let take two polynomials p(x) and q(x) then add these to get r(x) = p(x) + q(x) as a result of addition of two input polynomials.
If p(x) = A3 x2 + A2 x + A1 
and
q(x) = B3 x2 + B2 x + B1 

then result is 
r(x) = p(x) + q(x) 
i.e;
r(x) = (A3 + B3) x2 + (A2 + B2) x + (A1 + B1)
 
and output is 
( (A1 + B1), (A2 + B2), (A3 + B3) )

Below is the implementation with some examples :
Example 1: simple_use
Python3
# importing packageimport numpy  # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5,-2,5)  # q(x) = 2(x**2) + (-5)x +2qx = (2,-5,2)  # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx)  # print the resultant polynomialprint(rx)
Output :
[ 7. -7.  7.]

Example 2: #add_with_decimals
Python3
# importing packageimport numpy  # define the polynomials# p(x) = 2.2px = (0,0,2.2)  # q(x) = 9.8(x**2) + 4qx = (9.8,0,4)  # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx)  # print the resultant polynomialprint(rx)
Output :
[ 9.8  0.   6.2]

Example 3: eval_then_add
Python3
# importing packageimport numpy  # define the polynomials# p(x) = (5/3)xpx = (0,5/3,0)  # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4,0,9/5)  # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx)  # print the resultant polynomialprint(rx)
Output :
[-1.75        1.66666667  1.8       ]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
p5.js | loop() Function - GeeksforGeeks

17 Jan, 2020
The loop() function is used to call draw() function continuously. The loop() function can be stopped using noLoop() function.
Syntax:
loop()
Below example illustrates the loop() function in p5.js:
Example:
let l = 0;  function setup() {      // Create canvas of given size  createCanvas(500, 300);      // Set the background color  background('green');  }  function draw() {      // Set the stroke color  stroke('white');      l = l + 0.5;  if (l > width) {    l = 0;  }      // Function to draw the line  line(l, 0, l, height);    }  function mousePressed() {  noLoop();}  function mouseReleased() {  loop();}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
JavaScript-p5.js
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Java Program to Print Downward Triangle Star Pattern - GeeksforGeeks

17 Mar, 2021
Downward triangle star pattern means we want to print a triangle that is downward facing means base is upwards and by default, orientation is leftwards so the desired triangle to be printed should look like
* * * *
* * *
* *
*
Example
Java
// Java Program to Print Lower Star Triangle Pattern  // Main classpublic class GFG {      // Main driver method    public static void main(String[] args)    {        // Nested 2 for loops for iteration over the matrix          // Outer loop for rows        int rows = 9;        for (int a = rows - 1; a >= 0; a--) {              // Inner loop for columns            for (int b = 0; b <= a; b++) {                  // Prints star and space                System.out.print("*"                                 + " ");            }              // By now we are done with single row so new            // line            System.out.println();        }    }}
* * * * * * * * * 
* * * * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

java-basics
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
How to create a hyperlink with a Label in Tkinter?

Tkinter Label widgets are generally used to display text or images. In this example, we will see how to add a hyperlink on a Label widget in an application.
In order to add a hyperlink, we can bind the label text with a button that makes it clickable. The open_new(url) method is used to define the function that opens a web browser to follow the link. The open_new(url) method is defined in the webbrowser module in Python which can be imported in the notebook using 'import webbrowser'.
#Import the required libraries
from tkinter import *
import webbrowser

#Create an instance of tkinter frame
win = Tk()
win.geometry("750x250")

#Define a callback function
def callback(url):
   webbrowser.open_new_tab(url)

#Create a Label to display the link
link = Label(win, text="www.tutorialspoint.com",font=('Helveticabold', 15), fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", lambda e:
callback("http://www.tutorialspoint.com"))

win.mainloop()
Running the above code will display a Label text with a URL.
The displayed window will show a hyperlink which upon clicking will redirect the user to the website: www.tutorialspoint.com
Java & MySQL - Transactions

If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −
To increase performance.
To increase performance.
To maintain the integrity of business processes.
To maintain the integrity of business processes.
To use distributed transactions.
To use distributed transactions.
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);

Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −
conn.commit( );

Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −
conn.rollback( );

The new JDBC 3.0 Savepoint interface gives you the additional transactional control.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint.
The Connection object has two new methods that help you manage savepoints −
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Maximum number of characters between any two same character in a string in C

We are given a string of alphabets. The array can have at least two occurrences of the same character. The task here is to find the maximum number of characters between any two occurrences of a character. If there is no repetition of any character then return -1.
Input − string str = “abcdba”
Output −Maximum number of characters between any two same character in a string − 4
Explanation − The repeating characters are ‘a’ and ‘b’ only with indexes −
1. 2‘a’ first index 0 last 5 , characters in between 5-0-1=4
2. ‘b’ first index 1 last 4 , characters in between 4-1-1=2
   Maximum character in between repeating alphabets : 4
Input − string str = “AbcAaBcbC”
Output −Maximum number of characters between any two same character in a string − 5
Explanation − The repeating characters are ‘A’ , ‘b’ , ‘c’ only with indexes −
1. ‘A’ first index 0 last 3 , characters in between 3-0-1=2
2. ‘b’ first index 1 last 7 , characters in between 7-1-1=5
3. ‘c’ first index 2 last 6 , characters in between 6-2-1=3
   Maximum character in between repeating alphabets : 5
Note − if the input string is “abcdefg” , there are no repeating characters so the function will return -1.
We take a character array having a string of characters as Str[]
We take a character array having a string of characters as Str[]
The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets.
The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets.
We initialize the variable maxC with -1.
We initialize the variable maxC with -1.
Inside for loop traverse the array of string from the beginning.
Inside for loop traverse the array of string from the beginning.
In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] ).
In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] ).
If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)
If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)
If this value is maximum found so far, then store it in maxC.
If this value is maximum found so far, then store it in maxC.
Return maxC after traversing the whole string.
Return maxC after traversing the whole string.
 Live Demo
#include <stdio.h>
#include <stdio.h>
#include <math.h>
int maxChars(char str[],int n){
   int size = n;
   int maxC = -1;
   for (int i = 0; i < n - 1; i++)
      for (int j = i + 1; j < n; j++)
         if (str[i] == str[j]){
            int temp=abs(j-i-1);
            maxC = maxC>temp?maxC:temp;
         }
   return maxC;
}
// Driver code
int main(){
   char Str[] = "AbcAaBcbC";
   printf("Maximum number of characters between any two same character in a string :%d",
   maxChars(Str,9) );
   return 0;
}
If we run the above code it will generate the following output −
Maximum number of characters between any two same character in a string : 5
How to programmatically configure Chrome extension through Selenium WebDriver?

We can programmatically configure Chrome extension through Selenium webdriver. We can have multiple extensions of the Chrome browser while we manually open the browser and work on it.
However, while the Chrome browser is opened through Selenium webdriver, those extensions which are available to the local browser will not be present. To configure an extension, we have to obtain the .crx extension file of the extension.
Then we have to add that extension to the browser which is launched by
Selenium webdriver. To get all the extensions available to the browser enter
chrome://extensions on the browser.
To get add an extension for example: Momentum, visit the link −
https://chrome.google.com/webstore/category/extensions and enter Momentum in the search box. Once the search results are displayed, click on the relevant option.
After clicking on the Momentum extension, the details of the extension gets displayed. Copy the URL of the extension as highlighted in the below image.
Now, navigate to the link: https://chrome−extension−downloader.com/ and paste the URL we have copied within the Download extension field.
The .crx file of the extension gets downloaded to our system. We should then
save it in a desired location.
To add this extension to the Chrome browser, once it is launched by Selenium webdriver, we have to use the ChromeOptions class. We shall create an object of this class and apply addExtensions method on it.
The path of the .crx file of the extension that we want to add is passed as a parameter to that method. Then use the DesiredCapabilities class to set this browser capability.
We shall apply the setCapability method on the object of DesiredCapabilities and pass ChromeOptions.CAPABILITY and object of the ChromeOptions class as parameters to that method. Finally, the object of DesiredCapabilities is passed as a parameter to the webdriver object.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
public class AddExtensns{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      //ChromeOptions object
      ChromeOptions opt= new ChromeOptions();
      //set path of .crx file of extension
      opt.addExtensions(new File("C:\\Users\\Momentum_v0.92.2.crx"));
      //DesiredCapabilities object
      DesiredCapabilities c = DesiredCapabilities.chrome();
      // set ChromeOptions capability
      c.setCapability(ChromeOptions.CAPABILITY, opt);
      // pass capability to driver
      WebDriver driver = new ChromeDriver(c);
      driver.get("https://www.tutorialspoint.com/index.htm");
   }
}
Count words present in a string - GeeksforGeeks

30 Jun, 2017
Given an array of words and a string, we need to count all words that are present in given string.
Examples:
Input : words[] = { "welcome", "to", "geeks", "portal"}
            str = "geeksforgeeks is a computer science portal for geeks."
Output :  2
Two words "portal" and "geeks" is present in str.


Input : words[] = {"Save", "Water", "Save", "Yourself"}
        str     = "Save"
Output :1

Steps:
Extract each word from string.For each word, check if it is in word array(by creating set/map). If present, increment result.
Extract each word from string.
For each word, check if it is in word array(by creating set/map). If present, increment result.
Below is the Java implementation of above steps
// Java program to count number // of words present in a string  import java.util.HashSet;import java.util.regex.Matcher;import java.util.regex.Pattern;  public class Test {    static int countOccurrence(String[] word, String str)     {        // counter        int counter = 0;                  // for extracting words        Pattern p = Pattern.compile("[a-zA-Z]+");        Matcher m = p.matcher(str);                  // HashSet for quick check whether        //  a word in str present in word[] or not        HashSet<String> hs = new HashSet<String>();                  for (String string : word) {            hs.add(string);        }                  while(m.find())        {            if(hs.contains(m.group()))                counter++;        }                  return counter;              }          public static void main(String[] args)     {        String word[] = { "welcome", "to", "geeks", "portal"};                  String str = "geeksforgeeks is a computer science portal for geeks.";                  System.out.println(countOccurrence(word,str));              }  }
Output:
2

This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
How to split a string in C/C++, Python and Java?
C++ Program to Perform Matrix Multiplication

A matrix is a rectangular array of numbers that is arranged in the form of rows and columns.
An example of a matrix is as follows.
A 3*2 matrix has 3 rows and 2 columns as shown below −
8 1
4 9
5 6
A program that performs matrix multiplication is as follows.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
   int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
   int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
   if (c1 != r2) {
      cout<<"Column of first matrix should be equal to row of second matrix";
   } else {
      cout<<"The first matrix is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c1; ++j)
         cout<<a[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      cout<<"The second matrix is:"<<endl;
      for(i=0; i<r2; ++i) {
         for(j=0; j<c2; ++j)
         cout<<b[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      for(i=0; i<r1; ++i)
      for(j=0; j<c2; ++j) {
         product[i][j] = 0;
      }
      for(i=0; i<r1; ++i)
      for(j=0; j<c2; ++j)
      for(k=0; k<c1; ++k) {
         product[i][j]+=a[i][k]*b[k][j];
      }
      cout<<"Product of the two matrices is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c2; ++j)
         cout<<product[i][j]<<" ";
         cout<<endl;
      }
   }
   return 0;
}
The first matrix is:
2 4 1
2 3 9
3 1 8
The second matrix is:
1 2 3
3 6 1
2 4 7
Product of the two matrices is:
16 32 17
29 58 72
22 44 66
In the above program, the two matrices a and b are initialized as follows −
int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
If the number of columns in the first matrix are not equal to the number of rows in the second matrix then multiplication cannot be performed. In this case an error message is printed. It is given as follows.
if (c1 != r2) {
   cout<<"Column of first matrix should be equal to row of second matrix";
}
Both the matrices a and b are displayed using a nested for loop. This is demonstrated by the following code snippet.
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
   for(j=0; j<c1; ++j)
   cout<<a[i][j]<<" ";
   cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
   for(j=0; j<c2; ++j)
   cout<<b[i][j]<<" ";
   cout<<endl;
}
cout<<endl;
After this, the product[][] matrix is initialized to 0. Then a nested for loop is used to find the product of the 2 matrices a and b. This is demonstrated in the below code snippet.
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
   product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
   product[i][j]+=a[i][k]*b[k][j];
}
After the product is obtained, it is printed. This is shown as follows.
cout<<Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
   for(j=0; j<c2; ++j)
   cout<<product[i][j]<<" ";
   cout<<endl;
}
C library function - strncpy()

The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where the length of src is less than that of n, the remainder of dest will be padded with null bytes.
Following is the declaration for strncpy() function.
char *strncpy(char *dest, const char *src, size_t n)
dest − This is the pointer to the destination array where the content is to be copied.
dest − This is the pointer to the destination array where the content is to be copied.
src − This is the string to be copied.
src − This is the string to be copied.
n − The number of characters to be copied from source.
n − The number of characters to be copied from source.
This function returns the pointer to the copied string.
The following example shows the usage of strncpy() function. Here we have used function memset() to clear the memory location.
#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[12];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strncpy(dest, src, 10);

   printf("Final copied string : %s\n", dest);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Final copied string : This is tu


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Query to find 2nd largest value in a column in Table

11 Jun, 2019
Problem: Write a SQL query to find the 2nd largest value in a column in a table.
Examples:In the 1st example find the 2nd largest value in column “Income” and in the 2nd one find the 2nd largest value in “Cost”.
Input: Table name- Employee
+------+--------+
| Name | Income |
+------+--------+
| abc  | 4000   |
| xyz  | 4752   |
| qwe  | 6579   |
+------+--------+

Output: 4752

Input: Table name- price_list
+-------------+--------+
| Item        | Cost   |
+-------------+--------+
| Apple       | 150    |
| Banana      | 175    |
| Mango       | 200    |
| Pineapple   | 180    |
+-------------+--------+

Output: 180 
Method-1:
Syntax:
SELECT MAX (column_name) 
FROM table_name 
WHERE column_name NOT IN (SELECT Max (column_name) 
                          FROM table_name); 
First we selected the max from that column in the table then we searched for the max value again in that column with excluding the max value which has already been found, so it results in the 2nd maximum value.
Example-1:SELECT MAX (Income) 
FROM Employee 
WHERE Salary NOT IN (SELECT Max (Income) 
                     FROM Employee); 
SELECT MAX (Income) 
FROM Employee 
WHERE Salary NOT IN (SELECT Max (Income) 
                     FROM Employee); 
Example-2:SELECT MAX (Cost) 
FROM price_list 
WHERE Salary NOT IN (SELECT Max (Cost) 
                     FROM price_list); 
SELECT MAX (Cost) 
FROM price_list 
WHERE Salary NOT IN (SELECT Max (Cost) 
                     FROM price_list); 
Method-2:
Syntax:
SELECT column_name
FROM table_name e
WHERE 2 = (SELECT COUNT (DISTINCT column_name) 
           FROM table_name p
           WHERE e.column_name<=p.column_name) 
This is a nested sub query which is a generic SQL query to print the Nth largest value in column. For each record processed by outer query, inner query will be executed and will return how many records has records has value less than the current value. If you are looking for second highest value then your query will stop as soon as inner query will return 2.
Example-1:SELECT Income
FROM Employee e
WHERE 2=(SELECT COUNT(DISTINCT Income) 
         FROM Employee p
         WHERE e.Income<=p.Income) 
SELECT Income
FROM Employee e
WHERE 2=(SELECT COUNT(DISTINCT Income) 
         FROM Employee p
         WHERE e.Income<=p.Income) 
Example-2:SELECT Cost
FROM price_list e
WHERE 2=(SELECT COUNT(DISTINCT Cost) 
         FROM price_list p
         WHERE e.Cost<=p.Cost) 
SELECT Cost
FROM price_list e
WHERE 2=(SELECT COUNT(DISTINCT Cost) 
         FROM price_list p
         WHERE e.Cost<=p.Cost) 
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
Introduction of B-Tree
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?