code-rag-bench/online-tutorials huggingface dataset:
C++ Program to Check the Connectivity of Undirected Graph Using BFS

To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the undirected graph, we will select one node and traverse from it.
In this case the traversal algorithm is recursive BFS traversal.
Input − Adjacency matrix of a graph
Output − The Graph is connected.
Input − The start node s and the visited node to mark which node is visited.
Output − Traverse all connected vertices.
Begin
   mark s as visited
   insert s into a queue Q
   until the Q is not empty, do
   u = node that is taken out from the queue
   for each node v of the graph, do
      if the u and v are connected, then
         if u is not visited, then
            mark u as visited
            insert u into the queue Q.
      done
   done
End
Input − The graph.
Output − True if the graph is connected.
Begin
   define visited array
   for all vertices u in the graph, do
      make all nodes unvisited
      traverse(u, visited)
      if any unvisited node is still remaining, then
         return false
   done
   return true
End
 Live Demo
#include<iostream>
#include<queue>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
   {0, 1, 1, 0, 0},
   {1, 0, 1, 1, 0},
   {1, 1, 0, 1, 1},
   {0, 1, 1, 0, 1},
   {0, 0, 1, 1, 0}};
void traverse(int s, bool visited[]) {
   visited[s] = true; //mark v as visited
   queue<int> que;
   que.push(s);//insert s into queue
   while(!que.empty()) {
      int u = que.front(); //delete from queue and print
      que.pop();
      for(int i = 0; i < NODE; i++) {
         if(graph[i][u]) {
            //when the node is non-visited
            if(!visited[i]) {
               visited[i] = true;
               que.push(i);
            }
         }
      }
   }
}
bool isConnected() {
   bool *vis = new bool[NODE];
   //for all vertex u as start point, check whether all nodes are visible or not
   for(int u; u < NODE; u++) {
      for(int i = 0; i < NODE; i++)
         vis[i] = false; //initialize as no node is visited
         traverse(u, vis);
      for(int i = 0; i < NODE; i++) {
         if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
            return false;
      }
   }
   return true;
}
int main() {
   if(isConnected())
      cout << "The Graph is connected.";
   else
      cout << "The Graph is not connected.";
}
The Graph is connected.
Check if URL is valid or not in Java - GeeksforGeeks

30 May, 2018
Given a URL as string, we need to find if the given URL is valid or not.
Input : str = "https://www.geeksforgeeks.org/"
Output : Yes


Input : str = "https:// www.geeksforgeeks.org/"
Output : No
Note that there is a space after https://

Using java.net.urlWe can use java.net.url class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false.
// Java program to check if a URL is valid // using java.net.urlimport java.net.URL;  class Test {      /* Returns true if url is valid */    public static boolean isValid(String url)    {        /* Try creating a valid URL */        try {            new URL(url).toURI();            return true;        }                  // If there was an Exception        // while creating URL object        catch (Exception e) {            return false;        }    }          /*driver function*/        public static void main(String[] args)    {        String url1 = "https://www.geeksforgeeks.org/";        if (isValid(url1))             System.out.println("Yes");        else            System.out.println("No");                           String url2 = "http:// www.geeksforgeeks.org/";        if (isValid(url2))             System.out.println("Yes");        else            System.out.println("No");                    }}
Output:
Yes
No

This article is contributed by Pranav . 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.
java-regular-expression
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
Angular 8 - Backward Compatibility

Angular framework provides maximum compatibility with previous versions. If Angular Team deprecate a feature in a release, it will wait for 3 more release to completely remove the feature. Angular Team release a major version for every six months. Every version will have active maintenance period of six months and then Long Term Support (LTS) period for another one year. Angular does not introduce breaking changes during these 18 months. If Angular version deprecate a feature in version 5, then it will probably remove it in version 8 or in next releases.
Angular maintains documentation and guides of all version. For example, Angular documentation for version 7 can be checked @ https://v7.angular.io. Angular also provides a detailed upgrade path through https://update.angular.io/ site.
To update Angular application written from previous version, use below command inside the project directory:
ng update @angular/cli@8 @angular/core@8

