code-rag-bench/online-tutorials huggingface dataset:
React Native - ActivityIndicator

In this chapter we will show you how to use the activity indicator in React Native.
App component will be used to import and show our ActivityIndicator.
import React from 'react'
import ActivityIndicatorExample from './activity_indicator_example.js'

const Home = () => {
   return (
      <ActivityIndicatorExample />
   )
}
export default Home
Animating property is a Boolean which is used for showing the activity indicator. The latter closes six seconds after the component is mounted. This is done using the closeActivityIndicator() function.
import React, { Component } from 'react';
import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet } from 'react-native';

class ActivityIndicatorExample extends Component {
   state = { animating: true }
   
   closeActivityIndicator = () => setTimeout(() => this.setState({
   animating: false }), 60000)
   
   componentDidMount = () => this.closeActivityIndicator()
   render() {
      const animating = this.state.animating
      return (
         <View style = {styles.container}>
            <ActivityIndicator
               animating = {animating}
               color = '#bc2b78'
               size = "large"
               style = {styles.activityIndicator}/>
         </View>
      )
   }
}
export default ActivityIndicatorExample

const styles = StyleSheet.create ({
   container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      marginTop: 70
   },
   activityIndicator: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      height: 80
   }
})
When we run the app, we will see the loader on screen. It will disappear after six seconds.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Quick Code to Spruce Up Your Histograms & Scatterplots | by Jennifer McKaig | Towards Data Science

Simple graphs are essential visual tools for data analysis. If you are starting to learn how to make visualizations in Python, there are small adjustments to your graph parameters that will make them stand out. To get started, import the Pyplot and Seaborn libraries.
I. Choose Matplotlib colors that brighten up your graph.
II. Outline your histogram bins with a chosen edgecolor.
import seaborn as snsfrom matplotlib import pyplot as plt%matplotlib inlineplt.rcParams["patch.force_edgecolor"] = Trueplt.figure(figsize=(8,8)) #adjust the size of your graphsns.distplot(df["glucose"], bins= 20,color ='tomato',hist_kws=dict(edgecolor="k", linewidth=2)) #modify colors, number of bins, and linewidth for custom looks
III. Create a grid of subplots for a quick visual overview.
sns.set_style('darkgrid',{'axes.edgecolor': '.9'},)f, ax = plt.subplots(2,3,figsize = (16,7))plt.rcParams["patch.force_edgecolor"] = Truevis1 = sns.distplot(df["pregnancies"],bins=10,color='mediumturquoise',hist_kws=dict(edgecolor="magenta", linewidth=2.5),ax= ax[0][0])vis2 =sns.distplot(df["glucose"],bins=10,color='mediumturquoise', hist_kws=dict(edgecolor="magenta",linewidth=2.5),ax=ax[0][1])vis3 = sns.distplot(df["bloodpressure"],bins=10,color='mediumturquoise', hist_kws=dict(edgecolor="magenta", linewidth=2.5),ax=ax[0][2])vis4 = sns.distplot(df["skinthickness"],bins=10,color='mediumturquoise', hist_kws=dict(edgecolor="magenta", linewidth=2.5), ax=ax[1][0])vis5 =sns.distplot(df["insulin"],bins=10,color='mediumturquoise', hist_kws=dict(edgecolor="magenta", linewidth=2.5),ax=ax[1][1])vis6 =sns.distplot(df["bmi"],bins=10,color='mediumturquoise', hist_kws=dict(edgecolor="magenta", linewidth=2.5),ax=ax[1][2])
IV. Choose marker shapes, sizes, and colormaps to increase the readability of scatterplots and regression plots. Determine a “hue” variable input that will add clarity to each data point or use “size” in the same way.
plt.figure(figsize = (8,8))ax = sns.scatterplot(x = df.insulin, y = df.glucose, hue= df.bmi, size=df.bmi, sizes=(0,200), marker = ‘h’, palette=’plasma’, data=df)
plt.figure(figsize = (8,8))ax = sns.scatterplot(x = df.insulin, y = df.glucose, style=df.diabetes, hue=df.diabetes,palette= ‘husl’,markers=[‘D’,’*’],size= df.diabetes,sizes=(200,100), data=df)
Addition and Subtraction of Matrix using pthreads in C/C++

