code-rag-bench/online-tutorials huggingface dataset:
Python SQLite – Create Table

13 Jan, 2022
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. 
In SQLite database we use the following syntax to create a table:
CREATE TABLE database_name.table_name(
                                       column1 datatype PRIMARY KEY(one or more columns),
                                       column2 datatype,
                                       column3 datatype,
                                       .....
                                       columnN datatype
);
Now we will create a table using Python:
Approach:
Import the required module
Establish the connection or create a connection object with the database using the connect() function of the sqlite3 module.
Create a Cursor object by calling the cursor() method of the Connection object.
Form table using the CREATE TABLE statement with the execute() method of the Cursor class.
Implementation:
Python3
import sqlite3 # Connecting to sqlite# connection objectconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Drop the GEEK table if already exists.cursor_obj.execute("DROP TABLE IF EXISTS GEEK") # Creating tabletable = """ CREATE TABLE GEEK (            Email VARCHAR(255) NOT NULL,            First_Name CHAR(25) NOT NULL,            Last_Name CHAR(25),            Score INT        ); """ cursor_obj.execute(table) print("Table is Ready") # Close the connectionconnection_obj.close()
Output:
rkbhola5
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Odd elements indices

19 Feb, 2020
Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of Odd elements.
Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we check for odd element in list and append its index accordingly.
# Python3 code to demonstrate working of # Odd elements indices# using loop   # initialize list test_list = [5, 6, 10, 4, 7, 1, 19]   # printing original list print("The original list is : " + str(test_list))   # Odd elements indices# using loop res = [] for idx, ele in enumerate(test_list):     if ele % 2 != 0:         res.append(idx)           # printing result print("Indices list Odd elements is : " + str(res)) 
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Odd elements is : [0, 4, 5, 6]

 
Method #2 : Using list comprehensionThis is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner.
# Python3 code to demonstrate working of # Odd elements indices# using list comprehension   # initialize list test_list = [5, 6, 10, 4, 7, 1, 19]   # printing original list print("The original list is : " + str(test_list))   # Odd elements indices# using list comprehension res = [idx for idx, ele in enumerate(test_list) if ele % 2 != 0]           # printing result print("Indices list Odd elements is : " + str(res)) 
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Odd elements is : [0, 4, 5, 6]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Can we define a method name same as class name in Java?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.
Live Demo
public class MethodNameTest {
   private String str = "Welcome to TutorialsPoint";
   public void MethodNameTest() { // Declared method name same as the class name
      System.out.println("Both method name and class name are the same");
   }
   public static void main(String args[]) {
      MethodNameTest test = new MethodNameTest();
      System.out.println(test.str);
      System.out.println(test.MethodNameTest());
   }
}
In the above example, we can declare a method name (MethodNameTest) same as the class name (MethodNameTest), it will be compiled successfully without any errors.
Welcome to TutorialsPoint
Both method name and class name are the same
Get last N elements from given list in Python