Let us see some of the important changes introduced in Angular 8.
HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module.
HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module.
/deep/, >>> and :ng-deep component selectors are removed.
/deep/, >>> and :ng-deep component selectors are removed.
Angular default version of TypeScript is 3.4.
Angular default version of TypeScript is 3.4.
Node version supported by Angular is v10 and later.
Node version supported by Angular is v10 and later.
@ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static.
@ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static.
Lazy loading string syntax in router module is removed and only function based is supported.
loadChildren: './lazy/lazy.module#LazyModule' 
loadChildren: () => import('./lazy/lazy.module' 


    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Set up a standalone HBase local instance and connect to it with Python Happybase | by Andrea Guidi | Towards Data Science

Recently, in my starting adventure as a Data Science consultant, I was involved in a project where the database we are taking the data from is the famous Apache HBase.
HBase is a distributed, Hadoop non-relational database which is really powerful at handling massive amounts of data.
In the HBase data model, rows are identified by a row key which serves more or less an equivalent of the relational Primary Key and they are sorted by row key.
Columns are grouped in the so-called Column Families which are physical and logical grouping of columns, and the columns in one family are stored separately from the columns in another family so that queries can be performed only on the data you need.
You can read more about HBase here.
The reason why I decided to install an HBase local instance is that I must live with an endless curiosity and I love experimenting.
The first thing I did was to create a Linux Virtual Machine with Alpine Linux, mounted on VMWare. Once the VM was running, I logged into the installer by typing:
localhost login: rootsetup-alpine
I followed the shell instructions and finally, I rebooted the system. I needed Java support in order for HBase to work, so I installed openjdk8:
apk add openjdk8-jre
After that, I created a couple of folders inside /home, just for comfort:
cd homemkdir downloadsmkdir andreacd downloads
So now I am inside /home/downloads and I can download the HBase compressed folder, uncompress it and change directory:
wget https://www.apache.org/dyn/closer.lua/hbase/2.2.3/hbase-2.2.3-bin.tar.gztar xzvf hbase-2.2.3-bin.tar.gzcd hbase-2.2.3
Inside of this folder, there are two important folders: bin and conf.
I went inside conf:
And then modified the JAVA_HOME environment variable inside hbase_env.sh to /usr/lib/jvm/openjdk8-jre (folders might differ):
export JAVA_HOME=/usr/lib/jvm/openjdk8-jre
Also, I overwrote the content of the file hbase-site.xml with what reported here in Example 1 for Standalone HBase.
Then, I navigated up one folder back to Hbase main folder and changed to bin directory:
To check that HBase is working:
./start-hbase.sh./hbase shell
Et voilà!
To see the tables, type list:
Of course, there are no tables, but we can create one with the following convention:
create 'table_name','columnFamily1',...,'columnFamilyN'
In Shell:
And now let’s add two rows:
To retrieve the table, let’s run a Scan:
Now, the table is there and we can connect to it using Python package Happybase, built using Python Thrift.
First, stop the HBase instance and install Python 3 and Happybase package:
apk add python3pip install happybase
Then, start Thrift server:
And HBase again:
Now we open an Interactive Python session and make a connection to HBase to see that everything is working fine using Happybase APIs:
Thanks for reading, and reach me out for anything!
Java Program to Find the Cube Root of a Given Number Using Binary Search - GeeksforGeeks

03 Mar, 2021
Given a non-negative number find the cube root of a number using the binary search approach.
Examples :
Input: x = 27
Output: 3
Explanation:  The cube root of 16 is 4.

Input: x = 120
Output: 4
Explanation:  The cube root of 120 lies in between
4 and 5 so floor of the cube root is 4.
Naive Approach:
Check the cube of every element till n and store the answer till the cube is smaller or equal to the n
Java
// Java Program to Find the cube root// of given number using Naive approachimport java.io.*;class GFG {    static int cuberoot(int n)    {        int ans = 0;          for (int i = 1; i <= n; ++i) {            // checking every number cube            if (i * i * i <= n) {                ans = i;            }        }        return ans;    }    public static void main(String[] args)    {        // Number        int number = 27;        // Checking number        int cuberoot = cuberoot(number);        System.out.println(cuberoot);    }}
3

Complexity:
SpaceComplexity: O(1)
TimeComplexity: O(n)
Efficient Approach (Binary Search): 
Binary Search used Divide and Conquer approach that makes the complexity is O(log n).
Algorithm:
Initialize left=0 and right =n
Calculate mid=left+(right-left)/2
If mid*mid*mid is equal to the number  return the mid
If mid*mid*mid is less than the number store the mid in ans and increase left=mid+1
If mid*mid*mid is more than the number and decrease the right=mid-1
Return the answer
Implementation:
Java
// Java Program to Find the cube root// of given number using Binary Searchimport java.io.*;import java.util.*;class GFG {    // Function to find cuberoot    static int cuberoot(int number)    {        // Lower bound        int left = 1;        // Upper bound        int right = number;          int ans = 0;        while (left <= right) {            // Finding the mid value              int mid = left + (right - left) / 2;            // Checking the mid value            if (mid * mid * mid == number) {                return mid;            }              // Shift the lower bound            if (mid * mid * mid < number) {                left = mid + 1;                ans = mid;            }            // Shift the upper bound            else {                right = mid - 1;            }        }        // Return the ans        return ans;    }    public static void main(String[] args)    {        int number = 215;        System.out.println(cuberoot(number));    }}
5

Complexity:
SpaceComplexity: O(1)
TimeComplexity: O(log n)
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
Using mkvirtualenv to create new Virtual Environment - Python - GeeksforGeeks

08 Jun, 2020
Virtual Environment are used If you already have a python version installed and you want to use a different version for a project without bothering the older ones. it is good practice to use a new virtual environment for different projects.
There are multiple ways of creating that, today we will create one using mkvirtualenv  command.
virtualenvwrapper
To use the  mkvirtualenv command you need to have virtualenvwrapper installed which is nothing but a set of python extension commands.
Make sure you have pip installed.
$ sudo apt-get install python3-pip

Installing virtualenvwrapper 
$ sudo pip3 install virtualenvwrapper

Open bashrc by –
$ sudo gedit ~/.bashrc

After opening it, add the following  lines to it :
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

Save the bashrc file.
Using mkvirtualenv command
Now let us use it,
The syntax is :
$ mkvirtualenv venv_name

If you want to work on another version of python, try this :
$ mkvirtualenv -p python3.x venv_name
$(venv_name) // You will see something like this

Note: You can use any version in place of x. 
To work on an existing virtual environment,
$ workon venv_name

To get out of the virtual environment –
$(venv_name) deactivate

To see the list of your virtual environments are, go to-
Home/.virtualenvs
python-utility
Linux-Unix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python | Pandas DatetimeIndex.week - GeeksforGeeks

24 Dec, 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 DatetimeIndex.week attribute outputs the ordinal value of the week for each entries of the DatetimeIndex object. It is similar to the DatetimeIndex.week attribute.
Syntax: DatetimeIndex.week
Return: Index object
Example #1: Use DatetimeIndex.week attribute to find the ordinal value of the week for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'W' represents Weekly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='W',                            periods = 3, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find ordinal value of the week for each entries in the DatetimeIndex object.
# find the ordinal value of the week# for each entries present in the objectdidx.week 
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the weeks present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.week attribute to find the ordinal value of the week for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'M' represents monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M',                                periods = 5, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to find ordinal value of the week for each entries in the DatetimeIndex object.
# find the ordinal value of the week # for each entries present in the objectdidx.week
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the weeks present in each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

28 Jun, 2021
In a room there are only two types of people, namely Type 1 and Type 2. Type 1 people always tell the truth and Type 2 people always lie. You give a fair coin to a person in that room, without knowing which type he is from and tell him to toss it and hide the result from you till you ask for it. Upon asking, the person replies the following:
“The result of the toss is head if and only if I am telling the truth.” 
Which of the following options is correct?
(A) The result is head(B) The result is tail(C) If the person is of Type 2, then the result is tail(D) If the person is of Type 1, then the result is taiAnswer: (A)Explanation:
“The result of the toss is head if and only 
 if I am telling the truth.” 


If the person is of Type 1 who always tell truth, then result must be head.

If the person is of Type 2 who always tell lie, then result must be head.

Negation of a sentence of the form "X is true if and only if Y is true" is 
"Either X is true and Y is false, or X is false and Y is true."

Refer: http://math.stackexchange.com/questions/10435/negation-of-if-and-only-if

Which means "Either toss is head and I am not telling truth, or toss is tail
and I am telling truth".

Since the person always lie, it is "Either toss is head and I am not telling truth"

Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Extract all the URLs from the webpage Using Python - GeeksforGeeks

07 Jan, 2021
Scraping is a very essential skill for everyone to get data from any website. In this article, we are going to write Python scripts to extract all the URLs from the website or you can save it as a CSV file.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests:  Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import module
Make requests instance and pass into URL
Pass the requests into a Beautifulsoup() function
Use ‘a’ tag to find them all tag (‘a href ‘)
Example 1:
Python3
import requestsfrom bs4 import BeautifulSoup  url = 'https://www.geeksforgeeks.org/'reqs = requests.get(url)soup = BeautifulSoup(reqs.text, 'html.parser') urls = []for link in soup.find_all('a'):    print(link.get('href'))
Output:
Example 2:
Extracting URLs and save as CSV files.
Python3
import requestsfrom bs4 import BeautifulSoup urls = 'https://www.geeksforgeeks.org/'grab = requests.get(urls)soup = BeautifulSoup(grab.text, 'html.parser') # opening a file in write modef = open("test1.txt", "w")# traverse paragraphs from soupfor link in soup.find_all("a"):   data = link.get('href')   f.write(data)   f.write("\n") f.close()
Output:
 
skrg141
Python web-scraping-exercises
python-utility
Web-scraping
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Convert Lists of List to Dictionary - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python records, we can have problem in which we have data in form of Lists of list and we need to allocate certain elements as keys and certain as values to form a dictionary. This type of application can occur in data domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute way in which we perform this task. In this, we iterate through the lists forming key value pairs according to required slicing.
# Python3 code to demonstrate working of # Convert Lists of List to Dictionary# Using loop  # initializing listtest_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]  # printing original listprint("The original list is : " + str(test_list))  # Convert Lists of List to Dictionary# Using loopres = dict()for sub in test_list:    res[tuple(sub[:2])] = tuple(sub[2:])      # printing result print("The mapped Dictionary : " + str(res)) 
The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}
 
Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. This is similar to above method, just a one liner alternative.
# Python3 code to demonstrate working of # Convert Lists of List to Dictionary# Using dictionary comprehension  # initializing listtest_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]  # printing original listprint("The original list is : " + str(test_list))  # Convert Lists of List to Dictionary# Using dictionary comprehensionres = {tuple(sub[:2]): tuple(sub[2:]) for sub in test_list}      # printing result print("The mapped Dictionary : " + str(res)) 
The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
How to print without newline in Python?
Solve the Slide Puzzle with Hill Climbing Search Algorithm | by Rahul Aware | Towards Data Science

