code-rag-bench/online-tutorials huggingface dataset:
HTML DOM getRangeAt() method - GeeksforGeeks

03 Jul, 2020
The getRangeAt() method returns the range object which contains startOffset index and endOffset index from the selected text.
Syntax:
range = selection.getRangeAt(index)


Parameters:
index: zero-based index from the rangeCount of the document.
Return value:
Return the Range object which contain startOffset and endOffset index of selected text.
Example:
In this example, we will select some text and will get range of selected text.
<html>   <head>      <title>GeeksforGeeks</title>      </head>      <body>          <h1>GeeksforGeeks</h1>        <p>select some text and click on      button to get the range of selection</p>        <button onclick="range()">Click</button>      </body>        <script>            function range(){                 let ranges = [];              sel = window.getSelection();              for(let i = 0; i < sel.rangeCount; i++) {               ranges[i] = sel.getRangeAt(i);               console.log(ranges[i])              }              }        </script></html>
Output:
In console, range objects can be seen:
Supported Browsers:
Google Chrome
Edge
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
HTML Cheat Sheet - A Basic Guide to HTML
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
TRIM() Function in MySQL - GeeksforGeeks

23 Sep, 2020
TRIM() function in MySQL is used to clean up data. It is also used to remove the unwanted leading and trailing characters in a string.
Syntax :
TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)

Parameter : This method accepts three-parameter as mentioned above and described below :
BOTH | LEADING | TRAILING : LEADING, TRAILING, or BOTH option to explicitly instruct the TRIM() function to remove leading, trailing, or both leading and trailing unwanted characters from a string .By default, the TRIM() function uses the BOTH option.
removed_str : It is a string which we want to remove. If not given, spaces will be removed.
str : It identifies the string from which we want to remove removed_str.
Returns : It returns a string that has unwanted characters removed.
Example-1 : TRIM() function to remove only leading spaces.
SELECT TRIM(LEADING FROM "    www.geeksforgeeks.org    ") AS TrimmedString;

Output :
Example-2 : TRIM() function to remove only trailing spaces.
SELECT TRIM(TRAILING FROM "    www.geeksforgeeks.org    ") AS TrimmedString;

Output :
Example-3 : TRIM() function to remove both leading and trailing spaces.
SELECT TRIM("    www.geeksforgeeks.org    ") AS TrimmedString;

Output :
Example-4 : TRIM() function with the table data
Table : Student_Details :
SELECT  TRIM(TRAILING FROM Student_Name) FROM Student_Details AS Trimmed_String;

Output :
DBMS-SQL
mysql
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
Java Numeric Promotion in Conditional Expression - GeeksforGeeks

16 Dec, 2021
With recurrence use of if-else condition in programming which is tend to occur no matter how much we optimize our code. So taking this factor into consideration, conditional operator was introduced making our job of writing code easier as it do have a specific syntax in accordance to which it does check the condition passed to it. The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated. Let us do have an illustration to get used to with its syntax.
Illustration:
Object obj ;
if (true) {
    obj = new Integer(4) ;
} else {
    obj = new Float(2.0);
}
So, with the usage of conditional operator we expect the expression whose syntax is as follows:
Object obj = true ? new Integer(4) : new Float(2.0));
Note: But the result of running the code gives an unexpected result.
Example:
Java
// Java Program to Demonstrate// Replacing of Conditional Operator// with If-else and viceversa // Importing required classesimport java.io.*; // Main classclass GFG {     // Main driver method    public static void main (String[] args) {         // Expression 1 (using ?: )        // Automatic promotion in conditional expression        Object o1 = true ? new Integer(4) : new Float(2.0);         // Printing the output using conditional operator        System.out.println(o1);         // Expression 2 (Using if-else)        // No promotion in if else statement        Object o2;        if (true)            o2 = new Integer(4);        else            o2 = new Float(2.0);         // Printing the output using if-else statement        System.out.println(o2);    }}
Output:
According to Java Language Specification Section 15.25, the conditional operator will implement numeric type promotion if there are two different types as 2nd and 3rd operand.  The rules of conversion are defined at Binary Numeric Promotion. Therefore, according to the rules given, If either operand is of type double, the other is converted to double and hence 4 becomes 4.0. Whereas, the, if/else construct, does not perform numeric promotion and hence behaves as expected.
This article is contributed by Deepak Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@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.
solankimayank
sagartomar9927
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
What is a static class in C#?

The C# static class cannot be instantiated and can only have only static members. The static class in C# is sealed and cannot contain instance constructors.
The following is an example with static class and static members −
using System;

public static class Demo {
   public static float PI = 3.14f;
   public static int calc(int n){return n*n;}
}

class Program {