Given a Python list we want to find out only e e the last few elements.
The number of positions to be extracted is given. Based on that we design is slicing technique to slice elements from the end of the list by using a negative sign.
 Live Demo
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using list slicing
res = listA[-n:]
# print result
print("The last 4 elements of the list are : \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
The last 4 elements of the list are :
['Wed', 'Thu', 'Fri', 'Sat']
The islice function takes the number of positions as a parameter along with the reversed order of the list.
 Live Demo
from itertools import islice
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using reversed
res = list(islice(reversed(listA), 0, n))
res.reverse()
# print result
print("The last 4 elements of the list are : \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
The last 4 elements of the list are :
['Wed', 'Thu', 'Fri', 'Sat']
Python | Pandas DataFrame.columns

20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.columns attribute return the column labels of the given Dataframe.
Syntax: DataFrame.columns
Parameter : None
Returns : column names
Example #1: Use DataFrame.columns attribute to return the column labels of the given Dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],                   'Age':[14, 25, 55, 8, 21]})  # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.columns attribute to return the column labels of the given dataframe.
# return the column labelsresult = df.columns  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.columns attribute has successfully returned all of the column labels of the given dataframe. Example #2: Use DataFrame.columns attribute to return the column labels of the given Dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.columns attribute to return the column labels of the given dataframe.
# return the column labelsresult = df.columns  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.columns attribute has successfully returned all of the column labels of the given dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Scala Map count() method with example

13 Aug, 2019
The count() method is utilized to count pair of keys in the Map.
Method Definition: def count(p: ((A, B)) => Boolean): Int
Return Type: It returns the number of keys present in the map that satisfies the given predicate.
Example #1:
// Scala program of count()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 5)                  // Applying count method        val result = m1.count(z=>true)                  // Displays output        println(result)          }}
3

Example #2:
// Scala program of count()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map("geeks" -> 5, "for" -> 3, "geeks" -> 5)                  // Applying count method        val result = m1.count(z=>true)                  // Displays output        println(result)          }}
2

So, the identical keys are counted only once.
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binding rows and columns of a Data Frame in R – bind_rows() and bind_cols() Function

26 May, 2020
bind_rows() function in R Programming is used to combine rows of two data frames.
Syntax:bind_rows(data1, data2, id)
Parameter:id: dataframe identifierdata1, data2: data frame to combine
Example: Combining Rows
# R program to illustrate# combine rows  # Install dplyr packageinstall.packages("dplyr")    # Load dplyr package                   library("dplyr")                              # Create three data framesdata1 <- data.frame(x1 = 1:5,                                   x2 = letters[1:5])data2 <- data.frame(x1 = 0,                    x3 = 5:9)data3 <- data.frame(x3 = 5:9,                    x4 = letters[5:9])  # Apply bind_rows functionbind_rows(data1, data2, id = NULL)                      
Output:
    x1   x2  x3
 1   1    a  NA
 2   2    b  NA
 3   3    c  NA
 4   4    d  NA
 5   5    e  NA
 6   0    5
 7   0    6
 8   0    7
 9   0    8
 10  0    9

Here in the above code, we created 3 data frames data1, data2, data3 with rows and columns in it and then we use bind_rows() function to combine the rows that were present in the data frame. Also where the variable name is not listed bind_rows() inserted NA value.
bind_cols() function is used to combine columns of two data frames.
Syntax:bind_cols(data1, data2, id)
Parameter:id: dataframe identifierdata1, data2: data frame to combine
Example: Combining Columns
# R program to illustrate# combine rows  # Install dplyr packageinstall.packages("dplyr")    # Load dplyr package                   library("dplyr")                              # Create three data framesdata1 <- data.frame(x1 = 1:5,                                   x2 = letters[1:5])data2 <- data.frame(x1 = 0,                    x3 = 5:9)data3 <- data.frame(x3 = 5:9,                    x4 = letters[5:9])  # Apply bind_cols functionbind_cols(data1, data3, id = NULL)                      
Output:
   x1 x2 x3 x4
 1  1  a  5  e
 2  2  b  6  f
 3  3  c  7  g
 4  4  d  8  h
 5  5  e  9  i 
Here in the above code we have created 3 data frames and then combine their columns by using bind_cols() function.Here we have combined the var. x1, x2 of data1 and x3, x4 of data2 with each other.
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PrintWriter print(int) method in Java with Examples

31 Jan, 2019
The print(int) method of PrintWriter Class in Java is used to print the specified int value on the stream. This int value is taken as a parameter.
Syntax:
public void print(int intValue)
Parameters: This method accepts a mandatory parameter intValue which is the int value to be written on the stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of print(int) method:
Program 1:
// Java program to demonstrate// PrintWriter print(int) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintWriter instance            PrintWriter printr                = new PrintWriter(System.out);              // Print the int value '4'            // to this stream using print() method            // This will put the intValue in the            // stream till it is printed on the console            printr.print(4);              printr.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
4

Program 2:
// Java program to demonstrate// PrintWriter print(int) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintWriter instance            PrintWriter printr                = new PrintWriter(System.out);              // Print the int value '65'            // to this stream using print() method            // This will put the intValue in the            // stream till it is printed on the console            printr.print(65);              printr.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
65

Java-Functions
Java-IO package
Java-PrintWriter
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Calculate Standard Error in R

07 Sep, 2021
In this article, we are going to see how to calculate standard error in R Programming Language. 
Mathematically we can calculate standard error by using the formula:
standard deviation/squareroot(n)
Using sd() function with length function
By using the standard error formula.
Using plotrix package.
Here we are going to use sd() function which will calculate the standard deviation and then the length() function to find the total number of observation.
Syntax: sd(data)/sqrt(length((data)))
R
# consider a vector with 10 elementsa < - c(179, 160, 136, 227, 123, 23,        45, 67, 1, 234) # calculate standard errorprint(sd(a)/sqrt(length((a))))
Output:
[1] 26.20274
Here we will use the standard error formula for getting the observations.
Syntax: sqrt(sum((a-mean(a))^2/(length(a)-1)))/sqrt(length(a))
where
data is the input data
sqrt function is to find the square root
sum is used to find the sum of elements in the data
mean is the function used to find the mean of the data
length is the function used to return the length of the data
R
# consider a vector with 10 elementsa <- c(179, 160, 136, 227, 123, 23,       45, 67, 1, 234) # calculate standard errorprint(sqrt(sum((a - mean(a)) ^ 2/(length(a) - 1)))      /sqrt(length(a)))
Output:
[1] 26.20274
This is the built-in function that directly calculated the standard error. It is available in plotrix package 
Syntax: std.error(data)
R
# import plotrix packagelibrary("plotrix") # consider a vector with 10 elementsa <- c(179,160,136,227,123,       23,45,67,1,234) # calculate standard error using in built# functionprint(std.error(a))
Output:
[1] 26.20274
kk773572498
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Soroco India Interview Experience

04 Oct, 2021
Round 1: Coding Assessment
Maximum subarray sum
Sliding window maximum
Round 2: Video Call Interview
Coding round :
Find the kth largest element in a given array (using heaps)
List out the unique elements present in a string (use sets)
Round 3: video call interview
System Design Round + coding
Maximum subarray product( input can have negative numbers as well)
HLD for Whatsapp ( should know about communication protocols and web sockets )
Verdict: Rejected though I performed well in the two rounds didn’t do well in the system design round.
Marketing
Soroco
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C program to sort an array in an ascending order

Sort the given array in descending or ascending order based on the code that has been written.
An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its "index number".
The syntax for declaring an array is as follows −
datatype array_name [size];
For example,
float marks [50]
It declares ‘marks’ to be an array containing 50 float elements.
int number[10]
It declares the ‘number’ as an array to contain a maximum of 10 integer constants.
Each element is identified by using an "array index".
Accessing array elements is easy by using the array index.
The logic we use to sort the array elements in ascending order is as follows −
for (i = 0; i < n; ++i){
   for (j = i + 1; j < n; ++j){
      if (num[i] > num[j]){
         a = num[i];
         num[i] = num[j];
         num[j] = a;
      }
   }
}
Following is the C program to sort an array in an ascending order −
 Live Demo
#include <stdio.h>
void main (){
   int num[20];
   int i, j, a, n;
   printf("enter number of elements in an array\n");
   scanf("%d", &n);
   printf("Enter the elements\n");
   for (i = 0; i < n; ++i)
      scanf("%d", &num[i]);
   for (i = 0; i < n; ++i){
      for (j = i + 1; j < n; ++j){
         if (num[i] > num[j]){
            a = num[i];
            num[i] = num[j];
            num[j] = a;
         }
      }
   }
   printf("The numbers in ascending order is:\n");
   for (i = 0; i < n; ++i){
      printf("%d\n", num[i]);
   }
}
When the above program is executed, it produces the following result −
enter number of elements in an array
5
Enter the elements
12
23
89
11
22
The numbers in ascending order is:
11
12
22
23
89
Count and display vowels in a string in Python

Given a string of characters let's analyse how many of the characters are vowels.
We first find out all the individual and unique characters and then test if they are present in the string representing the vowels.
 Live Demo
stringA = "Tutorialspoint is best"
print("Given String: \n",stringA)
vowels = "AaEeIiOoUu"
# Get vowels
res = set([each for each in stringA if each in vowels])
print("The vlowels present in the string:\n ",res)
Running the above code gives us the following result −
Given String:
Tutorialspoint is best
The vlowels present in the string:
{'e', 'i', 'a', 'o', 'u'}
This function enables to extract the vowels form the string by treating it as a dictionary.
stringA = "Tutorialspoint is best"
#ignore cases
stringA = stringA.casefold()
vowels = "aeiou"
def vowel_count(string, vowels):

   # Take dictionary key as a vowel
   count = {}.fromkeys(vowels, 0)

   # To count the vowels
   for v in string:
      if v in count:
   # Increasing count for each occurence
      count[v] += 1
   return count
print("Given String: \n", stringA)
print ("The count of vlowels in the string:\n ",vowel_count(stringA, vowels))
Running the above code gives us the following result −
Given String:
tutorialspoint is best
The count of vlowels in the string:
{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}
How to update Python on Windows? - GeeksforGeeks

31 Aug, 2021
In this article, we are going to see how to update Python in the Windows system. For the sake of example, we will be upgrading from Python 3.6.8 to Python 3.9.6.
To check the current version of python on your system, use the following command in the command prompt:
python -V
This will show you your current python version as shown below:
Follow the below steps to update your python version:
Step 1: Go to Python’s official site.
Step 2: Click on the Downloads tab.
Here you will get a list of available releases.
Step 3: Download the version you need to upgrade to based on your system specifications(ie, 32-bit or 64-bit). Here we will be downloading the 64-bit installer for 3.9.6.
Step 4: Click on the installer and it will begin the installation. Make sure to select the “Add Python 3.9 to PATH” option. and click on “Install Now”.
This will start the installation as shown below:
After the installation is successful you will get the following message:
Now if you open up your cmd and use the below command:
python -V
You’ll see your version of Python has been updated to 3.9.6 as shown below:
Picked
python-basics
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
C++ Set Library - set() Function

The C++ constructor std::set::set() (Initializer-List Constructor) constructs a set container with the contents of the initializer list init
Following is the declaration for std::set::set() Initializer-list constructor from std::set header.
set (initializer_list<value_type> init,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());

set (initializer_list<value_type> init,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());
set (initializer_list<value_type> init,
     const allocator_type& alloc = allocator_type());
alloc − Input iterator to initial position.
alloc − Input iterator to initial position.
comp − comparison function object to use for all comparisons of keys
comp − comparison function object to use for all comparisons of keys
init − init is a initializer_list object which initializes the set container elements. Elements present in the set container are of value_type (Member Type)
init − init is a initializer_list object which initializes the set container elements. Elements present in the set container are of value_type (Member Type)
Constructor never returns any value.
This member function has no effect in case any exception is thrown.
N log(N) in general, where N = init.size();
else, linear in N, i.e., O(N) if init is already sorted.
The following example shows the usage of std::set::set() (initializer_list) constructor.
#include <iostream>
#include <set>
#include <string>

using namespace std;

int main() {
   // Initializer list constructor
   std::set<std::string> fruit {
      "orange", "apple", "mango", "peach", "grape"
   };

   std::cout << "Size of set container fruit is : " << fruit.size();
   return 0;
}
Let us compile and run the above program, this will produce the following result −
Size of set container fruit is : 5

 Print
 Add Notes
 Bookmark this page
Concatenate null to a string in Java

To concatenate null to a string, use the + operator.
Let’s say the following is our string.
String str = "Demo Text";
We will now see how to effortlessly concatenate null to string.
String strNULL = str + "null";
The following is the final example.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       String str = "Demo Text";
       System.out.println("String = "+str);
       String strNULL = str + "null";
       System.out.println("String concatenated with NULL: "+strNULL);
    }
}
String = Demo Text
String concatenated with NULL: Demo Textnull
Finding count of special characters in a string in JavaScript