Hill climbing search algorithm is one of the simplest algorithms which falls under local search and optimization techniques. Here’s how it’s defined in ‘An Introduction to Machine Learning’ book by Miroslav Kubat:
Evaluation function at step 3 calculates the distance of the current state from the final state. So in case of 3x3 Slide Puzzle we have:
Final State: 1 2 34 5 6 7 8 Consider Current State: 1 2 3 4 5 6 7   8
Evaluation Function dF calculates the sum of the moves required for each tile to reach its final state. Since tiles 1 to 7 are already in its correct position, they don’t need to be moved. However, tile 8 is 1 move away from its final position.
dF(8) = m(1)+m(2)+m(3)+m(4)+m(5)+m(6)+m(7)+m(8)= 1
Hill climbing evaluates the possible next moves and picks the one which has the least distance. It also checks if the new state after the move was already observed. If true, then it skips the move and picks the next best move. As the vacant tile can only be filled by its neighbors, Hill climbing sometimes gets locked and couldn’t find any solution. It’s one of the major drawbacks of this algorithm.
Another drawback which is highly documented is local optima. The algorithm decides the next move(state) based on immediate distance(cost), assuming that the small improvement now is the best way to reach the final state. However, the path chosen may lead to higher cost(more steps) later.
Analogues to entering a valley after climbing a small hill.
In order to get around the local optima, I propose the usage of depth-first approach.
Idea is to traverse a path for a defined number of steps(depth) to confirm that it’s the best move.
Loop over all the possible next moves(states) for the current state.Call step 1 until depth d is reached. This generates a tree of height d.Pick the move(state) with minimum cost(dF)Return dF so that evaluation can be done at depth-1 level.
Loop over all the possible next moves(states) for the current state.
Call step 1 until depth d is reached. This generates a tree of height d.
Pick the move(state) with minimum cost(dF)
Return dF so that evaluation can be done at depth-1 level.
I observed that the depth-first approach improves the overall efficiency of reaching the final state. However, its memory intensive, proportional to the depth value used. This is because the system has to keep track of future states as per the depth used.
Here’s a brief comparison of the Distance by Moves charts for various depths:
A live evaluation can be performed here. Try out various depths and complexities and see the evaluation graphs. Sometimes, the puzzle remains unresolved due to lockdown(no new state).
Or, if you are just in the mood of solving the puzzle, try yourself against the bot powered by Hill Climbing Algorithm.
Hit the like button on this article every time you lose against the bot :-)
Have fun!
Edited: Live evaluation and bot currently don’t work on mobile devices.
Creating a table with a TIMESTAMP field in MySQL?