   public static void Main(string[] args) {
      Console.WriteLine("PI: "+Demo.PI);
      Console.WriteLine("Square: " + Demo.calc(3));
   }
}
Above, the static class is −
public static class Demo {
   public static float PI = 3.14f;
   public static int calc(int n){return n*n;}
}
Above we have the following static members −
public static float PI = 3.14f;
public static int calc(int n){return n*n;}
MFC - Animation Control

An animation control is a window that displays an Audio clip in AVI format. An AVI clip is a series of bitmap frames, like a movie. Animation controls can only play simple AVI clips, and they do not support sound. It is represented by the CAnimateCtrl class.
Following is the list of methods in CAnimateCtrl class −
Close
Closes the AVI clip.
Create
Creates an animation control and attaches it to a CAnimateCtrl object.
CreateEx
Creates an animation control with the specified Windows extended styles and attaches it to a CAnimateCtrl object.
IsPlaying
Indicates whether an Audio-Video Interleaved (AVI) clip is playing.
Open
Opens an AVI clip from a file or resource and displays the first frame.
Play
Plays the AVI clip without sound.
Seek
Displays a selected single frame of the AVI clip.
Stop
Stops playing the AVI clip.
Here is the list of messages mapping for animation control −
Let us look into a simple example of animation control.
Step 1 − Create a new MFC dialog based project.
Step 2 − Once the project is created, remove the TODO line and click on Animation Control in Toolbox and draw a rectangle as shown in the following snapshot.
Step 3 − To add a control variable for animation control, right-click and select Add Variable.
Step 4 − Enter the variable name and variable type, which is CAnimateCtrl for animation.
Step 5 − Using the Properties window, set the Border value to False, Set the Auto Play, the Center, and the transparent values to True.
Step 6 − Here we have *.avi file in res folder, which is the default folder for any resources used in the project.
Step 7 − To start the animation, we need to call the Open method CAnimateCtrl class. Add the following line of code in CMFCAnimationDemoDlg::OnInitDialog()
m_animationCtrl.Open(L"res\\copyfile.avi");

Step 8 − Here is the complete implementation of CMFCAnimationDemoDlg::OnInitDialog()
BOOL CMFCAnimationDemoDlg::OnInitDialog(){
   CDialogEx::OnInitDialog();
	
   // Add "About..." menu item to system menu.
	
   // IDM_ABOUTBOX must be in the system command range.
   ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
   ASSERT(IDM_ABOUTBOX < 0xF000);
	
   CMenu* pSysMenu = GetSystemMenu(FALSE);
   if (pSysMenu != NULL){
      BOOL bNameValid;
      CString strAboutMenu;
      bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
      ASSERT(bNameValid);
      if (!strAboutMenu.IsEmpty()){
         pSysMenu -> AppendMenu(MF_SEPARATOR);
         pSysMenu -> AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
      }
   }
	
   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);        // Set big icon
   SetIcon(m_hIcon, FALSE);       // Set small icon
	
   // TODO: Add extra initialization here
   m_animationCtrl.Open(L"res\\copyfile.avi");
	
   return TRUE; // return TRUE unless you set the focus to a control
}
Step 9 − When the above code is compiled and executed, you will see the following output.
 Print
 Add Notes
 Bookmark this page
jQuery Traversing Descendants

With jQuery you can traverse down the DOM tree to 
find descendants of an element.
A descendant is a child, grandchild, great-grandchild, and so 
on.
Two useful jQuery methods for traversing down the DOM tree are:
children()
find()
The children() method returns all direct children of the selected element.
This method only traverses a single level down the DOM tree.
The following example returns all elements that are direct children of each <div> elements:
You can also use an optional parameter to filter the search for children.
The following example returns all <p> elements with the class name "first", that 
are direct children of <div>:
The find() method returns descendant elements of the selected element, all 
the way down to the last descendant.
The following example returns all <span> elements that are 
descendants of <div>:
The following example returns all 
descendants of <div>:
Use a jQuery method to get all direct children of a <div> element element.
$("div").();

Start the Exercise
For a complete overview of all jQuery Traversing methods, please go to our
jQuery Traversing Reference.
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.
Activity Selection Problem (Greedy Algo-1) in C++?

There are n different activities are given with their starting time and ending time. Select maximum number of activities to solve by a single person.
We will use the greedy approach to find the next activity whose finish time is minimum among rest activities, and the start time is more than or equal with the finish time of the last selected activity.
The complexity of this problem is O(n log n) when the list is not sorted. When the sorted list is provided the complexity will be O(n).
The complexity of this problem is O(n log n) when the list is not sorted. When the sorted list is provided the complexity will be O(n).
A list of different activities with starting and ending times.
{(5,9), (1,2), (3,4), (0,6), (5,7), (8,9)}
Selected Activities are −
Activity: 0 , Start: 1 End: 2
Activity: 1 , Start: 3 End: 4
Activity: 3 , Start: 5 End: 7
Activity: 5 , Start: 8 End: 9
Input - A list of activity, and the number of elements in the list.Output - The order of activities how the have been chosen.
Begin
   initially sort the given activity List
   set i := 1
   display the i-th activity //in this case it is the first activity
   for j := 1 to n-1 do
      if start time of act[j] >= end of act[i] then
         display the jth activity
         i := j
   done