Let’s say that we have a string that may contain any of the following characters.
'!', "," ,"\'" ,";" ,"\"", ".", "-" ,"?"
We are required to write a JavaScript function that takes in a string and count the number of
appearances of these characters in the string and return that count.
The code for this will be −
const str = "This, is a-sentence;.Is this a sentence?";
const countSpecial = str => {
   const punct = "!,\;\.-?";
   let count = 0;
   for(let i = 0; i < str.length; i++){
      if(!punct.includes(str[i])){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countSpecial(str));
The output in the console −
5
How to filter non-null value in Java?

Let’s say the following is our List with string elements:
List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL");
Now, create a stream and filter elements that end with a specific letter:
Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L"));
Now, use Objects::nonnull for non-null values:
List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());
The following is an example to filter non-null value in Java:
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL");
      Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L"));
      List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());
      System.out.println("League names ending with L = "+list);
   }
}
League names ending with L = [BBL, IPL, FPL, NFL]
Python - Uppercase Selective Substrings in String - GeeksforGeeks

30 Aug, 2020
Given a String, perform uppercase of particular Substrings from List.
Input : test_str = ‘geeksforgeeks is best for cs’, sub_list = [“best”, “geeksforgeeks”]Output : GEEKSFORGEEKS is BEST for csExplanation : geeksforgeeks and best uppercased.
Input : test_str = ‘geeksforgeeks is best for best’, sub_list = [“best”, “geeksforgeeks”]Output : GEEKSFORGEEKS is BEST for BESTExplanation : geeksforgeeks and best both occurrences uppercased.
Method #1 : Using split() + join() + loop
In this, we repeatedly split the string by substring and then perform join operation after joining the String with uppercased version of Substring. This is success only in cases of 1 occurrence of substring in String.
Python3
# Python3 code to demonstrate working of # Uppercase Selective Substrings in String# Using split() + join() + loop  # initializing stringstest_str = 'geeksforgeeks is best for cs'  # printing original stringprint("The original string is : " + str(test_str))  # initializing substringssub_list = ["best", "cs", "geeksforgeeks"]    for sub in sub_list:          # splitting string    temp = test_str.split(sub, -1)          # joining after uppercase    test_str = sub.upper().join(temp)    # printing result print("The String after uppercasing : " + str(test_str)) 
The original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS

Method #2 : Using re.sub() + upper()
This uses regex to solve this problem. In this, we use appropriate regex, and perform uppercase of found Strings.
Python3
# Python3 code to demonstrate working of # Uppercase Selective Substrings in String# Using re.sub() + upper()import re  # initializing stringstest_str = 'geeksforgeeks is best for cs'  # printing original stringprint("The original string is : " + str(test_str))  # initializing substringssub_list = ["best", "cs", "geeksforgeeks"]  # constructing regexreg = '|'.join(sub_list)res = re.sub(reg, lambda ele: ele.group(0).upper(), test_str)  # printing result print("The String after uppercasing : " + str(res)) 
The original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Split string into list of characters
MATLAB | Complement colors in a Grayscale Image - GeeksforGeeks

22 Oct, 2018
In MATLAB, a Grayscale image is a 2-D Image array ( M*N ) of color pixel. When we complement colors in a Grayscale image, Each color pixel in grayscale image is replaced with their complementary color pixel.
Dark areas become lighter and light areas become darker in the grayscale image as result of complement.
Complementing colors of a Grayscale Image Using MATLAB Library Function :
% read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg');  % complement colors of a Grayscale image % using imcomplement() functioncomp=imcomplement(img);  % Display Complemented grayscale Image imshow(comp);
 