For this, you can use TIMESTAMP keyword in MySQL.
Let us create a table −
mysql> create table demo50
−> (
−> id int not null auto_increment primary key,
−> start_date timestamp default current_timestamp not null,
−> end_date timestamp default current_timestamp not null
−> );
Query OK, 0 rows affected (1.35 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo50 values();
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo50(end_date) values('2020−12−21');
Query OK, 1 row affected (0.07 sec)

mysql> insert into demo50(start_date) values('2020−01−01');
Query OK, 1 row affected (0.14 sec)
Display records from the table using select statement −
mysql> select *from demo50;
This will produce the following output −
+----+---------------------+---------------------+
| id | start_date          | end_date            |
+----+---------------------+---------------------+
|  1 | 2020−11−04 20:54:31 | 2020−11−04 20:54:31 |
|  2 | 2020−11−04 20:54:53 | 2020−12−21 00:00:00 |
|  3 | 2020−01−01 00:00:00 | 2020−11−04 20:55:04 |
+----+---------------------+---------------------+
3 rows in set (0.00 sec)
PHP Prime Number Program

Theory of Computation
A prime number is a whole number greater than 1 whose only factors are 1 and itself, like -2, 3, 5, 7, 11 etc. For example, 17 is a prime number because it is only divisible by 1 and 17. On the other hand, 18 is not a prime number because it is divisible by 2, 3, 6, 9 and the number itself. These are different ways to print prime number between 1 to 100 in the PHP programming language.
The following code prints a list of prime numbers between 1 and 100 (that is, numbers not divisible by something other than 1 or the number itself) using a while loop.
<?php  
	$limit = 100;
	$init = 2;
	
	while(TRUE)
	{
		$div = 2;
		if($init > $limit) 
		{
			break;
		}
		while(TRUE)
		{
			if($div > sqrt($init))
			{
				echo $init."  ";
				break;
			}
			if($init % $div == 0) 
			{
				break;
			}
			$div = $div + 1;
		}
		$init = $init + 1;
	}
?>

2  3  5  7  11  13  17  19  23  29  31  37  41  43  47  53  59  61  67  71  73  79  83  89  97
In the above code, we have two while loops. The inner while loop does the testing with each possible divisor. If the inner loop finds a divisor, the number is not prime, so it breaks out without printing anything, and if the testing gets as high as the square root of the number, we can assume that the number is prime. The outer loop works through all the numbers between 1 and 100. This loop is broken when we have reached the breaking point of numbers to test.
Here, we have created a function 'checkPrime()' to check whether the number is prime or not. We loop over the number range (1 to 100) and pass each as a parameter to the function to check whether a number is prime or not.
<?php
function checkPrime($num)
{
   if ($num == 1)
   return 0;
   for ($i = 2; $i <= $num/2; $i++)
   {
      if ($num % $i == 0)
      return 0;
   }
   return 1;
}

echo '<h2>Prime Numbers between 1 and 100</h2> ';
for($num = 1; $num <= 100; $num++) {
	$flag = checkPrime($num);
	if ($flag == 1) {
		echo $num." ";
	}	
}  
?>
Prime Numbers between 1 and 100 :

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Bootstrap alert-danger class

The alert-danger class in Bootstrap is used to set danger action.
You can try to run the following code to implement the alert-danger class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "alert alert-danger">This is danger action!</div>
   </body>
</html>
Style the active link with CSS

To style the active links, use the CSS :active selector. You can try to run the following code to style the active links
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         a:active {
            background-color: green;
         }
      </style>
   </head>
   <body>
      <a href = "https://qries.com">Welcome to Qries</a>
      <p>Click on the above link to see the effect.</p>
   </body>
</html>
C library function - cosh()

The C library function double cosh(double x) returns the hypebolic cosine of x.
Following is the declaration for cosh() function.
double cosh(double x)
x − This is the floating point value.
x − This is the floating point value.
This function returns hyperbolic cosine of x.
The following example shows the usage of cosh() function.
#include <stdio.h>
#include <math.h>

int main () {
   double x;

   x = 0.5;
   printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));

   x = 1.0;
   printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));

   x = 1.5;
   printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));

   return(0);
}
Let us compile and run the above program to produce the following result −
The hyperbolic cosine of 0.500000 is 1.127626
The hyperbolic cosine of 1.000000 is 1.543081
The hyperbolic cosine of 1.500000 is 2.352410


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Python String swapcase() Method