Here we will see how to perform the matrix addition and subtraction using multithreaded environment. The pthread is used to execute multiple threads simultaneously in C or C++.
There are two matrices A and B. Order of each matrix is (m x n). Each thread will take each row, and perform addition or subtraction. So for m rows, there are m different threads.
#include<iostream>
#include <pthread.h>
#include <cstdlib>
#include <cstdint>
#define CORE 3
#define MAX 3
using namespace std;
int AMat[MAX][MAX] = {{10, 20, 30},
   {40, 50, 60},
   {70, 80, 50}
};
int BMat[MAX][MAX] = {{80, 60, 20},
   {30, 20, 15},
   {10, 14, 35}
};
pthread_t thread[CORE * 2];
int add[MAX][MAX], sub[MAX][MAX];
void* addMatrices(void* arg) {
   intptr_t core = (intptr_t)arg;
   // Each thread computes 1/3rd of matrix addition
   for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) {
      for (int j = 0; j < MAX; j++) {
         add[i][j] = AMat[i][j] + BMat[i][j];
      }
   }
}
void* subtraction(void* arg) {
   intptr_t core = (intptr_t)arg;
   // Each thread computes 1/3rd of matrix subtraction
   for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) {
      for (int j = 0; j < MAX; j++) {
         sub[i][j] = AMat[i][j] - BMat[i][j];
      }
   }
}
void display(){
   cout << "Matrix A: " << endl;
   for(int i = 0; i < MAX; i++) {
      for(int j = 0; j < MAX; j++) {
         cout << AMat[i][j] << " ";
      }
      cout << endl;
   }
   cout << "\nMatrix B: " << endl;
   for(int i = 0; i < MAX; i++) {
      for(int j = 0; j < MAX; j++) {
         cout << BMat[i][j] << " ";
      }
      cout << endl;
   }
}
void displayRes(){
   cout << "\nAddition: " << endl;
   for(int i = 0; i < MAX; i++) {
      for(int j = 0; j < MAX; j++) {
         cout << add[i][j] << " ";
      }
      cout << endl;
   }
   cout << "\nSubtraction: " << endl;
   for(int i = 0; i < MAX; i++) {
      for(int j = 0; j < MAX; j++) {
         cout << sub[i][j] << " ";
      }
      cout << endl;
   }
}
main() {
   display();
   int step = 0;
   for (int i = 0; i < CORE; i++) {
      pthread_create(&thread[i], NULL, &addMatrices, (void*)step);
      pthread_create(&thread[i + CORE], NULL, &subtraction, (void*)step);
      step++;
   }
   for (int i = 0; i < CORE * 2; i++) {
      pthread_join(thread[i], NULL);
   }
   displayRes();
}
Matrix A:
10 20 30
40 50 60
70 80 50
Matrix B:
80 60 20
30 20 15
10 14 35
Addition:
90 80 50
70 70 75
80 94 85
Subtraction:
-70 -40 10
10 30 45
60 66 15
Replace characters in a string in Arduino

The .replace() function in Arduino allows you to replace a character or a substring with another character/substring in Arduino.
Note: This function replaces substrings in the original string itself, and does not return a new string containing the changes.
Examples are given in the code below −
void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   Serial.println(s1);
   s1.replace('e','a');
   Serial.println(s1);
   
   s1 = "Hello World";
   s1.replace("ll","gg");
   Serial.println(s1);

   s1 = "Hello World";
   s1.replace("li","gg");
   Serial.println(s1);
}
void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, in the last attempt, the string was unchanged. This is because the substring 'li' was not part of s1. Therefore, there was nothing to replace!
R - Binomial Distribution

The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. For example, tossing of a coin always gives a head or a tail. The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times is estimated during the binomial distribution.
R has four in-built functions to generate binomial distribution. They are described below.
dbinom(x, size, prob)
pbinom(x, size, prob)
qbinom(p, size, prob)
rbinom(n, size, prob)

Following is the description of the parameters used −
x is a vector of numbers.
x is a vector of numbers.
p is a vector of probabilities.
p is a vector of probabilities.
n is number of observations.
n is number of observations.
size is the number of trials.
size is the number of trials.
prob is the probability of success of each trial.
prob is the probability of success of each trial.
This function gives the probability density distribution at each point.
# Create a sample of 50 numbers which are incremented by 1.
x <- seq(0,50,by = 1)

# Create the binomial distribution.
y <- dbinom(x,50,0.5)

# Give the chart file a name.
png(file = "dbinom.png")

# Plot the graph for this sample.
plot(x,y)

# Save the file.
dev.off()
When we execute the above code, it produces the following result −
This function gives the cumulative probability of an event. It is a single value representing the probability.
# Probability of getting 26 or less heads from a 51 tosses of a coin.
x <- pbinom(26,51,0.5)

print(x)
When we execute the above code, it produces the following result −
[1] 0.610116