Complementing colors of a Grayscale Image without Using MATLAB Library Function :
Grayscale Images have their pixel value in the range 0 to 255. we can complement a grayscale image by subtracting each pixel value from maximum possible pixel value a Grayscale image pixel can have (i.e 255 ), and the difference is used as the pixel value in the complemented Grayscale image.
It means if an image pixel have value 100 then, in complemented Grayscale image same pixel will have value ( 255 – 100 ) = 155.And if Grayscale image pixel have value 0 then, in complemented grayscale image same pixel will have value ( 255 – 0 ) = 255.Similarly, if Grayscale image pixel have value 255 then, in complemented grayscale image same pixel will have value ( 255 – 255 ) = 0.
Below is the Implementation of above idea:
% This function will take a Grayscale image as input% and will complement the colors in it.  function [complement] = complementGray(img)           % Determine the number of rows and columns    % in the Grayscale image array       [x, y]=size(img);         % create a array of same number rows and    % columns as original Grayscale image array    complement=zeros(x, y);          % loop to subtract 255 to each pixel.    for i=1:x        for j=1:y              complement(i, j) = 255-img(i, j);        end   endend  % Driver Code  % read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg');  % call complementGray() function to% complement colors in the Grayscale Imagecomp=complementGray(img);  % Display complemented Grayscale imageimshow(comp);
 