Python string  method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped.
Following is the syntax for swapcase() method −
str.swapcase();

NA
NA
This method returns a copy of the string in which all the case-based characters have had their case swapped.
The following example shows the usage of swapcase() method.
#!/usr/bin/python

str = "this is string example....wow!!!";
print str.swapcase()

str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.swapcase()
When we run above program, it produces following result −
THIS IS STRING EXAMPLE....WOW!!!
this is string example....wow!!!


    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
Logo - Repetition

We often repeat a sequence of commands. Computer programs often perform repetitive tasks. Just about every programming system has a way of carrying out this repetition, or iteration, as computer scientists call it. Let us consider the following example −
Let us assume we want to draw a square with sides of length 100, we can do this with the following program −
fd 100
rt 90
fd 100
rt 90
fd 100
rt 90
fd 100
rt 90

We note that the two commands – fd 100 and rt 90 are repeated four times. Will it not be simpler to tell the computer that it should just repeat these two commands four times instead of writing them four times in a row? We can do exactly this, using the following command −
It saves our time of typing-in to make a square. The general form is: repeat number [commands]. We must use the keyword – repeat followed by a number and then a sequence of commands in [square brackets].
Often, we might have to repeat within repeat. This is called nesting. Let us look at some examples on this.
Following is an exercise to check your aptitude on what you have learnt so far in this chapter.

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    38 Lectures 
     2.5 hours 

 Rob Cubbon

    81 Lectures 
     7.5 hours 

 YouAccel

    8 Lectures 
     34 mins

 Yash Rajoliya
 Print
 Add Notes
 Bookmark this page