End
 Live Demo
#include<iostream>
#include<algorithm>
using namespace std;
   struct Activitiy {
      int start, end;
   };
   bool comp(Activitiy act1, Activitiy act2) {
      return (act1.end < act2.end);
   }
   void maxActivity(Activitiy act[], int n) {
   sort(act, act+n, comp); //sort activities using compare function
   cout << "Selected Activities are: " << endl;
   int i = 0;// first activity as 0 is selected
   cout << "Activity: " << i << " , Start: " <<act[i].start << " End: " << act[i].end <<endl;
   for (int j = 1; j < n; j++) { //for all other activities
      if (act[j].start >= act[i].end) { //when start time is >=end time, print the activity
         cout << "Activity: " << j << " , Start: " <<act[j].start << " End: " << act[j].end <<endl;
         i = j;
      }
   }
}
int main() {
   Activitiy actArr[] = {{5,9},{1,2},{3,4},{0,6},{5,7},{8,9}};
   int n = 6;
   maxActivity(actArr,n);
   return 0;
}
Selected Activities are:
Activity: 0 , Start: 1 End: 2
Activity: 1 , Start: 3 End: 4
Activity: 3 , Start: 5 End: 7
Activity: 5 , Start: 8 End: 9
How to find specific lines in a table using Selenium?

We can find specific lines in a table with Selenium webdriver. A table is identified in an html document with <table> tag. Each table comprises a <tr> tag that represents rows and a <td> tag to represent columns. To traverse through table rows and columns we use the method findElements().
To count the total number of rows in table we use size() method available for list −
List <WebElement> l=driver.findElements(By.tagName("tr"));
int s= l.size();
To count the total number of columns in table we use size() method available for list −
List <WebElement> m=driver.findElements(By.tagName("td"));
int t= m.size();
Let us consider the below table and get the value of TYPE having AUTOMATION TOOL as UFT.
The html structure of a table is described below −
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TableHandling{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = " https://sqengineer.com/practice-sites/practice-tables- selenium/";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify table
      WebElement mytable = driver.findElement(By.xpath("//table[@id='table1']/tbody"));
      //identify rows of table.
      List<WebElement> r_table = mytable.findElements(By.tagName("tr"));
      String b_xpath = "//table[@id='table1']/tbody/tr[";
      String a_xpath = "]/td[1]";
      //calculate rows number with size()
      int rs_c = r_table.size();
      //iterate rows of table and check matching condition
      for (int r = 2;r <= rs_c; r++) {
         String n = driver.findElement(By.xpath(b_xpath + r + a_xpath)).getText();
         if(n.contains("UFT")){
            // get text of matching cell
            String                   celtxt=driver.findElement(By.xpath("//table[@id='table1']/tbody/tr["+r+"]/td[2]")).getText();
            System.out.println("The cell data at particular row is:" + celtxt);
            break;
         }
      }
      driver.quit();
   }
}
How to create table heading in HTML?

Use the <th> tag in HTML to create a heading. The HTML <th> tag is used for specifying a header cell or table header within a table.
The following are the attributes −
You can try to run the following code to learn how to create table heading in HTML −
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
         }
      </style>
   </head>
   <body>
      <h3>Result</h3>

      <table>
         <th>Marks</th>
         <th>Student</th>

         <tr>
            <td>600</td>
            <td>Amit</td>
         </tr>
         <tr>
            <td>400</td>
            <td>Anil</td>
         </tr>
      </table>

   </body>
</html>
C# Program to remove duplicate characters from String

Use Hashset to remove duplicate characters.
Here is the string −
string myStr = "kkllmmnnoo";
Now, use HashSet to map the string to char. This will remove the duplicate characters from a string.
var unique = new HashSet<char>(myStr);
Let us see the complete example −
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         string myStr = "kkllmmnnoo";
         Console.WriteLine("Initial String: "+myStr);
         var unique = new HashSet<char>(myStr);
         Console.Write("New String after removing duplicates: ");
         foreach (char c in unique)
         Console.Write(c);
      }
   }
}
Initial String: kkllmmnnoo
New String after removing duplicates: klmno
Lodash - flatMap method

_.flatMap(collection, [iteratee=_.identity])