This function takes the probability value and gives a number whose cumulative value matches the probability value.
# How many heads will have a probability of 0.25 will come out when a coin
# is tossed 51 times.
x <- qbinom(0.25,51,1/2)

print(x)
When we execute the above code, it produces the following result −
[1] 23

This function generates required number of random values of given probability from a given sample.
# Find 8 random values from a sample of 150 with probability of 0.4.
x <- rbinom(8,150,.4)

print(x)
When we execute the above code, it produces the following result −
[1] 58 61 59 66 55 60 61 67


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
Dynamic Memory Allocation in C - GeeksQuiz

08 Aug, 2018
X: m=malloc(5); m= NULL;        1: using dangling pointers
Y: free(n); n->value=5;         2: using uninitialized pointers
Z: char *p; *p = ’a’;           3. lost memory is:
    free(p);
    p = NULL;

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021
HackWithInfy - A Coding Competition by Infosys
Python | Convert 1D list to 2D list of variable length - GeeksforGeeks

22 May, 2019
Given a 1D list ‘lst’ and list of variable lengths ‘var_lst’, write a Python program to convert the given 1D list to 2D list of given variable lengths.
Examples:
Input : lst = [1, 2, 3, 4, 5, 6]
        var_lst = [1, 2, 3]
Output : [[1], [2, 3], [4, 5, 6]]

Input : lst = ['a', 'b', 'c', 'd', 'e']
        var_lst = [3, 2]
Output : [['a', 'b', 'c'], ['d', 'e']]

 Method #1 : List slicing
# Python3 program to Convert 1D # list to 2D listfrom itertools import islice  def convert(lst, var_lst):    idx = 0    for var_len in var_lst:        yield lst[idx : idx + var_len]        idx += var_len      # Driver codelst = [1, 2, 3, 4, 5, 6]var_lst = [1, 2, 3]print(list(convert(lst, var_lst)))
[[1], [2, 3], [4, 5, 6]]

 Method #2 : Using itertools.islice()
# Python3 program to Convert 1D # list to 2D listfrom itertools import islice  def convert(lst, var_lst):    it = iter(lst)    return [list(islice(it, i)) for i in var_lst]      # Driver codelst = [1, 2, 3, 4, 5, 6]var_lst = [1, 2, 3]print(convert(lst, var_lst))
[[1], [2, 3], [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.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Python - Algorithm Types

The efficiency and accuracy of algorithms have to be analysed to compare them and  choose a specific algorithm for certain scenarios. The process of making this analysis is called Asymptotic analysis. It refers to computing the running time of any operation in mathematical units of computation.
For example, the running time of one operation is computed as f(n) and may be for another operation it is computed as g(n2). This means the first operation running time will increase linearly with the increase in n and the running time of the second operation will increase exponentially when n increases. Similarly, the running time of both operations will be nearly the same if n is significantly small.
Usually, the time required by an algorithm falls under three types −
Best Case − Minimum time required for program execution.
Best Case − Minimum time required for program execution.
Average Case − Average time required for program execution.
Average Case − Average time required for program execution.
Worst Case − Maximum time required for program execution.
Worst Case − Maximum time required for program execution.
The commonly used asymptotic notations to calculate the running time complexity of an algorithm.
Ο Notation
Ο Notation
Ω Notation
Ω Notation
θ Notation
θ Notation
The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete.
For example, for a function f(n)
Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }

The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of time an algorithm can possibly take to complete.
For example, for a function f(n)
Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }

The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time. It is represented as follows −
θ(f(n)) = { g(n) if and only if g(n) =  Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }

A list of some common asymptotic notations is mentioned below −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to enable MySQL Query Log?

To enable query log, use the command SET global. You cannot use set general_log in MySQL
version 8.0.12 version. If you are using version 8.0.12, then you will get the below given error.
Here, we are trying to set general_log to see what error will come −
mysql> SET general_log = 1;
The following is the output −
ERROR 1229 (HY000): Variable 'general_log' is a GLOBAL variable and should be set with SET GLOBAL

Now, we will use the global command with general_log. The query is as follows −
mysql> SET global general_log = 1;
Query OK, 0 rows affected (0.10 sec)
To check it is enabled or not, use the SHOW command −
mysql> SHOW variables like '%general_log%';

The following is the output −
+------------------+---------------------+
| Variable_name    | Value               |
+------------------+---------------------+
| general_log      | ON                  |
| general_log_file | DESKTOP-QN2RB3H.log |
+------------------+---------------------+
2 rows in set (0.03 sec)
From the above sample output, you can see that it got enabled by giving value 1.
We can disable it by giving the value 0. The following is the query to disable −
mysql> SET global general_log = 0;
Query OK, 0 rows affected (0.06 sec)
Now let us check the same using the following query −
mysql> SHOW variables like '%general_log%';