Python program to find the second largest number in a list

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a list, we need to display the second largest number in a list.
There are three approaches to solve the problem−
 Live Demo
list1 = [11,22,1,2,5,67,21,32]
# to get unique elements
new_list = set(list1)
# removing the largest element from list1
new_list.remove(max(new_list))
# now computing the max element by built-in method?
print(max(new_list))
32
 Live Demo
list1 = [11,22,1,2,5,67,21,32]
# using built-in sort method
list1.sort()
# second last element
print("Second largest element in the list is:", list1[-2])
Second largest element in the list is: 32
 Live Demo
list1 = [11,22,1,2,5,67,21,32]
#assuming max_ is equal to maximum of element at 0th and 1st index
and secondmax is the minimum among them
max_=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
for i in range(2,len(list1)):
   # if found element is greater than max_
   if list1[i]>max_:
      secondmax=max_
      max_=list1[i]
   #if found element is greator than secondmax
   else:
      if list1[i]>secondmax:
         secondmax=list1[i]
print("Second highest number is the list is : ",str(secondmax))
Second highest number is the list is : 32
In this article, we have learned about how we can find the second largest element in a list.
MySQL Tryit Editor v1.0

SELECT * FROM Customers
WHERE Country='Mexico';
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How can we fetch all the records from a particular MySQL table?