Creates a flattened array of values by running each element in collection thru iteratee and flattening the mapped results. The iteratee is invoked with three arguments: (value, index|key, collection).
collection (Array|Object) − The collection to iterate over.
collection (Array|Object) − The collection to iterate over.
[iteratee=_.identity] (Function) − The function invoked per iteration.
[iteratee=_.identity] (Function) − The function invoked per iteration.
(Array) − Returns the new flattened array.
(Array) − Returns the new flattened array.
var _ = require('lodash');
var list = [1 , 2, 3, 4, 5];
var result = _.flatMap(list, function(n) {
   return [n, n];
});

console.log(result);
Save the above program in tester.js. Run the following command to execute this program.
\>node tester.js

[
   1, 1, 2, 2, 3,
   3, 4, 4, 5, 5
]

 Print
 Add Notes
 Bookmark this page
How to create Android Hello World App?

This example demonstrates how to create Android Hello World App.
Step 1  − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2  − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Step 3  − Add the following code to src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4  − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click  Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Tryit Editor v3.7

HTML form attributes
Tryit: submit method GET
C++ Member (dot & arrow) Operators

The . (dot) operator and the -> (arrow) operator are used to reference individual members of classes, structures, and unions.
The dot operator is applied to the actual object. The arrow operator is used with a pointer to an object. For example, consider the following structure −
struct Employee {
   char first_name[16];
   int  age;
}  emp;

To assign the value "zara" to the first_name member of object emp, you would write something as follows −
strcpy(emp.first_name, "zara");

If p_emp is a pointer to an object of type Employee, then to assign the value "zara" to the first_name member of object emp, you would write something as follows −
strcpy(p_emp->first_name, "zara");

The -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign.
Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
string.whitespace in Python - GeeksforGeeks

15 Oct, 2019
In Python3, string.whitespace is a pre-initialized string used as string constant. In Python, string.whitespace will give the characters space, tab, linefeed, return, formfeed, and vertical tab.
Syntax : string.whitespace
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return the characters space, tab, linefeed, return, formfeed, and vertical tab.
Note : Make sure to import string library function inorder to use string.whitespace
Code #1 :
# import string library function import string   print("Hello")# Storing the characters space, tab etcresult = string.whitespace  # Printing the valuesprint(result)print("Geeksforgeeks")
Hello
     

u000bf
Geeksforgeeks

 Code #2 : Given code tests for the whitespace values.
# import string library function import string     # An input string.Sentence = "Hey, Geeks !, How are you?"  for i in Sentence:          # checking whether the whitespace is present     if i in string.whitespace:                  # Printing the whitespace values         print("printable Value is: " + i)
printable Value is:  
printable Value is:  
printable Value is:  
printable Value is:  
printable Value is:

shubham_singh
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Difference between == and is operator in Python

17 Jun, 2022
The Equality operator (==) is a comparison operator in Python that compare values of both the operands and checks for value equality. Whereas the ‘is’ operator is the  identity operator that checks whether both the operands refer to the same object or not (present in the same memory location).
Illustration:
# Equality operator
>>> a=10
>>>b=10
>>>a==b
True

>>>a=10     
>>>id(a)
2813000247664   

>>>b=10
2813000247664    # Both a and b is pointing to the same object

>>>a is b
True

>>>c=a       # Here variable a is assigned to new variable c, which holds same object and same memory location

>>> id(c)
2813000247664

>>>a is c     
True
Example 1:
Python3
# python3 code to# illustrate the# difference between# == and is operator# [] is an empty listlist1 = []list2 = []list3=list1 if (list1 == list2):    print("True")else:    print("False") if (list1 is list2):    print("True")else:    print("False") if (list1 is list3):    print("True")else:       print("False") list3 = list3 + list2 if (list1 is list3):    print("True")else:       print("False")
Output: 
True
False
True
False
The output of the first if the condition is “True” as both list1 and list2 are empty lists.
Second, if the condition shows “False” because two empty lists are at different memory locations. Hence list1 and list2 refer to different objects. We can check it with id() function in python which returns the “identity” of an object.
The output of the third if the condition is “True” as both list1 and list3 are pointing to the same object.
The output of the fourth if the condition is “False” because the concatenation of two lists always produces a new list.
Example 2
Python3
list1 = []list2 = [] print(id(list1))print(id(list2))
Output: 
139877155242696
139877155253640
This shows that list1 and list2 refer to different objects.
XAkash
anshitaagarwal
anubhavchauhan177
sheetal18june
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
PostgreSQL – CUBE

01 Jun, 2020
In PostgreSQL, CUBE is used to generate multiple grouping sets at once. It is a subclass of the GROUP BY clause and comes in handy while generating multiple grouping sets. A grouping set is a set of columns to which you want to group.
Syntax:
SELECT
    column1,
    column2,
    column3,
    aggregate (column4)