The following is the output −
+------------------+---------------------+
| Variable_name    | Value               |
+------------------+---------------------+
| general_log      | OFF                 |
| general_log_file | DESKTOP-QN2RB3H.log |
+------------------+---------------------+
2 rows in set (0.00 sec)
Python program to find the sum of all even and odd digits of an integer list

When it is required to find the sum of all even and odd digits of an integer list, a simple iteration and the ‘modulus’ operator are used.
Below is a demonstration of the same −
 Live Demo
my_list = [369, 793, 2848, 4314, 57467]

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

sum_odd = 0
sum_even = 0

for index in my_list:
   for element in str(index):

      if int(element) % 2 == 0:
         sum_even += int(element)
      else:
         sum_odd += int(element)

print("The result is :")
print("The sum of odd digits is :")
print(sum_odd)
print("The sum of odd digits is :")
print(sum_even)
The list is :
[369, 793, 2848, 4314, 57467]
The result is :
The sum of odd digits is :
54
The sum of odd digits is :
46
A list of integers is defined and is displayed on the console.
A list of integers is defined and is displayed on the console.
Two variables ‘sum_odd’ and ‘sum_even’ are declared.
Two variables ‘sum_odd’ and ‘sum_even’ are declared.
The list is iterated over, and the sum of odd digits and even digits are calculated.
The list is iterated over, and the sum of odd digits and even digits are calculated.
This is done by getting the modulus of the element with 2, and comparing it with 0.
This is done by getting the modulus of the element with 2, and comparing it with 0.
This is the output that is displayed on the console.
This is the output that is displayed on the console.
Groovy - parseInt()

This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two.
static int parseInt(String s)
  
static int parseInt(String s, int radix)

s − This is a string representation of decimal.
s − This is a string representation of decimal.
radix − This would be used to convert String s into integer.
radix − This would be used to convert String s into integer.
parseInt(String s) − This returns an integer (decimal only).
parseInt(String s) − This returns an integer (decimal only).
parseInt(int i) − This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
parseInt(int i) − This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) { 
      int x = Integer.parseInt("9");
      double y = Double.parseDouble("5");
      int z = Integer.parseInt("444",16);
		
      System.out.println(x);
      System.out.println(y);
      System.out.println(z);
   } 
} 
When we run the above program, we will get the following result −
9 
5.0 
1092


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Intersection of two arrays in Java

The intersection of the two arrays results in those elements that are contained in both of them. If an element is only in one of the arrays, it is not available in the intersection.  An example of this is given as follows −
Array 1 = 1 2 5 8 9
Array 2 = 2 4 5 9
Intersection = 2 5 9

A program that demonstrates the intersection of two sorted  arrays in Java is given as follows.
 Live Demo
public class Example {
   public static void main(String args[]) {
      int arr1[] = {2, 4, 6, 8, 9};
      int arr2[] = {1, 3, 4, 5, 6, 8, 9};
      int m = arr1.length;
      int n = arr2.length;
      int i = 0, j = 0;
      System.out.print("Array 1: ");
      for(int k = 0; k < m; k++) {
         System.out.print(arr1[k] + " "); 
      }
      System.out.print("\n");
      System.out.print("Array 2: ");
      for(int k = 0; k < n; k++) {
         System.out.print(arr2[k] + " ");
      }
      System.out.print("\n");
      System.out.print("Intersection of two arrays is: ");
      while (i < m && j < n) {
         if (arr1[i] < arr2[j])
            i++;
         else if (arr2[j] < arr1[i])
            j++;
         else {
            System.out.print(arr2[j++]+" ");
            i++; 
         }
      }
   }
}
The output of the above program is as follows.
Array 1: 2 4 6 8 9
Array 2: 1 3 4 5 6 8 9
Intersection of two arrays is: 4 6 8 9

Now let us understand the above program.
First, the values of the two arrays are printed. The code snippet that demonstrates this is given as follows.
System.out.print("Array 1: ");
for(int k = 0; k < m; k++) {
   System.out.print(arr1[k] + " ");
}
System.out.print("\n");
System.out.print("Array 2: ");
for(int k = 0; k < n; k++) {
   System.out.print(arr2[k] + " ");
}
Then the intersection of the two arrays i.e. their common elements are displayed using a while loop. The code snippet that demonstrates this is given as follows.
System.out.print("Intersection of two arrays is: ");
while (i < m && j < n) {
   if (arr1[i] < arr2[j])
      i++;
   else if (arr2[j] < arr1[i])
      j++;
   else {
      System.out.print(arr2[j++]+" ");
      i++;
   }
}
How to retrieve all nested fields from MongoDB collection?

