code-rag-bench/online-tutorials huggingface dataset:
Convert the given numbers into words in Pl/SQL

12 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a number and task is to convert each digit of the number into words.Examples:
Input: 47856
Output: Four Seven Eight Five Six

Input: 123456
Output: one two three four five six

Approach is to select the corresponding word of a particular number using decode function.Below is the required implementation:
DECLARE       -- declare variable are num, num_to_word, str, len, c     -- and in above declare variable num, len, c are integer datatype      -- and num_to_word and str are varchar datatype     num         INTEGER;     num_to_word VARCHAR2(100);     str         VARCHAR2(100);     len         INTEGER;     c           INTEGER; BEGIN     num := 123456;       len := Length(num);       dbms_output.Put_line('Entered Number is: '                          ||num);       FOR i IN 1..len LOOP         c := Substr(num, i, 1);           SELECT Decode(c, 0, 'Zero ',                          1, 'One ',                          2, 'Two ',                          3, 'Three ',                          4, 'Four ',                          5, 'Five ',                          6, 'Six ',                          7, 'Seven ',                          8, 'Eight ',                          9, 'Nine ')         INTO   str         FROM   dual;           num_to_word := num_to_word                        ||str;     END LOOP;       dbms_output.Put_line('Number to words: '                          ||num_to_word); END;   -- Program End 
Output :
Entered Number is: 123456
Number to words: One Two Three Four Five Six 

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter in Python

We sometimes arrive at a situation where we have two lists and we want to check whether each item from the smaller list is present in the bigger list or not. In such case we use the filter() function as discussed below.
Filter(function_name, sequence name)
Here Function_name is the name of the function which has the filter criteria. Sequence name is the sequence which has elements that needs to be filtered. It can be sets, lists, tuples, or other iterators.
In the below example we take a bigger list of some month names and then filter out those months which does not have 30 days. For that we create a smaller list containing the months with 31 days and then apply the filter function.
 Live Demo
# list of Months
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug']
# function that filters some Months
def filterMonths(months):
   MonthsWith31 = ['Apr', 'Jun','Aug','Oct']
if(months in MonthsWith31):
   return True
else:
   return False
non30months = filter(filterMonths, months)
   print('The filtered Months :')
for month in non30months:
   print(month)
Running the above code gives us the following result −
The filtered Months :
Apr
Jun
Aug
How to declare a custom attribute in HTML ?

22 Jul, 2021
Attributes are extra information that provide for the HTML elements. There are lots of predefined attributes in HTML.
When the predefined attributes do not make sense to store extra data, custom attributes allow users to create custom data. If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery. There are some rules to keep in mind before defining your custom attributes.
You must define your attribute in lower case letters. Even though some browsers do automatically correct mistakes in the markup, it can cause errors, and they are not valid HTML5.
It must not start with XML (case-insensitive)
It should not contain any colon characters ( : ).
Any ordinary HTML element can become rather complex and custom defined through the HTML data-* attribute. Let us define a simple article tag in HTML for this article and store some extra information. You can access these values in JavaScript and CSS and use them according to your purpose. You can even define names similar to predefined tags. A custom attribute data-id is different from the id tag that is usually used. You can console the values and test that out.
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        body {            background-color: "red";        }          article[data-parent="GFG"] {            width: 1000px;            font-size: 50px;            color: green;        }          article[data-parent="GFG2"] {            width: 600px;            color: black;            font-size: 50px;        }    </style></head>  <body>    <article id="1"         data-title="custom-attributes"         data-parent="GFG">        Sample GFG article on Custom Attributes.    </article>      <article id="2"         data-title="custom-attributes-2"         data-parent="GFG2">        Sample GFG second article         on Custom Attributes.    </article>      <script>        const article = document.getElementById('1');        const article2 = document.getElementById('2');          // "custom-attributes"        console.log(article.dataset.title);          // "GFG"        console.log(article.dataset.parent);                            // "custom-attributes-2"        console.log(article2.dataset.title);                  // "GFG2"        console.log(article2.dataset.parent);    </script></body>  </html>
Output:
custom attributes
HTML-Attributes
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the size of axis labels in Matplotlib?

03 Jan, 2021
Matplotlib is a great data plotting tool. It’s used for visualizing data and also for presenting the data to your team on a presentation or for yourself for future reference. So, while presenting it might happen that the “X-label” and “y-label” are not that visible and for that reason, we might want to change its font size.  So in this article, we are going to see how we can change the size of axis labels in Matplotlib.  
Before starting let’s draw a simple plot with matplotlib.
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]y = [9, 8, 7, 6, 5]  fig, ax = plt.subplots()ax.plot(x, y)  ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')  plt.show()
Output 
Example 1: Changing both axis label.
 If we want to change the font size of the axis labels, we can use the parameter “fontsize” and set it your desired number. 
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]y = [9, 8, 7, 6, 5]  fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y)  ax.set_xlabel('x-axis', fontsize = 12)ax.set_ylabel('y-axis', fontsize = 10)  plt.show()
Output 
Example 2: Changing the y-axis label.
Python3
import matplotlib.pyplot as plt  x = [1, 2, 3, 4, 5]y = [9, 8, 7, 6, 5]  fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y)  plt.xticks(fontsize = 15)plt.show()
Output
Here the font size of X values is being set to 15
Picked
Python-matplotlib
Python
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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
java.time.Instant.toEpochMilli() Method Example

The java.time.Instant.toEpochMilli() method converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
Following is the declaration for java.time.Instant.toEpochMilli() method.
public long toEpochMilli()

the number of milliseconds since the epoch of 1970-01-01T00:00:00Z.
ArithmeticException − if numeric overflow occurs.
The following example shows the usage of java.time.Instant.toEpochMilli() method.
package com.tutorialspoint;

import java.time.Instant;

public class InstantDemo {
   public static void main(String[] args) {

      Instant instant = Instant.parse("2014-12-03T10:15:30.00Z");
      System.out.println(instant.toEpochMilli());
   }
}
Let us compile and run the above program, this will produce the following result −
1417601730000

 Print
 Add Notes
 Bookmark this page
Converting a StringBuilder to String in Java

The toString() method of the StringBuilder class reruns String value of the current object. To convert a StringBuilder to String value simple invoke the toString() method on it.
Instantiate the StringBuilder class.
Instantiate the StringBuilder class.
Append data to it using the append() method.
Append data to it using the append() method.
Convert the StringBuilder to string using the toString() method.
Convert the StringBuilder to string using the toString() method.
In the following Java program we are converting an array of Strings to a single String using the toString() method of the StringBuilder.
 Live Demo
public class StringToStringBuilder {
   public static void main(String args[]) {
      String strs[] = {"Arshad", "Althamas", "Johar", "Javed", "Raju", "Krishna" };
      StringBuilder sb = new StringBuilder();
      sb.append(strs[0]);
      sb.append(" "+strs[1]);
      sb.append(" "+strs[2]);
      sb.append(" "+strs[3]);
      sb.append(" "+strs[4]);
      sb.append(" "+strs[5]);
      String singleString = sb.toString();
      System.out.println(singleString);
   }
}
Arshad Althamas Johar Javed Raju Krishna
How to match and group array elements with the max value in MongoDB aggregation?

For this, use $group along with $max in MongoDB. Let us create a collection with documents −
> db.demo510.insertOne(
... {
...    details:[
...       {
...          Name:"Chris",
...          Score:56
...       },
...       {
...          Name:"David",
...          Score:45
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8845fa987b6e0e9d18f582")
}
> db.demo510.insertOne(
... {
...    details:[
...       {
...          Name:"Chris",
...          Score:56
...       },
...       {
...          Name:"David",
...          Score:47
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8845fb987b6e0e9d18f583")
}
> db.demo510.insertOne(
... {
...    details:[
...       {
...          Name:"Chris",
...          Score:45
...       },
...       {
...          Name:"David",
...          Score:91
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8845fb987b6e0e9d18f584")
}
Display all documents from a collection with the help of find() method −
> db.demo510.find();
This will produce the following output −
{ "_id" : ObjectId("5e8845fa987b6e0e9d18f582"), "details" : [ { "Name" : "Chris", "Score" : 56 },
{ "Name" : "David", "Score" : 45 } ] }
{ "_id" : ObjectId("5e8845fb987b6e0e9d18f583"), "details" : [ { "Name" : "Chris", "Score" : 56 },
{ "Name" : "David", "Score" : 47 } ] }
{ "_id" : ObjectId("5e8845fb987b6e0e9d18f584"), "details" : [ { "Name" : "Chris", "Score" : 45 },
{ "Name" : "David", "Score" : 91 } ] }
Following is the query to match and group array elements with the max value in aggregation −
> db.demo510.aggregate([
... { "$project": {
...    "details": {
...       "$arrayElemAt": [
...          { "$filter": {
...             "input": "$details",
...             "as": "res",
...             "cond": {
...                "$eq": [
...                   "$$res.Score",
...                   { "$max": {
...                      "$map": {
...                         "input": "$details",
...                         "as": "out",
...                         "in": "$$out.Score"
...                      }
...                   }}
...                ]
...             }
...          }},
...          0
...       ]
...    }
... }},
... { "$group": {
...    "_id": "$details.Name",
...    "Name": { "$first": "$details.Name" },
...    "count": { "$sum": 1 }
... }}
... ])
This will produce the following output −
{ "_id" : "David", "Name" : "David", "count" : 1 }
{ "_id" : "Chris", "Name" : "Chris", "count" : 2 }
PHP 7 - Filtered unserialize()

PHP 7 introduces Filtered unserialize() function to provide better security when unserializing objects on untrusted data. It prevents possible code injections and enables the developer to whitelist classes that can be unserialized.
<?php
   class MyClass1 { 
      public $obj1prop;   
   }
   class MyClass2 {
      public $obj2prop;
   }

   $obj1 = new MyClass1();
   $obj1->obj1prop = 1;
   $obj2 = new MyClass2();
   $obj2->obj2prop = 2;

   $serializedObj1 = serialize($obj1);
   $serializedObj2 = serialize($obj2);

   // default behaviour that accepts all classes
   // second argument can be ommited.
   // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object
   $data = unserialize($serializedObj1 , ["allowed_classes" => true]);

   // converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2
   $data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]);

   print($data->obj1prop);
   print("<br/>");
   print($data2->obj2prop);
?>
It produces the following browser output −
1
2


    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
SQL Query to Calculate Total Number of Days Between Two Specific Dates

23 Apr, 2021
Here we will see, how to calculate the number of days between the two given dates with the help of SQL query using DATEDIFF() function.
For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Use the below SQL statement to switch the database context to geeks:
USE geeks;
We have the following demo_table in our geeks database.
CREATE TABLE demo_orders(
ORDER_ID INT IDENTITY(1,1) PRIMARY KEY, 
ITEM_NAME VARCHAR(30) NOT NULL,
ORDER_DATE DATE
);
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS demo_orders;
Use the below statement to add data to the demo_orders table:
INSERT INTO demo_orders --no need to mention columns explicitly as we are inserting into
                        --all columns and ID gets
                          --automatically incremented.
VALUES
('Maserati', '2007-10-03'),
('BMW', '2010-07-23'),
('Mercedes Benz', '2012-11-12'),
('Ferrari', '2016-05-09'),
('Lamborghini', '2020-10-20');
To verify the contents of the table use the below statement:
SELECT * FROM demo_orders;
Now let’s find the number of months between the dates of the order of ‘Maserati’ and ‘Ferrari’ in the table using DATEDIFF() function.
Below is the syntax for the DATEDIFF() function to find the no. of days between two given dates.
Syntax: DATEDIFF(day or dy or y, <start_date>, <end_date>);
Example: 
DECLARE 
@start VARCHAR(10) = (
  SELECT order_date FROM demo_orders
  WHERE item_name = 'Maserati'),
@end VARCHAR(10) = (
  SELECT order_date FROM demo_orders
  WHERE item_name = 'Ferrari')
  

--@start variable holds the start date(i.e date of Maserati being purchased).

--@end variable holds the end date (i.e date of Ferrari being purchased).

SELECT DATEDIFF(day, @start, @end) AS number_of_days;
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Add values to Dictionary of List

01 Dec, 2021
In this article, we will discuss how to add values to the dictionary of lists. 
We can add values to a dictionary by using a list, the input list would be the following structure:
[('key',value),...........,('key',value)]
So the above list is an input, which we can use with for loop to add values to the dictionary of lists.
Syntax:
for key, value in input:
    data[key].append(value)
where,
key is the key in the input list
value is the value in the input list
Example 1: Python program to create an input list of students subjects and add to the dictionary of list
Python3
# import defaultdict modulefrom collections import defaultdict # declare a list with student datainput = [('bhanu', 'html'),         ('bhanu', 'php'),         ('suma', 'python'),         ('rasmi', 'java'),         ('suma', 'html/csscss')] # declare a default dictdata = defaultdict(list) # append to the dictionaryfor key, value in input:    data[key].append(value) # displayprint(data.items())
Output:
dict_items([(‘bhanu’, [‘html’, ‘php’]), (‘suma’, [‘python’, ‘html/csscss’]), (‘rasmi’, [‘java’])])
Example 2:
Python3
# import defaultdict modulefrom collections import defaultdict # declare a list with student data with ageinput = [('bhanu', 10), ('uma', 12), ('suma', 11)] # declare a default dictdata = defaultdict(list) # append to the dictionaryfor key, value in input:    data[key].append(value) # displayprint(data.items())
Output:
dict_items([('bhanu', [10]), ('uma', [12]), ('suma', [11])])
kapoorsagar226
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to Find Average Marks of Each Student in SQL?

28 Nov, 2021
In SQL, sometimes we need to find the average value of a column based on another column of the table such as finding the student-wise average marks scored by him/her in all the subjects. This involves the use of the GROUP BY clause along with the AGGREGATE function like AVG. The same is depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database.
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table of STDMARKS inside the database GeeksForGeeks. This table has 4 columns namely ROLL_NO, STUDENT_NAME, SUBJECT, and MARKS containing the roll number and name of the students and the subject name and marks scored by the student in the respective subject.
Query:
CREATE TABLE STDMARKS(
ROLL_NO INT,
STUDENT_NAME VARCHAR(10),
SUBJECT VARCHAR(10),
MARKS INT);
Output:
Step 4: Describe the structure of the table STDMARKS.
Query:
EXEC SP_COLUMNS STDMARKS;
Output:
Step 5: Insert 16 rows into the STDMARKS table.
Query:
INSERT INTO STDMARKS VALUES(1,'RAVI','C++',75);
INSERT INTO STDMARKS VALUES(1,'RAVI','ORACLE',84);
INSERT INTO STDMARKS VALUES(1,'RAVI','JAVA',95);
INSERT INTO STDMARKS VALUES(1,'RAVI','OS',62);
INSERT INTO STDMARKS VALUES(2,'VIVEK','C++',46);
INSERT INTO STDMARKS VALUES(2,'VIVEK','ORACLE',70);
INSERT INTO STDMARKS VALUES(2,'VIVEK','JAVA',55);
INSERT INTO STDMARKS VALUES(2,'VIVEK','OS',56);
INSERT INTO STDMARKS VALUES(3,'RAJ','C++',82);
INSERT INTO STDMARKS VALUES(3,'RAJ','ORACLE',84);
INSERT INTO STDMARKS VALUES(3,'RAJ','JAVA',74);
INSERT INTO STDMARKS VALUES(3,'RAJ','OS',92);
INSERT INTO STDMARKS VALUES(4,'MAHESH','C++',43);
INSERT INTO STDMARKS VALUES(4,'MAHESH','ORACLE',49);
INSERT INTO STDMARKS VALUES(4,'MAHESH','JAVA',68);
INSERT INTO STDMARKS VALUES(4,'MAHESH','OS',35);
Output:
Step 6: Display all the rows of the STDMARKS table.
Query:
SELECT * FROM STDMARKS;
Output:
Step 7: Display the ROLL_NO of the student and the average marks scored by that student in all subjects from the table STDMARKS. For achieving the aggregate value of a column according to another column, we need to use the GROUP BY clause along with the aggregate function such as AVG. The column mentioned after the GROUP BY clause is the basis for our output. The student-wise average marks are achieved in this manner.
Syntax:
SELECT COLUMN_NAME1,AVG(COLUMN_NAME2)
AS ALIAS FROM TABLE_NAME GROUP BY COLUMN_NAME1;
Query:
SELECT ROLL_NO,AVG(MARKS) AS "AVERAGE MARKS"
FROM STDMARKS GROUP BY ROLL_NO;
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Deep clone in JavaScript?

08 Oct, 2021
In general, cloning means copying one value to another. In JavaScript, we do cloning i.e. copying one value to another using JavaScript. To be more precise they are two types of cloning in JavaScript. As a programmer, it might be a beginner or veteran he/she should be able to know the differences between Deep clone and shallow clone. As this article is about Deep clones we will study detail about Deep clones. Cloning is a concept that can happen in any data type i.e., it might be a primitive data type (like string, number) or composite data types like arrays and JavaScript. So in order to master it, we need to be clear with the foundation.Deep Clone: Deep clone is a technique that is used to duplicate everything whenever we are cloning arrays, JavaScript in order to avoid data loss.
Example 1: As in this example, the data is becoming corrupted if we change one object value then it is reflecting in other objects also that is the reason in order to avoid this problem we use Deep Clone.
Javascript
<script>    var student1 ={        name : "Manish",        company : "Gfg"     }     var student2 =  student1  ;     student1.name = "Rakesh"         console.log("student 1 name is",student1.name)    console.log("student 2 name is ",student2.name);</script>
Output:
Example 2: Using Spread Operator
Javascript
<script>    var student1 ={     name : "Manish",    company : "Gfg"     }     var student2 =  { ...student1 } ;     student1.name = "Rakesh"     console.log("student 1 name is",student1.name)    console.log("student 2 name is ",student2.name);</script>
Output: 
Example 3: Using Object.assign()
Javascript
<script>    var student1 ={    name : "Manish",    company : "Gfg"    }     var student2 = Object.assign( {} ,student1) ;     student1.name = "Rakesh"     console.log("student 1 name is",student1.name)    console.log("student 2 name is ",student2.name);</script>
Output:
Example 4: Using Json.parse and Json.stringify
Javascript
<script>    var student1 ={    name : "Manish",    company : "Gfg"     }     var student2 = JSON.parse(JSON.stringify(student1))     student1.name = "Rakesh"     console.log("student 1 name is",student1.name)    console.log("student 2 name is ",student2.name);</script>
Output:
Conclusion: We can use all of these approaches to make sure that the data is safe and doesn’t get mutate when we change in one object.
adnanirshad158
JavaScript-Misc
JavaScript
Web Technologies
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Calculating byte values to megabyte (MB) in MySQL?

Here, we are taking BIGINT type, since it takes 8 byte signed integer. Let us first create a table with column as BIGINT type −
mysql> create table DemoTable2031
   -> (
   -> ByteValue bigint
   -> );
Query OK, 0 rows affected (1.17 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2031 values(1048576);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2031 values(1073741824);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2031;
This will produce the following output −
+------------+
| ByteValue  |
+------------+
| 1048576    |
| 1073741824 |
+------------+
2 rows in set (0.00 sec)
Here is the query to calculate bytes to Megabyte (MB) −
mysql> select (ByteValue/(1024*1024)) as MB from DemoTable2031;
This will produce the following output −
+-----------+
| MB        |
+-----------+
| 1.0000    |
| 1024.0000 |
+-----------+
2 rows in set (0.00 sec)
C++ Program to Generate All Subsets of a Given Set in the Lexico Graphic Order

This is C++ Program to Generate All Subsets of a Given Set in the Lexico Graphic Order. This algorithm prints all the possible combination of each length from the given set of array in increasing order. The time complexity of this algorithm is O(n*(2^n)).
Begin
   For each length ‘i’ GenAllSubset() function is called:
   1) In GenAllSubset(), if currLen is more than the reqLen then return.
   2) Otherwise, if currLen is equal to reqLen then there will be a new sequence generated, print it.
   3) If proceed with a start as ‘true’ and recursively call GenAllSubset() with incremented value of ‘currLen’ and ‘s’.
   else
      proceed with a start as ‘false’ and recursively call GenAllSubset() with incremented value of ‘s’.
End
#include<iostream>
using namespace std;
void Sorting(int a[], int n) //array sorting {
   int i, j, t;
   for(i = 0; i < n; i++) {
      for(j = i+1; j < n; j++) {
         if(a[i] > a[j]) {
            t = a[i];
            a[i] = a[j];
            a[j] = t;
         }
      }
   }
}
void GenAllSubset(int a[], int reqLen, int s, int currLen, bool check[], int len) {
   if(currLen > reqLen)
      return;
   else if (currLen == reqLen) {
      cout<<"\t";
      cout<<"{ ";
      for (int i = 0; i < len; i++) {
         if (check[i] == true) {
            cout<<a[i]<<" ";
         }
      }
      cout<<"}\n";
      return;
   }
   if (s == len) {
      return;
   }
   check[s] = true;
   GenAllSubset(a, reqLen, s + 1, currLen + 1, check, len);
   check[s] = false;
   GenAllSubset(a, reqLen, s + 1, currLen, check, len);
}
int main() {
   int i, n;
   bool ch[n];
   cout<<"Enter the number of element array have: ";
   cin>>n;
   int arr[n];
   cout<<"\n";
   for (i = 0; i < n; i++) {
      cout<<"Enter "<<i+1<<" element: ";
      cin>>arr[i];
      ch[i] = false;
   }
   Sorting(arr, n);
   cout<<"\nThe all subset of the given set in the lexicographic order: \n";
   cout<<"\t{ }\n";
   for(i = 1; i <= n; i++) {
      GenAllSubset(arr, i, 0, 0, ch, n);
   }
   return 0;
}
Enter the number of element array have: 6
Enter 1 element:3
Enter 2 element: 2
Enter 3 element: 1
Enter 4 element:7
Enter 5 element:6
Enter 6 element: 5
The all subset of the given set in the lexicographic order:
{ }
{ 1 }
{ 2 }
{ 3 }
{ 5 }
{ 6 }
{ 7 }
{ 1 2 }
{ 1 3 }
{ 1 5 }
{ 1 6 }
{ 1 7 }
{ 2 3 }
{ 2 5 }
{ 2 6 }
{ 2 7 }
{ 3 5 }
{ 3 6 }
{ 3 7 }
{ 5 6 }
{ 5 7 }
{ 6 7 }
{ 1 2 3 }
{ 1 2 5 }
{ 1 2 6 }
{ 1 2 7 }
{ 1 3 5 }
{ 1 3 6 }
{ 1 3 7 }
{ 1 5 6 }
{ 1 5 7 }
{ 1 6 7 }
{ 2 3 5 }
{ 2 3 6 }
{ 2 3 7 }
{ 2 5 6 }
{ 2 5 7 }
{ 2 6 7 }
{ 3 5 6 }
{ 3 5 7 }
{ 3 6 7 }
{ 5 6 7 }
{ 1 2 3 5 }
{ 1 2 3 6 }
{ 1 2 3 7 }
{ 1 2 5 6 }
{ 1 2 5 7 }
{ 1 2 6 7 }
{ 1 3 5 6 }
{ 1 3 5 7 }
{ 1 3 6 7 }
{ 1 5 6 7 }
{ 2 3 5 6 }
{ 2 3 5 7 }
{ 2 3 6 7 }
{ 2 5 6 7 }
{ 3 5 6 7 }
{ 1 2 3 5 6 }
{ 1 2 3 5 7 }
{ 1 2 3 6 7 }
{ 1 2 5 6 7 }
{ 1 3 5 6 7 }
{ 2 3 5 6 7 }
{ 1 2 3 5 6 7 }
How do I Install MySQLdb in Python?

Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following in your Python script and execute it −
#!/usr/bin/python
import MySQLdb
If it produces the following result, then it means MySQLdb module is not installed −
Traceback (most recent call last):
   File "test.py", line 3, in <module>
      import MySQLdb
ImportError: No module named MySQLdb
To install MySQLdb module, use the following command −
For Ubuntu, use the following command -
$ sudo apt-get install python-pip python-dev libmysqlclient-dev
For Fedora, use the following command -
$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc
For Python command prompt, use the following command -
pip install MySQL-python
Note − Make sure you have root privilege to install above module.
Java Examples - Id of a Thread

How to get the Id of the running thread?
Following example demonstrates how to get the Id of a running thread using getThreadId() method.
public class Main extends Object implements Runnable {
   private ThreadID var;
   public Main(ThreadID v) {
      this.var = v;
   } 
   public void run() {
      try {
         print("var getThreadID =" + var.getThreadID());
         Thread.sleep(2000);
         print("var getThreadID =" + var.getThreadID());
      } catch (InterruptedException x) {}
   } 
   private static void print(String msg) {
      String name = Thread.currentThread().getName();
      System.out.println(name + ": " + msg);
   } 
   public static void main(String[] args) {
      ThreadID tid = new ThreadID();
      Main shared = new Main(tid);
      try {
         Thread threadA = new Thread(shared, "threadA");
         threadA.start();
         Thread.sleep(500);
         
         Thread threadB = new Thread(shared, "threadB");
         threadB.start();
         Thread.sleep(500);
         
         Thread threadC = new Thread(shared, "threadC");
         threadC.start();
      } catch (InterruptedException x) {}
   }
}
class ThreadID extends ThreadLocal {
   private int nextID;
   public ThreadID() {
      nextID = 10001;
   } 
   private synchronized Integer getNewID() {
      Integer id = new Integer(nextID);
      nextID++;
      return id;
   } 
   protected Object initialValue() {
      print("in initialValue()");
      return getNewID();
   } 
   public int getThreadID() {
      Integer id = (Integer) get();
      return id.intValue();
   } 
   private static void print(String msg) {
      String name = Thread.currentThread().getName();
      System.out.println(name + ": " + msg);
   }
}
The above code sample will produce the following result.
threadA: in initialValue()
threadA: var getThreadID = 10001
threadB: in initialValue()
threadB: var getThreadID = 10002
threadC: in initialValue()
threadC: var getThreadID = 10003
threadA: var getThreadID = 10001
threadB: var getThreadID = 10002
threadC: var getThreadID = 10003

 Print
 Add Notes
 Bookmark this page
How to apply linear gradient (color) to a node in JavaFX?

You can apply colors to shapes in JavaFX using the setFill() method it adds color to the interior of the geometrical shapes or background.
This method accepts an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color.
The javafx.scene.paint.LinearGradient class in JavaFX is a subclass of the Paint and using this you can fill a shape with a circular linear-gradient pattern.
To apply a radial gradient pattern to a geometrical shape −
Instantiate the LinearGradient class by passing the required parameters.
Instantiate the LinearGradient class by passing the required parameters.
Set the created gradient to the shape using the setFill() method.
Set the created gradient to the shape using the setFill() method.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class LinearGradientExample extends Application {
   public void start(Stage stage) {
      //Drawing a circle
      Circle circle = new Circle(75.0f, 65.0f, 40.0f );
      //Drawing a Rectangle
      Rectangle rect = new Rectangle(150, 30, 100, 65);
      //Drawing an ellipse
      Ellipse ellipse = new Ellipse(330, 60, 60, 35);
      //Drawing Polygon
      Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
      //Setting the linear gradient
      Stop[] stops = new Stop[] {
         new Stop(0, Color.DARKSLATEBLUE),
         new Stop(1, Color.DARKRED)
      };
      LinearGradient gradient =
      new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
      //Setting the pattern
      circle.setFill(gradient);
      circle.setStrokeWidth(3);
      circle.setStroke(Color.CADETBLUE);
      rect.setFill(gradient);
      rect.setStrokeWidth(3);
      rect.setStroke(Color.CADETBLUE);
      ellipse.setFill(gradient);
      ellipse.setStrokeWidth(3);
      ellipse.setStroke(Color.CADETBLUE);
      poly.setFill(gradient);
      poly.setStrokeWidth(3);
      poly.setStroke(Color.CADETBLUE);
      //Setting the stage
      Group root = new Group(circle, ellipse, rect, poly);
      Scene scene = new Scene(root, 600, 150);
      stage.setTitle("Linear Gradient");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
How can I insert the values in columns without specifying the names of the column in MySQL INSERT INTO statement?

For inserting the values in the column without specifying the names of the columns in INSERT INTO statement, we must give the number of values that matches the number of columns in the table along with taking care about the data type of that column too.
In the example below we have inserted the values without specifying the name of the column.
mysql> Insert into student values(100,'Gaurav','Ph.D');
Query OK, 1 row affected (0.08 sec)

mysql> Select * from student;
+--------+--------+--------+
| RollNO | Name   | Class  |
+--------+--------+--------+
| 100    | Gaurav | Ph.D   |
+--------+--------+--------+

1 row in set (0.00 sec)

mysql> Insert into student values(200,'Rahul','Ph.D'),(300,'Aarav','B.tech');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from student;

+--------+--------+--------+
| RollNO | Name   | Class  |
+--------+--------+--------+
| 100    | Gaurav | Ph.D   |
| 200    | Rahul  | Ph.D   |
| 300    | Aarav  | B.tech |
+--------+--------+--------+

3 rows in set (0.00 sec)
MySQL throws error if we will not take care about the total number of columns and their data types as follows −
mysql> Insert into student values(400,'Raman',M.Tech);
ERROR 1054 (42S22): Unknown column 'M.Tech' in 'field list'

mysql> Insert into student values(400,'Raman');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
How to install Tkinter for Python on Linux?

Tkinter is one of the widely used libraries for creating GUI-based applications. In order to create applications using Tkinter, we have to install and import the library in the notebook.
First, we have to install the tkinter library in our local environment based on the Windows or Linux operating system.
For Windows users −
pip install tkinter
or
pip install tk
For Linux or Mac users −
apt-get install python-tk
Once installed, the user can import the tkinter library in the notebook using the following command,
from tkinter import*

To check if tkinter is installed in the system or not, we can use the following command,
import tkinter as tk
Tryit Editor v3.7

CSS Multiple Columns
Tryit: Specify the style, width and color of the rule between columns
Maximum of two numbers in Python - GeeksforGeeks

24 Nov, 2021
Given two numbers, write a Python code to find the Maximum of these two numbers.
Examples: 
Input: a = 2, b = 4
Output: 4

Input: a = -1, b = -4
Output: -1
Method #1: This is the naive approach where we will compare two numbers using if-else statement and will print the output accordingly.
Example: 
Python3
# Python program to find the# maximum of two numbers  def maximum(a, b):         if a >= b:        return a    else:        return b     # Driver codea = 2b = 4print(maximum(a, b))
4
Method #2: Using max() functionThis function is used to find the maximum of the values passed as its arguments.
Example: 
Python3
# Python program to find the# maximum of two numbers  a = 2b = 4 maximum = max(a, b)print(maximum)
4
Method #3: Using Ternary Operator
This operator is also known as conditional expression are operators that evaluate something based on a condition being true or false. It simply allows testing a condition in a single line
Example:
Python3
# Python program to find the# maximum of two numbers     # Driver codea = 2b = 4 # Use of ternary operatorprint(a if a >= b else b) # This code is contributed by AnkThon
4
ankthon
simmytarika5
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
C++ Classes and Objects

C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and 
methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and 
methods, such as drive and brake.
Attributes and methods are basically variables and 
functions that belongs to the class. These are often referred to as 
"class members".
A class is a user-defined data type that we can use in our program, and it 
works as an object constructor, or a "blueprint" for creating objects.
To create a class, use the class keyword:
Create a class called "MyClass":
The class keyword is used to create a class called MyClass.
The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. You will learn more about access specifiers later.
Inside the class, there is an integer variable 
myNum and a string variable myString. When variables are declared 
within a class, they are called attributes.
At last, end the class definition with a semicolon ;.
In C++, an object is created from a class. We have already created the class named MyClass, 
so now we can use this to create objects.
To create an object of MyClass, specify the 
class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) 
on the object:
Create an object called "myObj" and access 
the attributes:
You can create multiple objects of one class:
Create an object of MyClass called myObj.
 ;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Check if a cycle of length 3 exists or not in a graph that satisfy a given condition - GeeksforGeeks

13 May, 2021
Given an array Arr of N integers representing the nodes of a graph. The edges are defined between those pairs whose bitwise AND is not equal to zero. The task is to find if there exists a cycle of length 3 or not in the graph.Examples:  
Input: Arr[] = {26, 33, 35, 40, 50} Output: YesA cycle exists between 26, 33 and 50.Input: Arrr[] = {17, 142, 243, 300} Output: No 
 
Naive Approach: Run a nested loop and check for each pair whether there exists an edge between them(if their bitwise AND value is non-zero). Thus, we form the entire graph and check if a cycle exists in this graph by using any of cycle detection methods.Efficient Approach:  
A cycle is formed by joining at least 3 edges.
The idea is to make a 2D array where i-th row stores the binary value of Arr[i].
Next, loop in column-wise fashion and check if there exists a column where the number of 1’s is at least 3.If so, it implies that there exists a cycle in the graph.If no such column exists, it implies that there is no cycle in the graph.
If so, it implies that there exists a cycle in the graph.
If no such column exists, it implies that there is no cycle in the graph.
 
Arr[] = {26, 33, 35, 40, 50}The 2D array is as following bi = [ [0 1 0 1 1 0 0 0], [1 0 0 0 0 1 0 0], [1 1 0 0 0 1 0 0], [0 0 0 1 0 1 0 0], [0 1 0 0 1 1 0 0], ] bi[0][1], bi[2][1] and bi[4][1] are equal to 1. This implies that bitwise AND value of the following pairs (Arr[0], Arr[2]), (Arr[2], Arr[4]), (Arr[0], Arr[4]) are non-zero. These 3 edges form a cycle. 
Below is the implementation of the above approach:  
Code block
Yes
 
jit_t
princiraj1992
sanjeev2552
divyeshrabadiya07
graph-cycle
Bit Magic
Competitive Programming
Graph
Matrix
Bit Magic
Matrix
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming
Difference Between Inline and Normal Function in C++ - GeeksforGeeks

08 Feb, 2022
Inline Function is a function that is expanded inline by the compiler when it is invoked. During function call, a lot of overhead tasks are performed like saving registers, pushing arguments to the stack, and returning to the calling function. These overheads are time-consuming and inefficient for small-size functions. In C++, the inline function is used to solve these overhead costs. It is expanded in line by the compiler when it is invoked, thus overhead cost is avoided. A keyword known as ‘inline‘ is used before the function declaration. 
Syntax:
inline return_type function_name(parameters) 
{
// Insert your Function code here
}
Example:
C++
// C++ program to demonstrate inline function // Importing input output stream files#include <iostream> using namespace std; // Method 1// Inline function// To multiply two integer numbersinline int multiplication(int x, int y){     // Returning the product of two numbers    return x * y;} // Method 2// Main driver method/function// Execution begins hereint main(){    // Print and display the multiplication resultant number    // with usage of above created multiplication() inline()    cout << "Multiplication ( 20 , 30 ):"         << multiplication(20, 30) << endl;     return 0;}
Multiplication ( 20 , 30 ):600
Now dwelling onto the next function, s the name suggests Normal Function is basically simply a common function in C++. It promotes code reuse and makes the program modular. During function calls, a lot of overhead tasks are performed like saving registers, pushing arguments to the stack, and returning to the calling function. 
Syntax: 
return_type_name function_name( parameters) 
{ 
 // Insert your Function code here 
}
Example: 
C++
// Importing input output streams#include <iostream> using namespace std; // Method/Function// To get square of integer number been passedint square(int s){    // Returning the square of number    return s * s;} // Methodint main(){    // Calling the square() method/function    // over randoM value N         // Say N = 5    // Display message only    cout << "Enter number to compute its square : 5 " << endl;     // Calling the above square() in main()    // and print/display on the console    cout << "Square is : " << square(5) << endl;     return 0;}
Enter number to compute its square : 5 
Square is : 25
Inline Function 
Normal Function  
 
surinderdawra388
varshagumber28
avtarkumar719
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Classes and Objects
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Stack vs Heap Memory Allocation
How to create boxplot for multiple categories in base R?

To create the boxplot for multiple categories, we should create a vector for categories and construct data frame for categorical and numerical column. Once the construction of the data frame is done, we can simply use boxplot function in base R to create the boxplots by using tilde operator as shown in the below example.
Consider the below data frame −
 Live Demo
Categories<-sample(LETTERS[1:5],500,replace=TRUE)
Rate<-rnorm(500,8,2)
df<-data.frame(Categories,Rate)
head(df,20)
  Categories    Rate
1    C       4.618484
2    B       8.513390
3    A       9.071579
4    B       9.744654
5    C       5.963608
6    E       9.959320
7    A       9.803821
8    D       7.420664
9    C       7.776794
10   C       4.810012
11   B       8.556322
12   E       8.621443
13   B       7.353419
14   B       6.690489
15   A       12.806544
16   D       8.008669
17   B       10.102333
18   A       4.799457
19   D       6.999711
20   D       10.013520
Creating boxplot of Rate for categories −
boxplot(df$Rate~df$Categories)
How to scroll a Web Page using coordinates of a WebElement in Selenium WebDriver?

We can scroll a webpage using coordinates of a webelement in Selenium webdriver using the JavaScript Executor. Selenium executes JavaScript commands with the help of the executeScript method.
To get the unique coordinates of an element we shall create an object of the class Point which shall store the location of the webelement obtained from the getLocation method.
Then the individual x and y coordinate values can be computed from the getX and the getY methods respectively. Finally, to actually perform scroll upto the coordinates of an element, the command window.scrollBy(x coordinate, y coordinate) is passed as a parameter to the executeScript method.
(JavascriptExecutor)
driver).executeScript("window.scrollBy(100,150)");
here, 100 and 150 are the x and y coordinates respectively.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Point;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollWithCodrdnts{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      WebElement n = driver.findElement(By.linkText("Latest Courses"));

      //obtain element x, y coordinates with getLocation method
      Point p = n.getLocation();
      int X = p.getX();
      int Y = p.getY();
      //scroll with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("window.scrollBy(" + X + ", " + Y + ");");
      System.out.println("Text is: " + n.getText());
      driver.quit();
   }
}