FROM
    table_name
GROUP BY
    CUBE (column1, column2, column3);
Let’s analyze the above syntax:
First, define the CUBE subclause in the the GROUP BY clause of the SELECT statement.
Then in the select list, indicate the columns which you want to analyze and add the aggregation function expressions.
Lastly, in the GROUP BY clause, set the dimension columns within the parentheses of the CUBE subclause.
The query yield all feasible grouping sets based on the dimension columns set in CUBE. The CUBE subclause is a short way to define multiple grouping sets. Normally if the number of columns set in the CUBE is n, then it generates 2n combinations.To better understand the concept let’s create a new table and proceed to the examples.To create a sample table use the below command:
CREATE TABLE geeksforgeeks_courses(
    course_name VARCHAR NOT NULL,
    segment VARCHAR NOT NULL,
    quantity INT NOT NULL,
    PRIMARY KEY (course_name, segment)
);
Now insert some data into it using the below command:
INSERT INTO geeksforgeeks_courses(course_name, segment, quantity)
VALUES
    ('Data Structure in Python', 'Premium', 100),
    ('Algorithm Design in Python', 'Basic', 200),
    ('Data Structure in Java', 'Premium', 100),
    ('Algorithm Design in Java', 'Basic', 300);
Now that our table is set let’s look into examples.
Example 1:The following query uses the CUBE subclause to generate multiple grouping sets as follows:
SELECT
    course_name,
    segment,
    SUM (quantity)
FROM
    geeksforgeeks_courses
GROUP BY
    CUBE (course_name, segment)
ORDER BY
    course_name,
    segment;
Output:
Example 2:The following query performs a partial CUBE as follows:
SELECT
    course_name,
    segment,
    SUM (quantity)
FROM
    geeksforgeeks_courses
GROUP BY
    course_name,
    CUBE (segment)
ORDER BY
    course_name,
    segment;
Output:
postgreSQL-grouping-sets
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Rename Table
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Identity Column
PostgreSQL - CREATE SCHEMA
How to write an inline IF statement in JavaScript ?

29 May, 2019
We can write an inline IF statement in javascript using the methods described below.Method 1: In this method we write an inline IF statement Without else, only by using the statement given below.
Syntax:
(a < b) && (your code here)

Above statement is equivalent to
if(a < b){
   // Your code here
}

Example: Below is the implementation of above approach:
<script>    // Javascript script     // to write an inline IF    // statement          // Function using inline 'if'    // statement to print maximum    // number    function max(n, m){                  // Inline 'if' statement only        // If n > m then this will execute        (n > m) && document.write(n + "<br>");        // Above statement is equivalent to        // if(n > m){        //    document.write(n + "<br>");        // }                  // Inline 'if' statement only        // If m > n then this will execute        (m > n) && document.write(m + "<br>");        // Above statement is equivalent to        // if(m > n){        //    document.write(m + "<br>");        // }    }                //Driver code    var a = -10;    var b = 5;          // Call function    max(a, b);          // Update value    a = 50;    b = 20;          // Call function    max(a, b);</script>
Output:
5
50

Method 2: In this method, we will use ternary operator to write inline if statement.
Syntax:
result = condition ? value1 : value2;

If condition is true then value1 will be assigned to result variable and if wrong then value2 will be assigned.
Example: Below is the implementation of above approach:
<script>    // Javascript script     // to write an inline IF    // statement          // Function using inline 'if'    // statement to return maximum    // number    function max(n, m){                  // Inline 'if' statement        // using ternary operator        var x = (n > m) ? n : m;        // Above statement is equivalent to        // if(n > m){        //    x = n;        // }        // else {        //    x = m;             // }                  return x;    }          //Driver code    var a = -10;    var b = 5;    var res;          // Call function    res = max(a, b);    // Print result    document.write(res + "<br>");          // Update value    a = 50;    b = 20;          // Call function    res = max(a, b);    // Print result    document.write(res + "<br>");</script>                    
Output:
5
50

JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Playing Youtube Video using Python

29 Aug, 2020
In this article, we will see how we can play youtube video in python. In order to play youtube videos in python we need pafy and vlc module.
Pafy is a Python library to download YouTube content and retrieve metadata. Below is the command to install pafy
pip install pafy

VLC : is a python library to use the functionality of the vlc media player. In order to use the vlc module in python the user system should have a compatible version of VLC player as well. Below is the command to install vlc module
pip install python-vlc

