code-rag-bench/online-tutorials huggingface dataset:
How to use CircularProgress Component in ReactJS? - GeeksforGeeks

22 Jan, 2021
As we know that progress indicators inform users about the status of ongoing processes such as loading an app, uploading data, etc. We can use CircularProgress Component in ReactJS to show this circular loading effect. Material UI for React has this component available for us and it is very easy to integrate. 
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
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, {useEffect, useState} from 'react';import CircularProgress from '@material-ui/core/CircularProgress';  const App = () => {    useEffect(()=> {    getDataFromAPI()  }, [])    const [isLoading, setIsLoading] = useState(true)    // Sample API to fetch Data  const getDataFromAPI = () => {    console.log("API called!!")    fetch('http://dummy.restapiexample.com/api/v1/employees')     .then((response) => {      return response.json()    }).then((res) => {      setTimeout(()=>{        setIsLoading(false)      }, 2000)    })  }    return (    <div style={{      marginLeft: '40%',    }}>      <h2>How to use CircularProgress Component in ReactJS?</h2>      {isLoading && <CircularProgress color="secondary" />}       {!isLoading && <h3>Successfully API Loaded Data</h3>}    </div>  );}  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:
This is how we can show the loading effect in ReactJS using the CircularProgress component.
JavaScript
ReactJS
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?
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 ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
HTML | canvas font Property - GeeksforGeeks

21 Jun, 2019
The HTML canvas font Property is used to change the present font family of the Text content of the <canvas> element. The font Property has a Default Property i.e 10px sans-serif
Syntax:
  context.font="italic small-caps bold 12px arial"; 
Property Values:
font-family: It is used to set the font type of an HTML element. It holds several font names as a fallback
font-style: It is used to specify the font style of an HTML element. It can be “normal, italic or oblique”.
font-weight: It is used to set the boldness of the font. Its value can be “normal, bold, lighter, bolder”.
font-variant: It is used to create the small-caps effect. It can be “normal or small-caps”.
font-size: It is used to set the font size of an HTML element. The font-size can be set in different ways like in “pixels, percentage, em or we can set values like small, large” etc.
caption: Use the font captioned controls (like buttons, drop-downs etc.)
icon: Use the font used to label icons.
menu: Use the font used in menus (drop-down menu and menu lists).
message-box: Use the font used in dialog boxes.
small-caption: Use the font used for labeling small controls
status-bar: Use the fonts used in window status bar.
Example:
<!DOCTYPE html><html>  <head>    <title>      HTML canvas font Property  </title></head>  <body style="text-align:center">      <h1 style="color:green">      GeeksForGeeks  </h1>    <h2 style="color:green">      HTML canvas font Property  </h2>    <canvas id="sudo"             width="300"            height="150"            style="border:2px solid">  </canvas>      <script>        var c = document.getElementById("sudo");        var ctx = c.getContext("2d");        ctx.font = "40px Arial";        ctx.fillText("GeeksForGeeks", 10, 50);    </script>  </body>  </html>
Output:
Supported Browsers: The browsers supported by HTML canvas font Property are listed below:
Google Chrome
Internet Explorer 9.0
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Property
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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 ?
Difference between var, let and const keywords in JavaScript
Python | Merge overlapping part of lists - GeeksforGeeks

05 Sep, 2019
Sometimes, while working with Python lists, we can have a problem in which we have to merge two list’s overlapping part. This kind of problem can come in day-day programming domain. Let’s discuss a way in which this problem can be solved.
Method : Using generator + next() + list slicingThis method can be employed to solve this task. In this, first, we iterate a variable from rear end of one of list, and get the slice of rear end of first list till match of initial slice of second list. Then, we get the first such overlapping( max overlap ) using next() and then we join the remaining part using list slicing.
# Python3 code to demonstrate working of# Merge overlapping parts of list# using generator + next() + list slicing  # initialize liststest_list1 = [4, 5, 7, 9, 10, 11]test_list2 = [10, 11, 16, 17]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Merge overlapping parts of list# using generator + next() + list slicingtemp = (i for i in range(len(test_list2), 0, -1) if test_list2[:i] == test_list1[-i:])temp2 = next(temp, 0)res = test_list1 + test_list2[temp2 : ]  # printing resultprint("List after overlapping merge is : " + str(res))
The original list 1 is : [4, 5, 7, 9, 10, 11]
The original list 2 is : [10, 11, 16, 17]
List after overlapping merge is : [4, 5, 7, 9, 10, 11, 16, 17]

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Lex Program to count number of words - GeeksforGeeks

30 Apr, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt.Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Prerequisite: Flex (Fast lexical Analyzer Generator)
Example:
Input: Hello everyone
Output: 2

Input: This is GeeksforGeeks
Output: 3

Note: The words can consist of lowercase characters, uppercase characters and digits.
Below is the implementation to count the number of words.
/*lex program to count number of words*/%{#include<stdio.h>#include<string.h>int i = 0;%}  /* Rules Section*/%%([a-zA-Z0-9])*    {i++;} /* Rule for counting                           number of words*/  "\n" {printf("%d\n", i); i = 0;}%%  int yywrap(void){}  int main(){       // The function that starts the analysis    yylex();      return 0;}
Output:
Lex program
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Association Rule
Recursive Functions
Activation Functions
Java Math min() method with Examples
Characteristics of Internet of Things
Software Engineering | Prototyping Model
OOPs | Object Oriented Design
Distributed Database System
Nested functions in C - GeeksforGeeks

05 Sep, 2017
Some programmer thinks that defining a function inside an another function is known as “nested function”. But the reality is that it is not a nested function, it is treated as lexical scoping. Lexical scoping is not valid in C because the compiler cant reach/find the correct memory location of the inner function.
Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it’s not a nested function.Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module. This is done so that lookup of global variables doesn’t have to go through the directory. As in C, there are two nested scopes: local and global (and beyond this, built-ins). Therefore, nested functions have only a limited use. If we try to approach nested function in C, then we will get compile time error.
// C program to illustrate the// concept of Nested function.#include <stdio.h>int main(void){    printf("Main");    int fun()    {        printf("fun");          // defining view() function inside fun() function.        int view()        {            printf("view");        }        return 1;    }    view();}
Output:
Compile time error: undefined reference to `view'

An extension of the GNU C Compiler allows the declarations of nested functions. The declarations of nested functions under GCC’s extension need to be prefix/start with the auto keyword.
// C program of nested function// with the help of gcc extension#include <stdio.h>int main(void){    auto int view(); // declare function with auto keyword    view(); // calling function    printf("Main\n");      int view()    {        printf("View\n");        return 1;    }      printf("GEEKS");    return 0;}
Output:
view
Main
GEEKS

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-Functions
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++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers 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++
fork() in C
Different methods to reverse a string in C/C++
Rotate tick labels for Seaborn barplot in Matplotib

To rotate tick labels for Seaborn barplot, we can take the following steps −
Make a dataframe using Pandas.
Make a dataframe using Pandas.
Plot the bar using Seaborn's barplot() method.
Plot the bar using Seaborn's barplot() method.
Rotate the xticks label by 45 angle.
Rotate the xticks label by 45 angle.
To display the figure, use the show() method.
To display the figure, use the show() method.
import pandas
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pandas.DataFrame({"X-Axis": [np.random.randint(10) for i in range(10)], "YAxis": [i for i in range(10)]})
bar_plot = sns.barplot(x='X-Axis', y='Y-Axis', data=df)
plt.xticks(rotation=45)
plt.show()
Chef - Ruby Gems with Recipes

Recipes are the key building blocks of cookbook which is basically Ruby code. It is possible to use all of the Ruby language features inside the Chef recipe. Most of the time Ruby build in functionality is enough but sometimes one might need to use additional Ruby gems. For example, if one needs to access MySQL database from the recipe itself.
Chef recipe has the capability to get the required Ruby gems in order to use them inside the very same recipe.
Step 1 − Edit the default recipe of the cookbook and install the gem to be used inside the recipe.
vipin@laptop:~/chef-repo $ subl 
cookbooks/my_cookbook/recipes/default.rb 
chef_gem 'ipaddress' 
require 'ipaddress' 
ip = IPAddress("192.168.0.1/24") 
Chef::Log.info("Netmask of #{ip}: #{ip.netmask}")
Step 2 − Upload the modified cookbook to the Chef server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook 
Uploading my_cookbook [0.1.0] 

Step 3 − Running Chef client to see the output.
user@server $ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-01-18T14:02:02+00:00] INFO: Netmask of 192.168.0.1: 
255.255.255.0 
...TRUNCATED OUTPUT...

Chef run steps consist of the compilation phase, where it compiles all the resources and an execution phase where Chef runs the resource providers to converge the node to the desired state. If one needs any particular Ruby gem inside the cookbook, one needs to install the gem during the complication phase.
The chef_gem resource will exactly do the same, and in Chef, Omnibus is the only way to work. Its main function is to make gems available to Chef itself.
 Print
 Add Notes
 Bookmark this page
Python - Import from sibling directory - GeeksforGeeks

30 Apr, 2021
In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree:
Directory Tree:

root :
 |
 |__SiblingA:
 |    \__A.py
 |     
 |__SiblingB:
 |      \__B.py
In B.py we will create a simple function and in A.py we will import the sibling module and call the function created in B.py. In order to import the sibling module in A.py wee need to specify the parent directory in A.py which can be done by using path.append() method in the sys module. Passing ‘..’ in append() method will append the path of the parent directory in A.py 
Code for A.py :
Python3
# import requi9red moduleimport sys  # append the path of the# parent directorysys.path.append("..")  # import method from sibling# modulefrom SiblingB.B import methodB  # call methods = methodB()print(s)
Code for B.py :
Python3
# defining method to import # in A.py which returns a stringdef methodB():    return "\n\nThis is methodB from SiblingB"
Output after execution of A.py :
A.py is executed and the methodB() is called.
Note: We cannot directly import the methodB from A.py as “from ..SiblingB.B import methodB” this will give an error stating that ImportError: attempted relative import with no known parent package. This is because python does not consider the current working directory as a package if __init__.py is not defined in it.
Another similar way of performing the same task is by making the sibling directories as a package by putting the __init__.py file in the folders and then importing it from the sibling directory. __init__.py can be made to import the required methods to the other modules. Below is the dictionary tree:
Directory Tree:

root :
 |
 |__SiblingA:
 |    \__A.py
 |     
 |__SiblingB:
 |      \_ __init__.py
 |      \__B.py
 |
Code for A.py :
Python3
# import requi9red moduleimport sys  # append the path of the# parent directorysys.path.append("..")  # import method from sibling # modulefrom SiblingB import methodB  # call methods = methodB()print(s)
Code for __init__.py :
Python3
# from .fileName import methodNamefrom .B import methodB
Code for B.py :
Python3
# defining method to import in # A.py which returns this stringdef methodB():    return "\n\nThis is methodB from SiblingB"
Output after execution of A.py :
NOTE: Once __init__.py is placed inside a folder this folder now acts as a package in python.
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How can we create a JSON using JsonGenerator in Java?

The JsonGenerator is a base class that defines public API for writing JSON content. The instances are created using factory methods of a JsonFactory instance. Once we can get the JsonGenerator from factory instance then use the writeStartObject() for writing starting marker of a JSON Object value, writeFieldName() method for writing a field name, writeString() method for outputting a String value, writeStartArray() method for writing starting marker of a Array value and writeEndObject() method for writing closing marker of a JSON Object value.
public abstract class JsonGenerator extends Object implements Closeable, Flushable, Versioned
import java.io.*;
import com.fasterxml.jackson.core.*;
public class JsonGeneratorTest {  
   public static void main(String args[]) throws IOException {
      JsonFactory factory = new JsonFactory();
      StringWriter jsonObjectWriter = new StringWriter();
      JsonGenerator generator = factory.createGenerator(jsonObjectWriter);
      generator.useDefaultPrettyPrinter(); // pretty print JSON
      generator.writeStartObject();
      generator.writeFieldName("empid");
      generator.writeString("120");
      generator.writeFieldName("firstName");
      generator.writeString("Ravi");
      generator.writeFieldName("lastName");
      generator.writeString("Chandra");
      generator.writeFieldName("technologies");
      generator.writeStartArray();
      generator.writeString("SAP");
      generator.writeString("Java");
      generator.writeString("Selenium");
      generator.writeEndArray();
      generator.writeEndObject();
      generator.close(); // to close the generator
      System.out.println(jsonObjectWriter.toString());
   }
}
{
   "empid" : "120",
   "firstName" : "Ravi",
   "lastName" : "Chandra",
   "technologies" : [ "SAP", "Java", "Selenium" ]
}
How to create Directories using the File utility methods in Java?

Since Java 7 the File.02s class was introduced this contains (static) methods that operate on files, directories, or other types of files.
The createDirectory() method of the Files class accepts the path of the required directory and creates a new directory.
Following Java example reads the path and name of the directory to be created, from the user, and creates it.
Live Demo
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Test {
   public static void main(String args[]) throws IOException {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String pathStr = sc.next()      
      System.out.println("Enter the name of the desired a directory: ");
      pathStr = pathStr+sc.next();      
      //Creating a path object
      Path path = Paths.get(pathStr);      
      //Creating a directory
      Files.createDirectory(path);      
      System.out.println("Directory created successfully");
   }
}
Enter the path to create a directory:
D:
Enter the name of the desired a directory:
sample_directory
Directory created successfully
If you verify, you can observe see the created directory as −
The createDirectories() method creates the given directory including the non-existing parent directory.
Live Demo
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Test {
   public static void main(String args[]) throws IOException {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String pathStr = sc.next();      
      System.out.println("Enter the name of the desired a directory: ");
      pathStr = pathStr+sc.next();      
      //Creating a path object
      Path path = Paths.get(pathStr);      
      //Creating a directory
      Files.createDirectories(path);      
      System.out.println("Directories created successfully");  
   }
}
Enter the path to create a directory:
D:
Enter the name of the desired a directory:
sample/test1/test2/test3/final_folder
Directory created successfully
If you verify, you can observe see the created directory as −
Difference between Memory and Storage - GeeksforGeeks

25 Mar, 2020
Memory:Memories are made up of registers. Memory refers to the location of short-term data. Each register in the memory is one storage location. Storage location is also called as memory location. Memory locations are identified using Address. The total number of bit a memory can store is its capacity.Memory are of three type:
1. Primary Memory
2. Secondary Memory
3. Cache Memory 
Storage:Storage allows you to store and access data on a long-term basis.Data remains the same and nothing changes in the hard disk drive: everything gets pulled off into the main memory. Storage allows you to access and store your applications, operating system and files for an indefinite period of time.For Example:
1. HDD
2. SDD
3. SD Cards
4. CD, DVD, etc 
Let’s see the difference between Memory and Storage:
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Redis - Set Sadd Command

Redis SADD command is used to add members to a set stored at the key. If the member already exists, then it is ignored. If the key does not exist, then a new set is created and the members are added into it. If the value stored at the key is not set, then an error is returned.
Integer reply, the number of elements that were added to the set, not including all the elements already present in the set.
Following is the basic syntax of Redis SADD command.
redis 127.0.0.1:6379> SADD KEY_NAME VALUE1..VALUEN

redis 127.0.0.1:6379> SADD myset "hello" 
(integer) 1 
redis 127.0.0.1:6379> SADD myset "foo" 
(integer) 1 
redis 127.0.0.1:6379> SADD myset "hello" 
(integer) 0 
redis 127.0.0.1:6379> SMEMBERS myset 
1) "hello" 
2) "foo"


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How do I modify a MySQL column to allow NULL?

For our example, let us create a table with NOT NULL constraint. After that, we will modify a column to allow NULL.
The following is the query to create a table with NOT NULL constraint.
mysql> create table AllowNullDemo
   -> (
   -> id int not null
   -> );
Query OK, 0 rows affected (0.48 sec)=
Insert records with the help of INSERT command. The query is as follows.
mysql> insert into AllowNullDemo values();
Query OK, 1 row affected, 1 warning (0.19 sec)

mysql> insert into AllowNullDemo values();
Query OK, 1 row affected, 1 warning (0.15 sec)
The query to display records.
mysql> select *from AllowNullDemo;
Here is the output. The value 0 is displayed, since we haven’t added any value while using INSERT command above.
+----+
| id |
+----+
|  0 |
|  0 |
+----+
2 rows in set (0.00 sec)

Here is the syntax to allow NULL value.
alter table yourTableName  modify column yourColumnName datatype;
Apply the above syntax to modify the column to allow NULL. The query is as follows.
mysql> alter table AllowNullDemo modify column id int;
Query OK, 0 rows affected (1.59 sec)
Records: 0  Duplicates: 0  Warnings: 0
After executing the above query, you can insert NULL value to that column because the column is modified successfully above.
mysql>  insert into AllowNullDemo values();
Query OK, 1 row affected (0.15 sec)
Display records to check whether the last value inserted is NULL or not.
mysql> select *from AllowNullDemo;
The following is the output wherein NULL value is visible now.
+------+
| id   |
+------+
|    0 |
|    0 |
| NULL |
+------+
3 rows in set (0.00 sec)

Using the above method, we can easily modify a MySQL column to allow NULL.
Perform search/replace for only the first occurrence of a character in MySQL table records?

You can achieve this with the help of CONCAT() along with REPLACE() function. To find the first occurrences you need to use INSTR() function.
The syntax is as follows −
UPDATE yourTableName
SET UserPost = CONCAT(REPLACE(LEFT(yourColumnName, INSTR(yourColumnName, 'k')), 'k', 'i'),
SUBSTRING(yourColumnName, INSTR(yourColumnName, 'k') + 1));
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table UserInformation
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(10),
   -> UserPost text
   -> );
Query OK, 0 rows affected (2.05 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into UserInformation(UserName,UserPost) values('Larry','Thks is a MySQL query');
Query OK, 1 row affected (0.16 sec)
mysql> insert into UserInformation(UserName,UserPost) values('Mike','Thks is not a java program');
Query OK, 1 row affected (0.31 sec)
mysql> insert into UserInformation(UserName,UserPost) values('Sam','Thks is a SQL syntax');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from UserInformation;
The following is the output −
+--------+----------+----------------------------+
| UserId | UserName | UserPost                   |
+--------+----------+----------------------------+
|      1 | Larry    | Thks is a MySQL query      |
|      2 | Mike     | Thks is not a java program |
|      3 | Sam      | Thks is a SQL syntax       |
+--------+----------+----------------------------+
3 rows in set (0.00 sec)
Here is the query to search/replace but only the first time a value appears in a record. Here, the first occurrence of ‘k’ is replaced with ‘i’ −
mysql> update UserInformation
   -> set UserPost=CONCAT(REPLACE(LEFT(UserPost, INSTR(UserPost, 'k')), 'k', 'i'),
   -> SUBSTRING(UserPost, INSTR(UserPost, 'k') + 1));
Query OK, 3 rows affected (0.16 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Display all records from the table once again. The query is as follows −
mysql> select *from UserInformation;
The following is the output displaying the first occurrence of ‘k’ replaced with ‘I’ −
+--------+----------+----------------------------+
| UserId | UserName | UserPost                   |
+--------+----------+----------------------------+
|      1 | Larry    | This is a MySQL query      |
|      2 | Mike     | This is not a java program |
|      3 | Sam      | This is a SQL syntax       |
+--------+----------+----------------------------+
3 rows in set (0.00 sec)
PHP - Function preg_match()

int preg_match (string pattern, string string [, array pattern_array], [, int $flags [, int $offset]]]);

The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
If the optional input parameter pattern_array is provided, then pattern_array will contain various sections of the subpatterns contained in the search pattern, if applicable.
If this flag is passed as PREG_OFFSET_CAPTURE, for every occurring match the appendant string offset will also be returned
Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.
Returns true if pattern exists, and false otherwise.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
   $line = "Vi is the greatest word processor ever created!";
   // perform a case-Insensitive search for the word "Vi"
   
   if (preg_match("/\bVi\b/i", $line, $match)) :
      print "Match found!";
      endif;
?>
This will produce the following result −
Match found!


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How do exceptions work in C++

In C++, Exception Handling is a process to handle runtime errors. Exception is an event which is thrown at runtime in C++. All exceptions are derived from std::exception class. It is a runtime error which can be handled. It prints exception message and terminates the program, if we don't handle the exception.
Exceptions are defined in C++ standard as <exception> class that we can use inside our programs. The arrangement of parent-child class hierarchy has been shown below −
Common exception classes in C++ are −
There are 3 keywords in exception handling: try, catch and throw.
In C++, exception handling is performed using try/catch statement. The code that may occur exception is used to place by Try block. Catch block is used to handle the exception.
#include <iostream>
using namespace std;
class Sample1 {
   public:
      Sample1() {
         cout << "Construct an Object of sample1" << endl;
      }
      ~Sample1() {
         cout << "Destruct an Object of sample1" << endl;
      }
};
class Sample2 {
   public:
      Sample2() {
         int i=7;
         cout << "Construct an Object of sample2" << endl;
         throw i;
      }
      ~Sample2() {
         cout << "Destruct an Object of sample2" << endl;
      }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
         cout << "Caught " << i << endl;
   }
}
Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7
We can define our own exceptions by inheriting and overriding exception class functionalities.
#include <iostream>
#include <exception> using namespace std;
struct DivideByZero : public exception {
   const char * what () const throw () {
      return "My Exception";
   }
};
int main() {
   try {
      throw DivideByZero();
   } catch(DivideByZero& e) {
      cout << "Exception caught" << endl; cout << e.what() << endl;
   } catch(exception& e) {
   }
}
Exception caught My Exception
what() = A public method provided by exception class and it has been overridden by all the child exception classes. It returns the cause of an exception.
Count of N-bit binary numbers without leading zeros - GeeksforGeeks

10 Mar, 2022
Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.Examples:  
Input: N = 2 Output: 2 10 and 11 are the only possible binary numbers.Input: N = 4 Output: 8  
 
Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now for the rest of the N – 1 bits, there are two choices they can either be set to 0 or 1. So, the count of possible numbers will be 2N – 1.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of possible numbersint count(int n){    return pow(2, n - 1);} // Driver codeint main(){    int n = 4;     cout << count(n);     return 0;}
// Java implementation of the approachclass GFG{         // Function to return the count    // of possible numbers    static int count(int n)    {        return (int)Math.pow(2, n - 1);    }         // Driver code    public static void main (String[] args)    {        int n = 4;             System.out.println(count(n));    }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the count# of possible numbersdef count(n):    return pow(2, n - 1) # Driver coden = 4 print(count(n)) # This code is contributed by mohit kumar
// C# implementation of the approachusing System;     class GFG{    // Function to return the count    // of possible numbers    static int count(int n)    {        return (int)Math.Pow(2, n - 1);    }         // Driver code    public static void Main (String[] args)    {        int n = 4;             Console.WriteLine(count(n));    }} // This code is contributed by 29AjayKumar
<script>  // JavaScript implementation of the approach // Function to return the count// of possible numbersfunction count(n){    return Math.pow(2, n - 1);} // Driver codevar n = 4;document.write(count(n));  </script>
8
 
Time Complexity: O(log n)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
29AjayKumar
rrrtnx
subham348
Numbers
Bit Magic
Mathematical
Mathematical
Bit Magic
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Highest power of 2 less than or equal to given number
Check for Integer Overflow
Swap bits in a given number
Write an Efficient Method to Check if a Number is Multiple of 3
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Convert MySQL null to 0?

Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0.
The syntax is as follows
SELECT IFNULL(yourColumnName,0) AS anyAliasName FROM yourTableName;
The second syntax is as follows:
SELECT COALESCE(yourColumnName,0) AS anyAliasName FROM yourTableName;
Let us first create a table. The query to create a table is as follows
mysql> create table convertNullToZeroDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> Salary int
   -> );
Query OK, 0 rows affected (1.28 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into convertNullToZeroDemo(Name,Salary) values('John',NULL);
Query OK, 1 row affected (0.20 sec)
mysql> insert into convertNullToZeroDemo(Name,Salary) values('Carol',5610);
Query OK, 1 row affected (0.10 sec)
mysql> insert into convertNullToZeroDemo(Name,Salary) values('Bob',NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into convertNullToZeroDemo(Name,Salary) values('David',NULL);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from convertNullToZeroDemo;
The following is the output
+----+-------+--------+
| Id | Name  | Salary |
+----+-------+--------+
| 1  | John  | NULL   |
| 2  | Carol | 5610   |
| 3  | Bob   | NULL   |
| 4  | David | NULL   |
+----+-------+--------+
4 rows in set (0.05 sec)
Here is your first query to convert MySQL NULL to 0
mysql> select IFNULL(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;
The following is the output
+--------------------+
| CONVERT_NULL _TO_0 |
+--------------------+
| 0                  |
| 5610               |
| 0                  |
| 0                  |
+--------------------+
4 rows in set (0.05 sec)
Here is your second query to convert MySQL NULL to 0
mysql> select coalesce(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;
The following is the output
+--------------------+
| CONVERT_NULL _TO_0 |
+--------------------+
| 0                  |
| 5610               |
| 0                  |
| 0                  |
+--------------------+
4 rows in set (0.00 sec)
C++ program to create a file - GeeksforGeeks

28 Sep, 2018
Problem Statement: Write a C++ program to create a file using file handling and check whether the file is created successfully or not. If a file is created successfully then it should print “File Created Successfully” otherwise should print some error message.
Approach: Declare a stream class file and open that text file in writing mode. If the file is not present then it creates a new text file. Now check if the file does not exist or not created then return false otherwise return true.
Below is the program to create a file:
// C++ implementation to create a file#include <bits/stdc++.h>using namespace std;  // Driver codeint main(){    // fstream is Stream class to both    // read and write from/to files.    // file is object of fstream class   fstream file;     // opening file "Gfg.txt"   // in out(write) mode   // ios::out Open for output operations.   file.open("Gfg.txt",ios::out);     // If no file is created, then   // show the error message.   if(!file)   {       cout<<"Error in creating file!!!";       return 0;   }     cout<<"File created successfully.";     // closing the file.   // The reason you need to call close()   // at the end of the loop is that trying   // to open a new file without closing the   // first file will fail.   file.close();     return 0;}
Output:
cpp-file-handling
File Handling
C++ Programs
File Handling
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Sorting a Map by value in C++ STL
delete keyword in C++
Passing a function as a parameter in C++
C++ program for hashing with chaining
cin in C++
Aptitude - Decimals & Fractions Online Quiz

Following quiz provides Multiple Choice Questions (MCQs) related to Decimals and Fractions. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - (0.92+0.32+0.12)/(0.092+0.032+0.012)=?
A - 100
B - 81
C - 99
D - 75
 (0.92+0.32+0.12)/(0.092+0.032+0.012) 
 = (0.92+0.32+0.12)/0.12(0.92+0.32+0.12) 
 = 1/0.12 = 100

Q 2 - 31.2 x 0.6 = 
A - 18.72
B - 18.85
C - 19.02
D - 19.08
 31.2 x 0.6=(312/10)x(6/10)=1872/100=18.72

Q 3 -  √(0.169/0.064)=?
A - 13/8
B - 19/8
C - 13/5
D - 1
√(0.169/0.064)=√((169/1000)/(64/1000))=√(169/64)=13/8

Q 4 - Find the value of 0.16 / (0.4/16). 
A - 6.4
B - 6.2
C - 0.4
D - 4.0
 0.16/ (0.4/16) =  0.16/(0.4/16)  =  (16/100)/(4/10) x16 = 16x16x10/100x4  = 6.4

Q 5 - 15.60 x 0.30 = ?
A - 4.68
B - 0.458
C - 0.468
D - 0.0468
 
 Number of decimal places in the product = 2 + 2 = 4. 
 1560 
  x30 
----- 
 0000 
4680x 
----- 
46800 
----- 
 ∴ 15.60 x 0.30 = 4.68 

Q 6 - if 6.06 x X = 1212/0.5. What is X?
A - 4.04
B - 400
C - 0.4
D - 0.44
 
 6.06 x X = 1212/0.5 
 => X = (1212 x 10)/(0.5 x 6.06) 
 = (1212 x 1000) / 3030 
 = 400 
 
Q 7 - b/a = 0.25. What is (2a-b)/(2a+b) + 2/9?
A - 4/9
B - 5/9
C - 1
D - 2
 
 (2a-b)/(2a+b) + 2/9 = (2-b/a)/(2+b/a) + 2/9 = (2-1/4)/(2+1/4) + 2/9 = 7/9 + 2/9 = (7+2)/9 = 9/9 = 1 

Q 8 - {(27.5 - 19.3)2 + (19.3 + 27.5)2} / (19.32 + 27.52)= ?
A - 4
B - 3
C - 2
D - 1
  
 Given expression can be expressed as {(a-b)2 + (a+b)2} / (a2 + b2) 
 where a = 27.5 and b = 19.3 
 = 2(a2 + b2)/(a2 + b2) = 2 

Q 9 - If (x - 0.11) / 1.6 = 1.6. What is x?
A - 2.56
B - 1.76
C - 2.67
D - 267
 
 (x - 0.11) / 1.6 = 1.6 
 => x = (1.6 x 1.6) + 0.11 =  2.56 + 0.11 
= 2.67 

Q 10 - If a student is asked to divide a number by 3, but he multiplied it by 3 and got 29.7. What should be the correct answer?
A - 3.1
B - 3.2
C - 3.3
D - 3.4
 
 3x = 29.7 => x =9.9. ∴ correct answer = 9.9 / 3 = 3.3.


    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
Java Examples - Set multiple classpath

How to set multiple classpath?
Following example demonstrates how to set multiple classpath. Multiple class paths are separated by a semicolon.
c:> java -classpath C:\java\MyClasse1;C:\java\MyClass2 
   utility.testapp.main

The above code sample will produce the following result.
Class path set.

 Print
 Add Notes
 Bookmark this page
Python | Pandas dataframe.cov()

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.cov() is used to compute pairwise covariance of columns.If some of the cells in a column contain NaN value, then it is ignored.
Syntax: DataFrame.cov(min_periods=None)
Parameters:min_periods : Minimum number of observations required per pair of columns to have a valid result.
Returns: y : DataFrame
Example #1: Use cov() function to find the covariance between the columns of the dataframe.
Note : Any non-numeric columns will be ignored.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                    "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                   "D":[5, 4, 2, 8]})  # Print the dataframedf
Output :
Now find the covariance among the columns of the data frame
# To find the covariance df.cov()
Output :
 
Example #2: Use cov() function to find the covariance between the columns of the dataframe which are having NaN value.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4],                   "B":[None, 2, 4, 3],                   "C":[4, 3, 8, 5],                    "D":[5, 4, 2, None]})  # To find the covariance df.cov()
Output :
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
Python OOPs Concepts
Python – Remove after substring in String

02 Sep, 2020
Given a String, remove all characters after particular substring.
Input : test_str = ‘geeksforgeeks is best for geeks’, sub_str = “for”Output : geeksforgeeks is best forExplanation : everything removed after for.
Input : test_str = ‘geeksforgeeks is best for geeks’, sub_str = “is”Output : geeksforgeeks isExplanation : everything removed after is.
Method #1 : Using index() + len() + slicing
In this, we first get the index of substring to perform removal after, add to that its length using len() and then slice off elements after that string using slicing.
Python3
# Python3 code to demonstrate working of # Remove after substring in String# Using index() + len() + slicing  # initializing stringstest_str = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing sub string sub_str = "best"  # slicing off after length computationres = test_str[:test_str.index(sub_str) + len(sub_str)]  # printing result print("The string after removal : " + str(res)) 
The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

Method #2 : Using regex() ( for stripping off after numeric occurrence)
This is solution to a slightly different problem in which the string removal is required after numeric occurrence. We employ match operation and it retains all before match is found.
Python3
# Python3 code to demonstrate working of # Remove after substring in String# Using regex() ( for stripping off after numeric occurrence)import re  # initializing stringstest_str = 'geeksforgeeks is best 4 geeks'  # printing original stringprint("The original string is : " + str(test_str))  # slicing after the numeric occurrenceres = re.match(r"(.*\d+)", test_str).group()  # printing result print("The string after removal : " + str(res)) 
The original string is : geeksforgeeks is best 4 geeks
The string after removal : geeksforgeeks is best 4

Python string-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
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
C# Program to Search Directories and List Files

01 Nov, 2021
Given files and directories, now our task is to search these files and directories using C#. So to do this task we use the following methods:
1. SearchOption: This method is used to specify whether to search the current directory or the current directory with all subdirectories.
Syntax:
public enum SearchOption
It will take two fields that is AllDirectories and TopDirectoryOnly. AllDirectories field is used to perform the search that contains the current directory and all its subdirectories in a search operation. And TopDirectoryOnly field is used to search only in the main directory.
2. GetFiles: This method is used to return the name of the files present in a particular directory or subdirectory. Or we can say that it returns the name along with the path of the files that are available in the given directory. 
Syntax:
public static string[] GetFiles (string path);
Where the path is the directory to search. This string is not case-sensitive. Here the path can be the relative or absolute path.
Approach
1. Read the directory and search in C drive A folder using searchoption AllDirectories keyword
list = Directory.GetFiles("C:\\A\\","*.*", SearchOption.AllDirectories)
2. Iterate through the list and display using foreach loop
foreach (string file in list)
{
    Console.WriteLine(file);
}
Example: 
In this example, we are displaying the list of file names along with their path by searching in the C drive – A directory.
C#
// C# program to search directories and list files using System;using System.IO;  class GFG{      static void Main(){          // Here we search the file present in C drive    // and A directory. Using SearchOption     string[] list = Directory.GetFiles("C:\\A\\", "*.*",                                        SearchOption.AllDirectories);                                             // Display the file names     // Present in the A directory     foreach (string file in list)    {        Console.WriteLine(file);    }}}
Output:
C:\A\file.txt
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.