Alternatively –
Instead of using two loops to subtract 255 to each pixel of grayscale image. We can directly write it as comp = 255-image. Above code will subtract each value of image array from 255.
Below code will also complement a Grayscale Image:
% read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg');  % complement each pixel by subtracting it from 255.comp=255-img;  % Display Complemented Grayscale Image imshow(comp);
Input:
Output:
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
System Design Tutorial
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
Docker - COPY Instruction
p5.js Geometry() Method - GeeksforGeeks

21 May, 2021
p5.Geometry() method is used to represent 3d objects. It is returned by the loadModel() function and also used internally by the 3d primitive drawing functions. 
This function requires p5.dom library. So add the following line in the head section of the index.html file.
Javascript
<script language="javascript"     type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:
new p5.Geometry([detailX], [detailY], [callback])
Parameters: detailX and detailY takes the number of vertices on a horizontal surface, callback takes a function to call upon object instantiation. 
 
Available methods in p5.Geometry Class:
Sr.no.
Methods
Description
1.
computeFaces()
It used to compute the faces for geometry objects based on the vertices.
2.
computeNormals()
It used to compute the smooth normals per vertex as an average of each face.
3.
averageNormals()
It is used in curved surfaces to compute the average vertex normals.
4.
averagePoleNormals()
It is used in spherical primitives to compute the average pole normals.
5.
normalize()
It will modify all vertices to be centered within the range -100 to 100.
Example:
Javascript
function setup() {        // Create Canvas of given size     var cvs = createCanvas(400, 300);}    function draw() {        // Set the background color  background('pink');       // Creating rectangle at center of canvas  rectMode(CENTER);      // Initializing a rect geometry   geo = new p5.Geometry(    rect(200,150,190,120)  );      // Adding text to the geometry figure  text('GeeksforGeeks', 160, 150);}
In new p5.Geometry( rect(200,150,190,120)), 200 is used to specify the x-axis, 150 for the y-axis and 190 is the width of the rectangle and, 120 is the height of the rectangle.
Similarly, in text, 160 is the x-axis position and 150 is the y-axis position with respect to the canvas screen.
Output:
Reference : https://p5js.org/reference/#/p5.Geometry
JavaScript-p5.js
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to draw a pie chart using react bootstrap ? - GeeksforGeeks

02 Jul, 2021
A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. The area of slices of the pie represents the percentage of the parts of the data. 
Creating React Application And Installing Module:
Step 1: Create a React application using the following commandnpx create-react-app foldername
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2
npm install --save mdbreact react-chartjs-2
Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css';  
import 'bootstrap-css-only/css/bootstrap.min.css';  
import 'mdbreact/dist/css/mdb.css';
import '@fortawesome/fontawesome-free/css/all.min.css';  
import 'bootstrap-css-only/css/bootstrap.min.css';  
import 'mdbreact/dist/css/mdb.css';
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import { MDBContainer } from "mdbreact";import { Pie } from "react-chartjs-2";    const App = () => {      // Sample data  const data = {    labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],      datasets: [        {          label: "Hours Studied in Geeksforgeeks",          data: [2, 5, 6, 7, 3],          backgroundColor: ["blue", "green", "yellow", "pink", "orange"],        }      ]  }      return (    <MDBContainer>      <Pie data={data} />    </MDBContainer>  );}    export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
Picked
React-Bootstrap
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to redirect to another page in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS useNavigate() Hook
ReactJS defaultProps
Re-rendering Components in ReactJS
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
tmpnam() function in C - GeeksforGeeks

06 Sep, 2017
The tmpnam() function is a special function which is declared inside “stdio.h” header file. It generates a different temporary file name each time it is called up to at least TMP_MAX names. Here TMP_MAX represents maximum number of different file names that can be produce by tmpnam() function. If it is called more than TMP_MAX times, the behavior is implementation dependent.Here, L_tmpnam define the size needed for an array of char to hold the result of tmpnam.
Syntax :
char *tmpnam(char *str)
s : The character array to copy the file name.
It generates and returns a valid temporary 
filename which does not exist. 
If str is null then it simply returns the tmp file name.
// C program to generate random temporary file names.#include <stdio.h>int main(void){    // L_tmpnam declared in the stdio.h file.    // L_tmpnam define length of the generated file name.    char generate[L_tmpnam + 1]; // Add +1 for the null character.    tmpnam(generate);    puts(generate);    return 0;}
Output:
The file names are dependent on running machine, which can be anything.
Example: /tmp/fileRTOA0m
         \s260.
         \s3ok.
         \s5gg. etc

This article is contributed by Bishal Kumar Dubey. 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.
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Converting Strings to Numbers in C/C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
std::string class in C++
Different methods to reverse a string in C/C++
Enumeration (or enum) in C
Lodash _.mean() Method - GeeksforGeeks

09 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.mean() method is used to find the mean of the values in the array.
Syntax:
_.mean( array )
Parameters: This method accepts a single parameter as mentioned above and described below:
array: It is the array that the method iterates over to get the mean of all the values.
Return Value: This method returns the mean of the values in the array.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.mean()  // method let mean_val = _.mean([15, 7, 38, 46, 82]);         // Printing the output  console.log(mean_val);
Output:
37.6
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.mean()  // method let mean_val = _.mean([2, 3, 4, 6, 7, 8]);         // Printing the output  console.log(mean_val);
Output:
5
Example 3:  
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.mean()  // method let mean_val = _.mean([10, -4, -6, 8, 12]);         // Printing the output  console.log(mean_val);
Output:
4
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
GATE | GATE-CS-2004 | Question 32 - GeeksforGeeks

28 Jun, 2021
Consider the following program fragment for reversing the digits in a given integer to obtain a new integer. Let n = D1D2...Dm
int n, rev;rev = 0;while (n > 0){   rev = rev*10 + n%10;   n = n/10;}
The loop invariant condition at the end of the ith iteration is:(A) n = D1D2....Dm-i and rev = DmDm-1...Dm-i+1(B) n = Dm-i+1...Dm-1Dm and rev = Dm-1....D2D1(C) n != rev(D) n = D1D2....Dm and rev = DmDm-1...D2D1Answer: (A)Explanation: The loop one by adds digits to rev starting from the last digit of n. It also removes digits from n starting from left.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Java | Packages | Question 1 - GeeksforGeeks

28 Jun, 2021
Which of the following is/are true about packages in Java?
1) Every class is part of some package. 
2) All classes in a file are part of the same package. 
3) If no package is specified, the classes in the file 
   go into a special unnamed package 
4) If no package is specified, a new package is created with 
   folder name of class and the class is put in this package. 
(A) Only 1, 2 and 3(B) Only 1, 2 and 4(C) Only 4(D) Only 1 and 3Answer: (A)Explanation: In Java, a package can be considered as equivalent to C++ language’s namespace.Quiz of this Question
Java-Java Packages
Java-Packages
Java Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Constructors | Question 3
Java | Constructors | Question 5
Java | Exception Handling | Question 2
Java | final keyword | Question 1
Java | Class and Object | Question 1
Java | Abstract Class and Interface | Question 2
Java | Functions | Question 1
Java | Exception Handling | Question 3
Java | Exception Handling | Question 4
Java | Exception Handling | Question 7
How to use Meta Tag to redirect an HTML page?

Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection.
To use a META Tag to redirect your site is quite easy. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute.
The following is an example of redirecting current page to another page after 2 seconds. If you want to redirect page immediately then do not specify the content attribute.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Meta Tag</title>
      <meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" />
   </head>
   <body>
      <p>This is demo text.</p>
   </body>
</html>
Difference between TimeSpan Seconds() and TotalSeconds()

TimeSpan Seconds() is part of time, whereas TimeSpan TotalSeconds() converts entire time to seconds.
Let us first see the TimeSpan Seconds() method.
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0);
      // seconds
      Console.WriteLine(ts.Seconds);
   }
}
20
Now, let us see how TotalSeconds works for the same TimeSpan value.
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0);
      // total seconds
      Console.WriteLine(ts.TotalSeconds);
   }
}
360020
Now, we will see both of them in the same example.
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0);
      // seconds
      Console.WriteLine(ts.Seconds);
      // total seconds
      Console.WriteLine(ts.TotalSeconds);
   }
}
20
360020
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider the relation X(P, Q, R, S, T, U) with the following set of functional dependencies
F = {
       {P, R} → {S,T},  
       {P, S, U} → {Q, R}
    }
Which of the following is the trivial functional dependency in F+ is closure of F?
(A) {P,R}→{S,T}(B) {P,R}→{R,T}(C) {P,S}→{S}(D) {P,S,U}→{Q}Answer: (C)Explanation: A functional dependency X -> Y is trivial if Y is a subset of X.Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2004 | Question 3
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2019 | Question 27
What is stored procedure and how can we create MySQL stored procedures?

Stored procedure, in the context of regular computing language, may be defined as a subroutine like a subprogram that is stored in a database. In the context of MySQL, it is a segment of declarative SQL statements stored inside the database catalog. Before writing stored procedures in MySQL, we must have to check the version because MySQL 5 introduces stored procedure. Following is the syntax for creating a stored procedure −
CREATE [DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
proc_parameter: [ IN | OUT | INOUT ] param_name type
type:
Any valid MySQL data type
characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA
| MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
routine_body:
Valid SQL routine statement
Following is an example in which we created a simple procedure to get all the records from the table ‘student_info’ which have the following data −
mysql> select * from student_info;
+-----+---------+------------+------------+
| id  | Name    | Address    | Subject    |
+-----+---------+------------+------------+
| 100 | Aarav   | Delhi      | Computers  |
| 101 | YashPal | Amritsar   | History    |
| 105 | Gaurav  | Jaipur     | Literature |
| 110 | Rahul   | Chandigarh | History    |
+------+--------+------------+------------+
4 rows in set (0.00 sec)
Now, with the help of following queries we created the stored procedure named allrecords()
mysql> Delimiter //
mysql> Create Procedure allrecords()
    -> BEGIN
    -> Select * from Student_info;
    -> END//
Query OK, 0 rows affected (0.02 sec)
mysql> DELIMITER ;