Steps for implementation :1. Import the pafy and vlc module2. Create a variable having URL of the video3. Create a pafy object using the link4. Get the best quality stream of the given youtube link5. Create a vlc MediaPlayer object by passing the best Stream6. Play the video
Below is the implementation
# importing vlc moduleimport vlc  # importing pafy moduleimport pafy  # url of the videourl = "https://www.youtube.com/watch?v = vG2PNdI8axo"  # creating pafy object of the videovideo = pafy.new(url)  # getting best streambest = video.getbest()  # creating vlc media player objectmedia = vlc.MediaPlayer(best.url)  # start playing videomedia.play()
Output :
Another example
# importing vlc moduleimport vlc  # importing pafy moduleimport pafy  # url of the videourl = "https://www.youtube.com/watch?v=il_t1WVLNxk&list=PLqM7alHXFySGqCvcwfqqMrteqWukz9ZoE"  # creating pafy object of the videovideo = pafy.new(url)  # getting stream at index 0best = video.streams[0]  # creating vlc media player objectmedia = vlc.MediaPlayer(best.url)  # start playing videomedia.play()
Output :
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
How to Turn Off the Axes for Subplots in Matplotlib?

29 Oct, 2021
In this article, we are going to discuss how to turn off the axes of subplots using matplotlib module. We can turn off the axes for subplots and plots using the below methods:
Method 1: Using matplotlib.axes.Axes.axis()
To turn off the axes for subplots, we will matplotlib.axes.Axes.axis() method here.
Python3
# import required modulesimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np     # assign data   x = np.asarray([0, 1, 2, 3, 0.5,                1.5, 2.5, 1, 2,                1.5]) y = np.asarray([0, 0, 0, 0, 1.0,                1.0, 1.0, 2, 2,                3.0]) triangles = [[0, 1, 4], [1, 5, 4],            [2, 6, 5], [4, 5, 7],            [5, 6, 8], [5, 8, 7],            [7, 8, 9], [1, 2, 5],            [2, 3, 6]] # depict illustrationtriang = mtri.Triangulation(x, y, triangles)z = np.cos(1.5 * x) * np.cos(1.5 * y)     fig, axs = plt.subplots()axs.tricontourf(triang, z)axs.triplot(triang, 'go-', color ='white') # turn off the axesaxs.set_axis_off() # assign titleaxs.set_title('Triangle illustration') plt.show()
Output:
Here, we turn off axes using the axis(“off”) statement.  
Method 2: Using matplotlib.axes.Axes.set_axis_off()
We use matplotlib.axes.Axes.set_axis_off() to turn the x-and y-pivot off influencing the axis lines, ticks, ticklabels, network and axis marks as well.
Python3
# import required modulesimport matplotlib.pyplot as pltimport numpy as np     # time series datageeksx = np.array([24.40, 110.25, 20.05,                22.00, 61.90, 7.80,                15.00]) geeksy = np.array([24.40, 110.25, 20.05,                22.00, 61.90, 7.80,                15.00])     # depict illustration   fig, ax = plt.subplots()ax.xcorr(geeksx, geeksy, maxlags = 6,        color ="green") # turn off the axesax.set_axis_off() # assign titleax.set_title('Time series graph')plt.show()
Output:
Method 3: Using matplotlib.pyplot.axis()
In a visualization, if the figure has a single plot in it, we can turn off the axes for subplots by making look like a contention to the matplotlib.pyplot.axis() technique. If the figure contains different subplots, this technique just turns off axes for the last subplot.
Python3
# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)):    y.append(max(0, x[i])) # depicting the visualizationax = plt.plot(x, y, color='green') # turn off the axesplt.axis('off') # displaying the titleplt.title("ReLU function graph") plt.show()
Output:
Here, we turn off axes using the plt.axis(“off”) statement.  
sumitgumber28
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create new instance of an Array with Java Reflection Method

A new instance of an Array can be created using the java.lang.reflect.Array.newInstance() method. This method basically creates a new array with the required component type as well as length.
A program that demonstrates the creation of an array using the Array.newInstance() method is given as follows −
 Live Demo
import java.lang.reflect.Array;
public class Demo {
   public static void main (String args[]) {
      int arr[] = (int[])Array.newInstance(int.class, 5);
      Array.set(arr, 0, 5);
      Array.set(arr, 1, 1);
      Array.set(arr, 2, 9);
      Array.set(arr, 3, 3);
      Array.set(arr, 4, 7);
      System.out.print("The array elements are: ");
      for(int i: arr) {
         System.out.print(i + " ");
      }
   }
}
The array elements are: 5 1 9 3 7
Now let us understand the above program.
A new array instance is created using the Array.newInstance() method. Then the Array.set() method is used to set the values for the array. A code snippet which demonstrates this is as follows −
int arr[] = (int[])Array.newInstance(int.class, 5);
Array.set(arr, 0, 5);
Array.set(arr, 1, 1);
Array.set(arr, 2, 9);
Array.set(arr, 3, 3);
Array.set(arr, 4, 7);
Then the array elements are displayed using the for loop. A code snippet which demonstrates this is as follows −
System.out.print("The array elements are: ");
for(int i: arr) {
   System.out.print(i + " ");
}
Java short Keyword

❮ Java Keywords

short myNum = 5000;
System.out.println(myNum);


Try it Yourself »

The short keyword is a data type that can store whole numbers from -32768 to 32767.
Read more about data types in our Java Data Types Tutorial.

❮ Java Keywords

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.
What is the difference between na.omit and complete.cases in R?

The na.omit function removes all the missing values in a data frame and complete.cases also does the same thing if applied to the whole data frame. The main difference between the two is that complete.cases can be applied to some columns or rows. Check out the below example to understand the difference.
Consider the below data frame:
Live Demo
> set.seed(2584)
> x<-sample(c(NA,2,8,6,5,4),20,replace=TRUE)
> y<-sample(c(NA,5,25),20,replace=TRUE)
> df<-data.frame(x,y)
> df
   x y
1 NA 25
2 5 5
3 8 NA
4 6 5
5 4 NA
6 4 5
7 6 NA
8 4 NA
9 4 5
10 8 5
11 8 5
12 6 25
13 5 25
14 6 5
15 5 5
16 4 5
17 NA 25
18 8 NA
19 4 NA
20 8 5
Applying na.omit to df:
> na.omit(df)
  x y
2 5 5
4 6 5
6 4 5
9 4 5
10 8 5
11 8 5
12 6 25
13 5 25
14 6 5
15 5 5
16 4 5
20 8 5
Applying complete.cases to df:
> df[complete.cases(df),]
  x y
2 5 5
4 6 5
6 4 5
9 4 5
10 8 5
11 8 5
12 6 25
13 5 25
14 6 5
15 5 5
16 4 5
20 8 5
Applying complete.cases to df to remove missing values in column 1 only:
> df[complete.cases(df[,1]),]
  x y
2 5 5
3 8 NA
4 6 5
5 4 NA
6 4 5
7 6 NA
8 4 NA
9 4 5
10 8 5
11 8 5
12 6 25
13 5 25
14 6 5
15 5 5
16 4 5
18 8 NA
19 4 NA
20 8 5
Applying complete.cases to df to remove missing values in column 2 only:
> df[complete.cases(df[,2]),]
   x y
1 NA 25
2 5 5
4 6 5
6 4 5
9 4 5
10 8 5
11 8 5
12 6 25
13 5 25
14 6 5
15 5 5
16 4 5
17 NA 25
20 8 5
GDB - Debugging Example1

Let us write a program to generate a core dump.
#include <iostream>
using namespace std;  

int divint(int, int);  
int main() 
{ 
   int x = 5, y = 2; 
   cout << divint(x, y); 
   
   x =3; y = 0; 
   cout << divint(x, y); 
   
   return 0; 
}  

int divint(int a, int b) 
{ 
   return a / b; 
}   
To enable debugging, the program must be compiled with the -g option.
$g++ -g crash.cc -o crash 

NOTE: We are using g++ compiler because we have used C++ source code.
Now, when you run this program on your linux machine, it will produce the following result:
Floating point exception (core dumped) 

You will find a core file in your current directory.
Now to debug the problem, start gdb debugger at the command prompt:
$gdb crash 
# Gdb prints summary information and then the (gdb) prompt
  
(gdb) r 
Program received signal SIGFPE, Arithmetic exception. 
0x08048681 in divint(int, int) (a=3, b=0) at crash.cc:21 
21        return a / b; 

# 'r' runs the program inside the debugger 
# In this case the program crashed and gdb prints out some 
# relevant information.  In particular, it crashed trying 
# to execute line 21 of crash.cc.  The function parameters 
# 'a' and 'b' had values 3 and 0 respectively.  

(gdb) l 
# l is short for 'list'.  Useful for seeing the context of 
# the crash, lists code lines near around 21 of crash.cc  

(gdb) where 
#0  0x08048681 in divint(int, int) (a=3, b=0) at crash.cc:21 
#1  0x08048654 in main () at crash.cc:13 
# Equivalent to 'bt' or backtrace.  Produces what is known 
# as a 'stack trace'.  Read this as follows:  The crash occurred 
# in the function divint at line 21 of crash.cc.  This, in turn, 
# was called from the function main at line 13 of crash.cc  

(gdb) up 
# Move from the default level '0' of the stack trace up one level 
# to level 1.  

(gdb) list 
# list now lists the code lines near line 13 of crash.cc  

(gdb) p x 
# print the value of the local (to main) variable x 

In this example, it is fairly obvious that the crash occurs because of the attempt to divide an integer by 0.
To debug a program 'crash' that has crashed and produced a core file named 'core', type the following at the command line:
gdb crash core 

As this is mostly equivalent to starting gdb and typing the 'r' command, all of the commands above could now be used to debug the file.
 Print
 Add Notes
 Bookmark this page
MySQL “order by” inside of “group by”? Is it possible?

Instead of using ORDER BY inside GROUP BY, you can use the MAX() aggregate function.
The syntax is as follows −
SELECT yourNameColumnName,MAX(yourRankColumnName) FROM yourTableName
GROUP BY yourNameColumnName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table MaxDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20),
   -> UserRank int
   -> );
Query OK, 0 rows affected (0.77 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into MaxDemo(UserName,UserRank) values('Larry',2);
Query OK, 1 row affected (0.21 sec)
mysql> insert into MaxDemo(UserName,UserRank) values('Sam',1);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MaxDemo(UserName,UserRank) values('Sam',2);
Query OK, 1 row affected (0.15 sec)
Now you can display all records from the table using a select statement. The query is as follows −
mysql> select *from MaxDemo;
+--------+----------+----------+
| UserId | UserName | UserRank |
+--------+----------+----------+
|      1 | Larry    |        2 |
|      2 | Sam      |        1 |
|      3 | Sam      |        2 |
+--------+----------+----------+
3 rows in set (0.00 sec)
Here is the query to use MAX() function to get your result −
mysql> select UserName,MAX(UserRank) from MaxDemo group by UserName;
+----------+---------------+
| UserName | MAX(UserRank) |
+----------+---------------+
| Larry    |             2 |
| Sam      |             2 |
+----------+---------------+
2 rows in set (0.00 sec)
Ubuntu - Nginx

Nginx is a much lighter web server than Apache. This web server has become quite popular in the recent years. The Apache web server can be quite complex to configure and use. However, Nginx is much simpler. This chapter will focus on how to install this light web server.
To install Nginx, following are the steps −
Step 1 − Open the command terminal on Ubuntu desktop and run the following command.
sudo apt-get update  

This first ensures that all packages on the operating system are up to date.
Step 2 − Next enter the following command to install the nginx server.
sudo apt-get install nginx

Step 3 − Once done, if we run ps –ef | grep nginx, we can see the process for the web server in a running state.
We now have nginx run as a web server on Ubuntu.

    8 Lectures 
     31 mins

 Musab Zayadneh

    14 Lectures 
     1.5 hours 

 Satish

    26 Lectures 
     1.5 hours 

 YouAccel
 Print
 Add Notes
 Bookmark this page
JSON.simple - Encode JSONArray

Using JSON.simple, we can encode a JSON Array using following ways −
Encode a JSON Array - to String − Simple encoding.
Encode a JSON Array - to String − Simple encoding.
Encode a JSON Array - Streaming − Output can be used for streaming.
Encode a JSON Array - Streaming − Output can be used for streaming.
Encode a JSON Array - Using List − Encoding by using the List.
Encode a JSON Array - Using List − Encoding by using the List.
Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream.
Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream.
Following example illustrates the above concepts.
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray list = new JSONArray();
      String jsonText;

      list.add("foo");
      list.add(new Integer(100));
      list.add(new Double(1000.21));
      list.add(new Boolean(true));
      list.add(null);
      jsonText = list.toString();

      System.out.println("Encode a JSON Array - to String");
      System.out.print(jsonText);

      StringWriter out = new StringWriter();
      list.writeJSONString(out);       
      jsonText = out.toString();

      System.out.println("\nEncode a JSON Array - Streaming");       
      System.out.print(jsonText);

      List list1 = new LinkedList();
      list1.add("foo");
      list1.add(new Integer(100));
      list1.add(new Double(1000.21));
      list1.add(new Boolean(true));
      list1.add(null);

      jsonText = JSONValue.toJSONString(list1); 
      System.out.println("\nEncode a JSON Array - Using List");
      System.out.print(jsonText);

      out = new StringWriter();
      JSONValue.writeJSONString(list1, out); 
      jsonText = out.toString();
      System.out.println("\nEncode a JSON Array - Using List and Stream");
      System.out.print(jsonText);
   }
}
Encode a JSON Array - to String
["foo",100,1000.21,true,null]
Encode a JSON Array - Streaming
["foo",100,1000.21,true,null]
Encode a JSON Array - Using List
["foo",100,1000.21,true,null]
Encode a JSON Array - Using List and Stream
["foo",100,1000.21,true,null]


    20 Lectures 
     1 hours 

 Laurence Svekis

    16 Lectures 
     1 hours 

 Laurence Svekis

    10 Lectures 
     1 hours 

 Laurence Svekis

    23 Lectures 
     2.5 hours 

 Laurence Svekis

    9 Lectures 
     48 mins

 Nilay Mehta

    18 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page