We can fetch all the record from a MySQL table by using SELECT * from table_name; query. An example is as follows, fetched all the records from ‘Employee’ table −
mysql> Select * from Employee;
+------+--------+
| Id   | Name   |
+------+--------+
| 100  | Ram    |
| 200  | Gaurav |
| 300  | Mohan  |
+------+--------+
3 rows in set (0.00 sec)
Callable and Future in Java


java.util.concurrent.The callable object can return the computed result done by a thread in contrast to a runnable interface which can only run the thread. The Callable object returns a Future object which provides methods to monitor the progress of a task being executed by a thread. The future object can be used to check the status of a Callable and then retrieve the result from the Callable once the thread is done. It also provides timeout functionality.
//submit the callable using ThreadExecutor
//and get the result as a Future object
Future<Long> result10 = executor.submit(new FactorialService(10));  

//get the result using get method of the Future object
//get method waits till the thread execution and then return the result of the execution.
Long factorial10 = result10.get();
The following TestThread program shows usage of Futures and Callables in the thread based environment.
Live Demo
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException, ExecutionException {

      ExecutorService executor = Executors.newSingleThreadExecutor();

      System.out.println("Factorial Service called for 10!");
      Future<Long> result10 = executor.submit(new FactorialService(10));

      System.out.println("Factorial Service called for 20!");
      Future<Long> result20 = executor.submit(new FactorialService(20));

      Long factorial10 = result10.get();
      System.out.println("10! = " + factorial10);

      Long factorial20 = result20.get();
      System.out.println("20! = " + factorial20);

      executor.shutdown();
   }  

   static class FactorialService implements Callable<Long> {
      private int number;

      public FactorialService(int number) {
         this.number = number;
      }

      @Override
      public Long call() throws Exception {
         return factorial();
      }

      private Long factorial() throws InterruptedException {
         long result = 1;
                   
         while (number != 0) {              
            result = number * result;
            number--;
            Thread.sleep(100);          
         }
         return result;      
      }
   }
}
This will produce the following result.
Factorial Service called for 10!
Factorial Service called for 20!
10! = 3628800
20! = 2432902008176640000
Change tinyint default value to 1 in MySQL?