For this, use aggregate(). Let us create a collection with documents −
>db.demo138.insertOne({"Id":101,"PlayerDetails":[{"PlayerName":"Chris","PlayerScore":400},{"PlayerName":"David","PlayerScore":1000}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31bb9ffdf09dd6d08539a1")
}
>db.demo138.insertOne({"Id":102,"PlayerDetails":[{"PlayerName":"Bob","PlayerScore":500},{"PlayerName":"Carol","PlayerScore":600}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31bbcefdf09dd6d08539a2")
}
Display all documents from a collection with the help of find() method −
> db.demo138.find();
This will produce the following output −
{
   "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "Id" : 101, "PlayerDetails" : [
      { "PlayerName" : "Chris", "PlayerScore" : 400 },
      { "PlayerName" : "David", "PlayerScore" : 1000 }
   ]
}
{
   "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "Id" : 102, "PlayerDetails" : [
      { "PlayerName" : "Bob", "PlayerScore" : 500 }, { "PlayerName" : "Carol", "PlayerScore" : 600 }
   ] 
}
Following is the query to retrieve all nested fields from the collection −
> db.demo138.aggregate([{ $unwind:"$PlayerDetails" }, { $project: { "PlayerName":"$PlayerDetails.PlayerName", "PlayerScore":"$PlayerDetails.PlayerScore" } } ] );
This will produce the following output −
{ "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName" : "Chris", "PlayerScore" : 400 }
{ "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName" : "David", "PlayerScore" : 1000 }
{ "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName" : "Bob", "PlayerScore" : 500 }
{ "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName" : "Carol", "PlayerScore" : 600 }
CSS overflow: visible

In the CSS overflow property with value visible, the overflow is not clipped. This is the default. You can try to run the following code to implement CSS overflow: visible property:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            background-color: orange;
            width: 250px;
            height: 30px;
            border: 2px solid blue;
            overflow: visible;
         }
      </style>
   </head>
   <body>
      <h1>Heading</h1>
      <div>Overflow property used here. This is a demo text to show the working of CSS overflow: visible.</div>
   </body>
</html>
Explain the purpose of render() in ReactJS - GeeksforGeeks

19 Sep, 2021
React.js library has two components:
Class components
Functional Components
Class components uses render function. The ReactDOM.render() function takes two arguments, HTML code and an HTML element.
Purpose of render():
React renders HTML to the web page by using a function called render().
The purpose of the function is to display the specified HTML code inside the specified HTML element.
In the render() method, we can read props and state and return our JSX code to the root component of our app.
In the render() method, we cannot change the state, and we cannot cause side effects( such as making an HTTP request to the webserver).
Let’s understand the render function with an example.
 
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Now write down the following code in the App.js file. 
App.js
import React, { Component } from 'react';export default class App extends Component {state = {    PawriDays: [        { id: '123s', Day: 'Monday' },        { id: '234r', Day: 'Saturday' },        { id: '12d5', Day: 'Sunday' }    ]}  render() {    const PartyDays = this.state.PawriDays.length    const style = {    'textAlign': 'center',    'color': 'green'    }      // Return JSX code    return (    <div style={style}>        <h1>I am User</h1>        <p> We party: {PartyDays} days a week </p>    </div>    );}}
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:
Blogathon-2021
Picked
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
Explain Key-events in JavaScript?

The key-events happen whenever a user interacts with keyboard. There are mainly three key event types − keydown, keypress and keyup.
Following is the code for key events in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Key-events in JavaScript</h1>
<div class="result"></div>
<h3>Press or release key to see the keyevent fired</h3>
<script>
   let resEle = document.querySelector(".result");
   document.body.addEventListener("keydown", () => {
      resEle.innerHTML = "keydown event is being fired <br>";
   });
   document.body.addEventListener("keyup", () => {
      resEle.innerHTML = "keyup event is being fired";
   });
   document.body.addEventListener("keypress", () => {
      resEle.innerHTML += "keypress event is being fired";
   });
</script>
</body>
</html>
On holding down the key −
On releasing the key −
Generate Random Point in a Circle in C++

Suppose we have the radius and x-y positions of the center of a circle, we have to write a function called randPoint() which generates a uniform random point in the circle. So there will be some important points that we have to keep in mind −
Input and output values are in floating-point.
Radius and x-y position of the center of the circle is passed into the class constructor.
A point on the circumference of the circle is considered to be in the circle.
The randPoint() returns x-position and y-position of the random point, in that order.
So if the input is like [10, 5,-7.5], then it may generate some random points like [11.15792,-8.54781],[2.49851,-16.27854],[11.16325,-12.45479].
To solve this, we will follow these steps −
Define a method called uniform(). This will work as follows −
return random_number/MAX RANDOM
Through the initializer initialize the rad, and center coordinate
The randPoint will work as follows −
theta = 2*Pi*uniform()
r := square root of uniform()
return a pair like (center_x + r*radius*cos(theta), center_y + r*radius*sin(theta))
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   const double PI = 3.14159265358979732384626433832795;
   double m_radius, m_x_center, m_y_center;
   double uniform() {
      return (double)rand() / RAND_MAX;
   }
   Solution(double radius, double x_center, double y_center) {
      srand(time(NULL));
      m_radius = radius; m_x_center = x_center; m_y_center = y_center;
   }
   vector<double> randPoint() {
      double theta = 2 * 3.14159265358979323846264 * uniform();
      double r = sqrt(uniform());
      return vector<double>{
         m_x_center + r * m_radius * cos(theta),
         m_y_center + r * m_radius * sin(theta)
      };
   }
};
main(){
   Solution ob(10, 5, 7);
   print_vector(ob.randPoint());
   print_vector(ob.randPoint());
   print_vector(ob.randPoint());
}
Pass 10, 5, 7 into constructor
Call randPoint() three times
[1.5441, 9.14912, ]
[-1.00029, 13.9072, ]
[10.2384, 6.49618, ]
How to animate a change in background color using jQuery on mouseover?

To change background color, use the mouseenter event. The background color change when you place mouse cursor:
mouseenter: function(){
   $(this).css("background-color", "gray");
}
The mouse cursor is placed on the following element:
<p class="my">Click and move the mouse pointer to change the background color.</p>
You can try to run the following code to learn how to animate a change in background color on mouseover:
 Live Demo
<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $("body").on({
            mouseenter: function(){
               $(this).css("background-color", "gray");
            },
   
            mouseleave: function(){
               $(this).css("background-color", "red");
            },
   
         });
      });
   </script>
</head>
<body>

   <p class="my">Click and move the mouse pointer to change the background color.</p>

</body>
</html>
Tryit Editor v3.7

Tryit: HTML address element
C# Program to Kill a Thread

Create a thread first and start it −
// new thread
Thread thread = new Thread(c.display);
thread.Start();
Now display the thread and set a stop function to stop the working of the thread −
public void display() {
   while (!flag) {
      Console.WriteLine("It's Working");
      Thread.Sleep(2000);
   }
}
public void Stop() {
   flag = true;
   }
}
The following is the complete code to learn how to kill a thread in C#.
Live Demo
using System;
using System.Threading.Tasks;
using System.Threading;
class Demo {    
   static void Main(string[] args){
      MyClass c = new MyClass();      
      // new thread      
      Thread thread = new Thread(c.display);      
      thread.Start();      
      Console.WriteLine("Press any key to exit!");      
      Console.ReadKey();      
      c.Stop();      
       thread.Join();    
   }
}
public class MyClass {    
   private bool flag = false;    
   public void display() {      
      while (!flag) {        
         Console.WriteLine("It's Working");    
         Thread.Sleep(2000);      
       }    .
   }    .
   public void Stop() {      
      flag = true;    
   }
}
It's Working
Press any key to exit!
VBA - Exit For

A Exit For statement is used when we want to exit the For Loop based on certain criteria. When Exit For is executed, the control jumps to the next statement immediately after the For Loop.
Following is the syntax for Exit For Statement in VBA.
 Exit For

The following example uses Exit For. If the value of the Counter reaches 4, the For Loop is exited and the control jumps to the next statement immediately after the For Loop.
Private Sub Constant_demo_Click()
   Dim a As Integer
   a = 10
   
   For i = 0 To a Step 2 'i is the counter variable and it is incremented by 2
      MsgBox ("The value is i is : " & i)
      If i = 4 Then
         i = i * 10 'This is executed only if i=4
         MsgBox ("The value is i is : " & i)
         Exit For 'Exited when i=4
      End If
   Next
End Sub
When the above code is executed, it prints the following output in a message Box.
The value is i is : 0

The value is i is : 2

The value is i is : 4

The value is i is : 40 


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How can we find the most recent and most oldest date from a table with the help of MySQL MAX() and MIN() functions?

For getting the most recent date from a table, we need to provide the name of the column, having a date as value, as the argument of MAX() function. Similarly, forgetting the oldest date from a table, we need to provide the name of a column, having a date as value, as the argument of MIN() function. To understand it, consider the following example of table ‘Collegedetail’, having the following details −
mysql> Select * from collegedetail;
+------+---------+------------+
| ID   | Country | estb       |
+------+---------+------------+
| 111  | INDIA   | 2010-05-01 |
| 130  | INDIA   | 1995-10-25 |
| 139  | USA     | 1994-09-25 |
| 1539 | UK      | 2001-07-23 |
| 1545 | Russia  | 2010-07-30 |
+------+---------+------------+
rows in set (0.00 sec)
Now, MIN() and MAX() function can be used to retrieve the oldest college and newest college respectively from the above table, as follows −
mysql> Select MIN(estb), MAX(estb) from collegedetail;
+------------+------------+
| MIN(estb)  | MAX(estb)  |
+------------+------------+
| 1994-09-25 | 2010-07-30 |
+------------+------------+
1 row in set (0.19 sec)
How to Install psycopg2 Binary Module in Python ? - GeeksforGeeks

05 Oct, 2021
psycopg2 is the most popular PostgreSQL database adapter for the Python programming language. It is a DB API 2.0 compliant PostgressSQL driver that is actively developed. It is designed for heavily multi-threaded applications that create and destroy lots of cursors and create a large number of “INSERTs” or “UPDATEs”.
To install this module follow the below steps.
Step 1: First of all check whether Python is installed or not in your system. Do it by simply printing its version. Open the command prompt and run the command given below:
python --version
If python is not installed in your system, then you can install it running the given command in your command prompt.
pip install python
Step 2: Open the command prompt and run the below command to install psycopg2-binary. If it shows successfully installed then you are good to go.
pip install psycopg2-binary
Step 3: Check if it is working or not. Do it simply by importing psycopg2 library and checking its version. Open the command prompt and put the command given below. Showing no error means our package is successfully installed.
python -c "import psycopg2; print(psycopg2.__version__)"
how-to-install
Picked
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
PyQt5 – How to add an item to the ComboBox ?

22 Apr, 2020
In this article we will see how we can add item to the combo box. By default the combo box has no items in order to add items to the combo box we use addItem method. Combo box will then allow us to choose from the added items.
Syntax : combo_box.addItem(item)
Argument : It takes string as argument
Action performed : It will add the item to the drop down list of combo box
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        combo_box = QComboBox(self)          # setting geometry of combo box        combo_box.setGeometry(200, 150, 120, 40)          # adding items to combo box        # adding Geek to the combobox        combo_box.addItem("Geek")        # adding Super Geek to the combobox        combo_box.addItem("Super Geek")        # adding Ultra Geek to the combobox        combo_box.addItem("Ultra Geek")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
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
Python OOPs Concepts
C# String.Contains() Method

The String.Contains() method in C# is used to return a value indicating whether a specified substring occurs within this string.
public bool Contains (string val);
Above, val is the string to search for.
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Akon";
      string str2 = "Ak";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("String 2 = "+str2);
      Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());
      Console.WriteLine("String 1 is equal to String 2: {0}", str1.Equals(str2));
      Console.WriteLine("Does String 1 has String 2 = "+str1.Contains(str2));
   }
}
String 1 = Akon
HashCode of String 1 = 416613838
String 2 = Ak
HashCode of String 2 = -839927841
String 1 is equal to String 2: False
Does String 1 has String 2 = True
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Jacob";
      string str2 = "John";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("String 2 = "+str2);
      Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());
      bool res = str1.Contains(str2);
      if (res)
         Console.WriteLine("Found!");
      else
         Console.WriteLine("Not found!");
   }
}
String 1 = Jacob
HashCode of String 1 = -790718923
String 2 = John
HashCode of String 2 = -1505962600
Not found!
Inline media query in React components

21 Feb, 2022
Generally, one can not do inline styling with media queries because React doesn’t allow us to use media queries in inline styling. We can use radium which is a third-party package that enables media queries for inline styling.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Step 3: Now create a new component Example.js in your src folder that will return the GeeksforGeeks text.
Step 4: Now go to the app.js file in your editor and edit it, so that it returns a component example(an example).
Step 5: Now install the Radium module from the root of your my-app using the command. 
$ npm install --save radium
Step 6: Import radium with { styleroot } from react in both app.js and example.js.
Step 7: Finally we can use media queries in our react component example.js. In this example, we have added a query if the width of the device is less than 501px then our app will display nothing.
Note: One thing we have to keep in mind that the syntax will be slightly different like we have to wrap everything which we are returning in styleroot.
Filename-App.js:
Javascript
import React, { Component } from 'react'import Radium, { StyleRoot } from 'radium'; // Importing our Example component(src folder)import Example from './Example' class App extends Component {  render() {    return (       // Wrapping in styleroot      <StyleRoot>        <div className="App">          <Example />        </div>      </StyleRoot>    )  }} export default Radium(App);
Filename-Example.js: Our Component
Javascript
import React, { Component } from 'react'import Radium, { StyleRoot } from 'radium';class App extends Component {  render() {    const style = {       // Adding media query..      '@media (max-width: 500px)': {        display: 'none',      },    };    return (       // Wrapping under styleroot.      <StyleRoot>        <div className="App">          <h1 style={style}>GeeksforGeeks</h1>        </div>      </StyleRoot>    )  }} export default Radium(App);
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: You will see the following output on your browser screen:
Now inspect the window and decrease the width up to 501px, the GeeksforGeeks will not be visible now, this is how you can use media queries inline in the React app.
sumitgumber28
Technical Scripter 2020
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Importance of wait(), notify() and notifyAll() methods in Java?

The threads can communicate with each other through wait(), notify() and notifyAll() methods in Java. These are final methods defined in the Object class and can be called only from within a synchronized context. The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting on that object’s monitor. The notifyAll() method wakes up all threads that are waiting on that object’s monitor. A thread waits on an object’s monitor by calling one of the wait() method. These methods can throw IllegalMonitorStateException if the current thread is not the owner of the object’s monitor.
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()

public class WaitNotifyTest {
   private static final long SLEEP_INTERVAL = 3000;
   private boolean running = true;
   private Thread thread;
   public void start() {
      print("Inside start() method");
      thread = new Thread(new Runnable() {
         @Override
         public void run() {
            print("Inside run() method");
            try {
               Thread.sleep(SLEEP_INTERVAL);
            } catch(InterruptedException e) {
               Thread.currentThread().interrupt();
            }
            synchronized(WaitNotifyTest.this) {
               running = false;
               WaitNotifyTest.this.notify();
            }
         }
      });
      thread.start();
   }
   public void join() throws InterruptedException {
      print("Inside join() method");
      synchronized(this) {
         while(running) {
            print("Waiting for the peer thread to finish.");
            wait(); //waiting, not running
         }
         print("Peer thread finished.");
      }
   }
   private void print(String s) {
      System.out.println(s);
   }
   public static void main(String[] args) throws InterruptedException {
      WaitNotifyTest test = new WaitNotifyTest();
      test.start();
      test.join();
   }
}
Inside start() method
Inside join() method
Waiting for the peer thread to finish.
Inside run() method
Peer thread finished.
Python | Group list elements based on frequency

25 Jun, 2019
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple.
Examples:
Input : [1, 3, 4, 4, 1, 5, 3, 1]
Output : [(1, 3), (3, 2), (4, 2), (5, 1)]

Input : ['x', 'a', 'x', 'y', 'a', 'x']
Output : [('x', 3), ('a', 2), ('y', 1)]

Method #1 : List comprehension
We can use list comprehension to form tuples of each element and the count of its occurrence and store it in ‘res’, but that will contain the duplicate first element. Thus, to remove the duplicate first element, we use OrderedDict(res).items().
# Python3 program to Grouping list # elements based on frequencyfrom collections import OrderedDict   def group_list(lst):          res =  [(el, lst.count(el)) for el in lst]    return list(OrderedDict(res).items())      # Driver codelst = [1, 3, 4, 4, 1, 5, 3, 1]print(group_list(lst))
[(1, 3), (3, 2), (4, 2), (5, 1)]

 Method #2 : Using collections.Counter()
collections.Counter() provides two direct methods keys() and values() that provides the elements and its occurrences. At last, zip them together using Python zip() method.
# Python3 program to Grouping list # elements based on frequencyfrom collections import Counter  def group_list(lst):          return list(zip(Counter(lst).keys(), Counter(lst).values()))      # Driver codelst = [1, 3, 4, 4, 1, 5, 3, 1]print(group_list(lst))
[(1, 3), (3, 2), (4, 2), (5, 1)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
\mathring - Tex Command

\mathring - Used to draw mathring symbol over the argument.
{ \mathring #1}
\mathring command is used to draw mathring symbol over the argument.