You can use DEFAULT command for this. Following is the syntax −
alter table yourTableName change yourColumnName yourColumnName TINYINT(1) DEFAULT 1 NOT NULL;
Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(20),
   UserAge int,
   isMarried tinyint(1)
);
Query OK, 0 rows affected (0.80 sec)
Let us check the description of table −
mysql> desc DemoTable;
This will produce the following output −
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| Id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserName  | varchar(20) | YES  |     | NULL    |                |
| UserAge   | int(11)     | YES  |     | NULL    |                |
| isMarried | tinyint(1)  | YES  |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
4 rows in set (0.21 sec)
Following is the query to change tinyint default value to 1 −
mysql> alter table DemoTable change isMarried isMarried TINYINT(1) DEFAULT 1 NOT NULL;
Query OK, 0 rows affected (1.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again. The default value of tinyint has been changed to 1 −
mysql> desc DemoTable;
This will produce the following output −
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| Id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserName  | varchar(20) | YES  |     | NULL    |                |
| UserAge   | int(11)     | YES  |     | NULL    |                |
| isMarried | tinyint(1)  | NO   |     | 1       |                |
+-----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
How to convert a JSON array to CSV in Java?

The JSON can be used as a data-interchange format and is lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can convert a JSON Array to CSV format using org.json.CDL class, it can provide a static method toString(), to convert a JSONArray into comma-delimited text. We need to import org.apache.commons.io.FileUtils package to store the data in a CSV file using the writeStringToFile() method.
public static java.lang.String toString(JSONArray ja) throws JSONException
In the below example, we can convert a JSON Array to CSV format.
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.*;
public class ConvertJsonToCSVTest {
   public static void main(String[] args) throws JSONException {
      String jsonArrayString = "{\"fileName\": [{\"first name\": \"Ravi\",\"last name\": \"Chandra\",\"location\": \"Bangalore\"}]}";
      JSONObject output;
      try {
         output = new JSONObject(jsonArrayString);
         JSONArray docs = output.getJSONArray("fileName");
         File file = new File("EmpDetails.csv");
         String csv = CDL.toString(docs);
         FileUtils.writeStringToFile(file, csv);
         System.out.println("Data has been Sucessfully Writeen to "+ file);
         System.out.println(csv);
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}
Data has been Sucessfully Writeen to EmpDetails.csv
last name,first name,location
Chandra,Ravi,Bangalore
SQL Query to Get Only Numbers From a String - GeeksforGeeks

25 Oct, 2021
As we know in an SQL database we can insert any type of data. Sometimes in the productions server, the data gets corrupted by two or more rows being merged and being saved in a column. In that case, we can extract the numeric part from that string and save it again. So in this article, we will learn how to extract numeric parts of a string in SQL. We will make use of Microsoft SQL as our server.
So let’s start by creating a database First.
Step 1: Create DB
Query:
CREATE DATABASE GFG
Step 2: Use this DB
Query:
USE GFG
Step 3: Create a table 
Create a table (GetNum) to store the data
Query:
CREATE TABLE GetNum(
 StudentName varchar (255)
)
 
Step 4: Insert some data into the database
Query:
 INSERT INTO GetNum (StudentName) VALUES ('Devesh123')
 
 INSERT INTO GetNum (StudentName) VALUES ('Geeks2')
 
 INSERT INTO GetNum (StudentName) VALUES ('For5')
 
 INSERT INTO GetNum (StudentName) VALUES ('Aman98')
Output:
Step 4: SQL query to extract the numbers
We will write a SQL function in order to not run the same query again and again for extracting the numbers, we can use that function multiple times also it will be stored in the database.
Query:
CREATE FUNCTION dbo.getNumericValue
 (
@inputString VARCHAR(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
  DECLARE @integerPart INT
  SET @integerPart = PATINDEX('%[^0-9]%', @inputString)
  BEGIN
    WHILE @integerPart > 0
    BEGIN
      SET @inputString = STUFF(@inputString, @integerPart, 1, '' )
      SET @integerPart = PATINDEX('%[^0-9]%', @inputString )
    END
  END
  RETURN ISNULL(@inputString,0)
END
GO
You can refer for more details for PATINDEX().
Step 5: Now run the created function to get the desired output.
Query:
SELECT dbo.getNumericValue(StudentName) from GetNum
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates