code-rag-bench/online-tutorials huggingface dataset:
HAVING with GROUP BY in MySQL

To use HAVING with GROUPBY in MySQL, the following is the syntax. Here, we have set a condition under HAVING to get check for maximum value condition −
SELECT yourColumnName FROM yourTableName GROUP BY yourColumnName HAVING MAX(yourColumnName) < yourValue;
Let us see an example by creating a table in MySQL −
mysql> create table WhereAfterGroupDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserProcess int,
-> UserThreadId int
-> );
Query OK, 0 rows affected (5.74 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1211,3);
Query OK, 1 row affected (0.10 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1412,3);
Query OK, 1 row affected (0.39 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1510,4);
Query OK, 1 row affected (0.19 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1511,4);
Query OK, 1 row affected (0.31 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from WhereAfterGroupDemo;
+--------+-------------+--------------+
| UserId | UserProcess | UserThreadId |
+--------+-------------+--------------+
|      1 | 1211        |            3 |
|      2 | 1412        |            3 |
|      3 | 1510        |            4 |
|      4 | 1511        |            4 |
+--------+-------------+--------------+
4 rows in set (0.00 sec)
The following is the query to use HAVING and GROUP BY and get the UserThreaId with process less than 1510 −
mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;
+--------------+
| UserThreadId |
+--------------+
|            3 |
+--------------+
1 row in set (0.00 sec)
MongoDB aggregate $slice to get the length of the array

For this, use projectandinthat,size to get the length. Let us first create a collection with documents −
> db.demo382.insertOne(
...    {
...
...       "Name" : "David",
...       "details" : [
...          {
...             "SubjectName":"MySQL"
...          },
...          {
...             "SubjectName":"MongoDB"
...          },
...          {
...             "SubjectName":"Java"
...          }
...       ]
...
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b5e1c22064be7ab44e7f0")
}
Display all documents from a collection with the help of find() method &Minus;
> db.demo382.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"),
   "Name" : "David",
   "details" : [
      {
         "SubjectName" : "MySQL"
      },
      {
         "SubjectName" : "MongoDB"
      },
      {
         "SubjectName" : "Java"
      }
   ]
}
Following is the query to aggregate $slice and get the length −
> db.demo382.aggregate([
...    { "$match": { "Name": "David" } },
...    { "$project": { "count": { "$size": "$details" }}}
... ])
This will produce the following output −
{ "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"), "count" : 3 }
Bokeh - Customising legends

Various glyphs in a plot can be identified by legend property appear as a label by default at top-right position of the plot area. This legend can be customised by following attributes −
Example code for legend customisation is as follows −
from bokeh.plotting import figure, output_file, show
import math
x2 = list(range(1,11))
y4 = [math.pow(i,2) for i in x2]
y2 = [math.log10(pow(10,i)) for i in x2]
fig = figure(y_axis_type = 'log')
fig.circle(x2, y2,size = 5, color = 'blue', legend = 'blue circle')
fig.line(x2,y4, line_width = 2, line_color = 'red', legend = 'red line')
fig.legend.location = 'top_left'
fig.legend.title = 'Legend Title'
fig.legend.title_text_font = 'Arial'
fig.legend.title_text_font_size = '20pt'
show(fig)
 Print
 Add Notes
 Bookmark this page
Excel Sheet Column Title in C++

Suppose we have a positive integer; we have to find its corresponding column title as appear in an Excel sheet. So [1 : A], [2 : B], [26 : Z], [27 : AA], [28 : AB] etc.
So, if the input is like 28, then the output will be AB.
To solve this, we will follow these steps −
while n is non-zero, do −n := n - 1res := res + n mod 26 + ASCII of 'A'n := n / 26
while n is non-zero, do −
n := n - 1
n := n - 1
res := res + n mod 26 + ASCII of 'A'
res := res + n mod 26 + ASCII of 'A'
n := n / 26
n := n / 26
reverse the array res
reverse the array res
return res
return res
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string convertToTitle(int n) {
      string res;
      while(n){
         res += (--n)%26 + 'A';
         n /= 26;
      }
      reverse(res.begin(), res.end());
      return res;
   }
};
main(){
   Solution ob;
   cout << (ob.convertToTitle(30));
}
30
AD
Removing nth character from a string in Python program

In this article, we will learn about the solution to the problem statement given below −
We are given a string, we have to remove the ith indexed character from the given string and display it.
In any string in Python, indexing always starts from 0. Suppose we have a string “tutorialspoint” then its indexing will be done as shown below −
T u t o r i a l s p o i n t
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Now let’s see the Python script gfor solving the statement −
 Live Demo
def remove(string, i):
   # slicing till ith character
   a = string[ : i]
   # slicing from i+1th index
   b = string[i + 1: ]
   return a + b
# Driver Code
if __name__ == '__main__':
   string = "Tutorialspoint"
   # Remove nth index element
   i = 8
   print(remove(string, i))
Tutorialpoint
From the given input string, i-th indexed element has to be popped. So, Split the string into two parts, before indexed character and after indexed character thereby leaving the ith character Return the merged string.
Here we have three variables declared in global scope as shown below −
In this article, we learnt about the removal of ith character from a given input string in Python 3.x or earlier
How to update multiple rows and left pad values in MySQL?

Use the LPAD() function to left pad values. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (2.26 sec
Insert some records in the table using insert command −
mysql> insert into DemoTable values(857786);
Query OK, 1 row affected (0.26 sec)

mysql> insert into DemoTable values(89696);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values(89049443);
Query OK, 1 row affected (0.25 sec
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Number   |
+----------+
| 857786   |
| 89696    |
| 89049443 |
+----------+
3 rows in set (0.00 sec)
Following is the query to update multiple rows and left pad values −
mysql> update DemoTable set Number=LPAD(Number, 7, "9") where length(Number) < 7;
Query OK, 2 rows affected (0.40 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Number   |
+----------+
| 9857786  |
| 9989696  |
| 89049443 |
+----------+
3 rows in set (0.00 sec)
How to display the current working directory in the Linux system?

To print the current working directory, we use the pwd command in the Linux system.
pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal. This is a shell building command that is available in most Unix shells such as Bourne shell, ash, bash, kash, and zsh.
The general syntax of the pwd command is as follows −
pwd [-LP]
A brief description of options available in the pwd command.
By default, the pwd works as if -L option was specified.
The pwd command returns true unless an invalid option supplied or the current directory could not be read.
To display the current working directory, we use the pwd command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~ pwd
/home/vikash
To display the physical directory instead of symbolic links or soft links, we use -P option with the pwd command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~ pwd -P
/home/vikash
To display more about the pwd command we use -help option with the pwd command as shown below.
vikash@tutorialspoint:~ pwd --help
After execution of above command. It will be prompt a short description with available options available in the pwd command.
What is a final parameter in java?

You can pass final variables as the parameters to methods in Java.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed. So, the state of the object can be changed but not the reference. With variables, the final modifier often is used with static to make the constant a class variable.
 Live Demo
public class Test{
   public void sample(final int data){
      System.out.println(data);
   }
   public static void main(String args[]) throws Exception{
      Test t = new Test();
      t.sample(500);
   }
}
500
Push() vs unshift() in JavaScript?

The methods push() and unshift() are used to add an element in an array. But they have a slight variation. The method push() is used to add an element at the end of the array, whereas the method unshift() is used to add the element at the start of the array. Let's discuss them in detail.
array.push("element");
In the following example, to a 3 element array, using push() method another element is added at the back of the array and the result is displayed in the output.
<html>
<body>
<script>
   var companies = ["Spacex", "Hyperloop", "Solarcity"];
   document.write("Before push:" +" "+ companies);
   companies.push("Tesla");
   document.write("</br>");
   document.write("After push:" +" "+ companies);
</body>
</html>
Before push: Spacex,Hyperloop,Solarcity
After push: Spacex,Hyperloop,Solarcity,Tesla
array.unshift("element");
In the following example, to a 3 element array, using unshift() method another element is added at the start of the array and the result is displayed in the output.
<html>
<body>
<script>
   var companies = ["Spacex", "Hyperloop", "Solarcity"];
   document.write("Before unshift:" +" "+ companies);
   companies.unshift("Tesla");
   document.write("</br>");
   document.write("After unshift:" +" "+ companies);
</script>
</body>
</html>
Before unshift: Spacex,Hyperloop,Solarcity
After unshift: Tesla,Spacex,Hyperloop,Solarcity
How to check if data is NULL in MySQL?

You can use IF() to check if data is NULL.  Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(200),
   Age int
);
Query OK, 0 rows affected (0.44 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(Name,Age) values('John',23);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Age) values('Sam',null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Age) values('Mike',23);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Name,Age) values('David',21);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name,Age) values('Carol',null);
Query OK, 1 row affected (0.13 sec)
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | John  | 23   |
| 2  | Sam   | NULL |
| 3  | Mike  | 23   |
| 4  | David | 21   |
| 5  | Carol | NULL |
+----+-------+------+
5 rows in set (0.00 sec)
Here is the query to check if data is NULL or not. This adds a message wherever NULL in the record is visible −
mysql> select if(Age IS NULL,'Age is missing',Age) from DemoTable;
This will produce the following output −
+--------------------------------------+
| if(Age IS NULL,'Age is missing',Age) |
+--------------------------------------+
| 23                                   |
| Age is missing                       |
| 23                                   |
| 21                                   |
| Age is missing                       |
+--------------------------------------+
5 rows in set (0.00 sec)
Aptitude | GATE CS 1998 | Question 75 - GeeksforGeeks

20 Mar, 2020
Let p be a pointer as shown in the figure in a single linked list.What do the following assignment statements achieve ?
q: = p → next
p → next:= q → next 
q → next:=(q → next) → next 
(p → next) → next:= q
Answer:Explanation: Initially p points to i and q points to i+1.
p ->next:= q ->next : i next points to i+2q ->next:=(q ->next) ? next : i+1 next points to i+3(p ->next) ->next:= q : i+2 next points to i+1
p ->next:= q ->next : i next points to i+2
q ->next:=(q ->next) ? next : i+1 next points to i+3
(p ->next) ->next:= q : i+2 next points to i+1
Deducing finally i->i+2->i+1->i+3.
So, it swaps the two nodes next to p in the linked list.
Quiz of this Question
abhinandanbr
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
How to print number of words in textview in android?

This example demonstrate about How to print number of words in textview in android.
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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="100dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </TextView>
</LinearLayout>
In the above code, we have taken textview to show paragraph and toast will show the information about number of words.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   TextView text;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      text = findViewById(R.id.text);
      text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                    Lorem Ipsum has been the industry's standard dummy text ever since the
                    1500s, when an unknown printer took a galley of type and scrambled it to
                    make a type specimen book. It has survived not only five centuries, but
                    also the leap into electronic typesetting, remaining essentially unchanged.
                    It was popularised in the 1960s with the release of Letraset sheets
                    containing Lorem Ipsum passages, and more recently with desktop publishing
                    software like Aldus PageMaker including versions of Lorem Ipsum.");
      String[] para = text.getText().toString().split("\\s+");
      Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
   }
}
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
PostgreSQL - Size of a Table - GeeksforGeeks

22 Feb, 2021
In this article, we will look into the function that is used to get the size of the PostgreSQL database table. In this article, we will be using a sample database for reference which is described here and can be downloaded from here.
The pg_relation_size() function is used to get the size of a table. 
Syntax: select pg_relation_size('table_name');
Example 1: Here we will query for the size “country” table from the sample dvdrental database using the below command: 
select pg_relation_size('country');
Output:  
To make the result readable, one can use the pg_size_pretty() function. The pg_size_pretty() function takes the result of another function and formats it using bytes, kB, MB, GB or TB as required. 
SELECT pg_size_pretty (pg_relation_size('country'));
Output:  
Example 2: Here we will query for the size “customer” table from the sample dvdrental database using the below command: 
SELECT pg_size_pretty (pg_relation_size('customer'));
Output: 
Example 3: Here we will query for the size “film” table from the sample dvdrental database using the below command: 
SELECT pg_size_pretty (pg_relation_size('film'));
Output: 
Example 4: Here we will query for the top 10 biggest tables in the dvdrental database. 
SELECT
    relname AS "tables",
    pg_size_pretty (
        pg_total_relation_size (X .oid)
    ) AS "size"
FROM
    pg_class X
LEFT JOIN pg_namespace Y ON (Y.oid = X .relnamespace)
WHERE
    nspname NOT IN (
        'pg_catalog',
        'information_schema'
    )
AND X .relkind <> 'i'
AND nspname !~ '^pg_toast'
ORDER BY
    pg_total_relation_size (X .oid) ASC
LIMIT 10;
Output: 
RajuKumar19
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - LEFT JOIN
PostgreSQL - Rename Table
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Record type variable
PostgreSQL - While Loops
PostgreSQL - Select Into
PostgreSQL - ROW_NUMBER Function
How to create and use a named pipe in Python?

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink()). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn’t open the FIFO — it just creates the rendezvous point. To create a FIFO(named pipe) and use it in Python, you can use the os.mkfifo(). But mkfifo fails with File exists exception if file already exists. In order to avoid that, you can put it in a try-except block.
import os, sys
# Path to be created
path = "/tmp/hourly"
try:
    os.mkfifo(path)
except OSError, e:
    print "Failed to create FIFO: %s" % e
else:
    fifo = open(path, 'w')
print "Path is created"
When you run this program, you can expect the pipe to be created.
Date getTime() method in Java with Examples

02 Jan, 2019
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.
Syntax:
public long getTime()

Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
// Java code to demonstrate// getTime() function of Date class  import java.util.Date;import java.util.Calendar;public class GfG {    // main method    public static void main(String[] args)    {          // creating a Calendar object        Calendar c1 = Calendar.getInstance();          // set Month        // MONTH starts with 0 i.e. ( 0 - Jan)        c1.set(Calendar.MONTH, 11);          // set Date        c1.set(Calendar.DATE, 05);          // set Year        c1.set(Calendar.YEAR, 1996);          // creating a date object with specified time.        Date dateOne = c1.getTime();          System.out.println("Date: " + dateOne);          System.out.println(dateOne.getTime());    }}
Date: Thu Dec 05 09:29:39 UTC 1996
849778179420

// Java code to demonstrate// getTime() function of Date class  import java.util.Date;import java.util.Calendar;public class GfG {    // main method    public static void main(String[] args)    {          // creating a Calendar object        Calendar c1 = Calendar.getInstance();          // set Month        // MONTH starts with 0 i.e. ( 0 - Jan)        c1.set(Calendar.MONTH, 11);          // set Date        c1.set(Calendar.DATE, 05);          // set Year        c1.set(Calendar.YEAR, 2000);          // creating a date object with specified time.        Date dateOne = c1.getTime();          System.out.println("Date: " + dateOne);          System.out.println(dateOne.getTime());    }}
Date: Tue Dec 05 09:29:40 UTC 2000
976008580370

Java - util package
Java-Functions
Java-util-Date
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
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Python – Replace duplicate Occurrence in String

08 May, 2020
Sometimes, while working with Python strings, we can have problem in which we need to perform the replace of a word. This is quite common task and has been discussed many times. But sometimes, the requirement is to replace occurrence of only duplicate, i.e from second occurrence. This has applications in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using split() + enumerate() + loopThe combination of above functions can be used to perform this task. In this, we separate the words using split. In this, we memoize the first occurrence in set and check if the value is saved before and then is replaced is already occurred.
# Python3 code to demonstrate working of # Replace duplicate Occurrence in String# Using split() + enumerate() + loop  # initializing stringtest_str = 'Gfg is best . Gfg also has Classes now. \                Classes help understand better . '  # printing original stringprint("The original string is : " + str(test_str))  # initializing replace mapping repl_dict = {'Gfg' :  'It', 'Classes' : 'They' }  # Replace duplicate Occurrence in String# Using split() + enumerate() + looptest_list = test_str.split(' ')res = set()for idx, ele in enumerate(test_list):    if ele in repl_dict:        if ele in res:            test_list[idx] = repl_dict[ele]        else:            res.add(ele)res = ' '.join(test_list)  # printing result print("The string after replacing : " + str(res)) 
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .The string after replacing : Gfg is best . It also has Classes now. They help understand better .
 
Method #2 : Using keys() + index() + list comprehensionThis is yet another way in which this task can be performed. In this, we don’t require memoization. This is one liner approach to solve this problem.
# Python3 code to demonstrate working of # Replace duplicate Occurrence in String# Using keys() + index() + list comprehension  # initializing stringtest_str = 'Gfg is best . Gfg also has Classes now. Classes help understand better . '  # printing original stringprint("The original string is : " + str(test_str))  # initializing replace mapping repl_dict = {'Gfg' :  'It', 'Classes' : 'They' }  # Replace duplicate Occurrence in String# Using keys() + index() + list comprehensiontest_list = test_str.split(' ')res = ' '.join([repl_dict.get(val) if val in repl_dict.keys() and test_list.index(val) != idx                                    else val for idx, val in enumerate(test_list)])  # printing result print("The string after replacing : " + str(res)) 
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .The string after replacing : Gfg is best . It also has Classes now. They help understand better .
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Ways to print list without quotes

25 Jun, 2019
Whenever we print list in Python, we generally use str(list) because of which we have single quotes in the output list. Suppose if the problem requires to print solution without quotes. Let’s see some ways to print list without quotes.
Method #1: Using map()
# Python code to demonstrate # printing list in a proper way  # Initialising listini_list = ['a', 'b', 'c', 'd']  # Printing initial list with strprint ("List with str", str(ini_list))  # Printing list using mapprint ("List in proper method", '[%s]' % ', '.join(map(str, ini_list)))
List with str ['a', 'b', 'c', 'd']
List in proper method [a, b, c, d]

 Method #2: Using sep Method
# Python code to demonstrate # printing list in proper way  # Initialising listini_list = ['a', 'b', 'c', 'd']  # Printing initial list with strprint ("List with str", str(ini_list))  # Printing list using sep Methodprint (*ini_list, sep =', ')
List with str ['a', 'b', 'c', 'd']
a, b, c, d

 Method #3: Using .format()
# Python code to demonstrate # printing list in proper way  # Initialising listini_list = ['a', 'b', 'c', 'd']  # Printing initial list with strprint ("List with str", str(ini_list))  # Printing list using .format()print ("Printing list without quotes", ("[{0}]".format(                       ', '.join(map(str, ini_list)))))
List with str ['a', 'b', 'c', 'd']
Printing list without quotes [a, b, c, d]

 Method #4: Using translate Method
# Python code to demonstrate # printing list in proper way  # Initialising listini_list = ['a', 'b', 'c', 'd']  # Printing initial list with strprint ("List with str", str(ini_list))  translation = {39: None}# Printing list using translate Methodprint ("Printing list without quotes",         str(ini_list).translate(translation))
List with str ['a', 'b', 'c', 'd']
Printing list without quotes [a, b, c, d]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy fromarrays() method

19 Sep, 2019
With the help of numpy.core.fromarrays() method, we can create the record array by using the list of different arrays by using numpy.core.fromarrays() method.
Syntax : numpy.core.fromarrays([li1, li2....], metadata)
Return : Return the record of an array.
Example #1 :
In this example we can see that using numpy.core.fromarrays() method, we are able to get the record array by using list of different arrays.
# import numpyimport numpy as np  # using numpy.core.fromarrays() methodli1 = np.array([101, 102, 103, 104])li2 = np.array(['Jitender', 'Purnima', 'Ruhi', 'Varun'])li3 = np.array([21, 22, 12, 35])  gfg = np.core.records.fromarrays([li1, li2, li3],                      names ='Rollno, Name, Age')  print(gfg[1])
Output :
(102, ‘Purnima’, 22)
Example #2 :
# import numpyimport numpy as np  # using numpy.core.fromarrays() methodli1 = np.array([101, 102, 103, 104])li2 = np.array(['Jitender', 'Purnima', 'Ruhi', 'Varun'])li3 = np.array([21, 22, 12, 35])  gfg = np.core.records.fromarrays([li1, li2, li3],                      names ='Rollno, Name, Age')  print(gfg.Rollno)print(gfg.Name)print(gfg.Age)
Output :
[101 102 103 104][‘Jitender’ ‘Purnima’ ‘Ruhi’ ‘Varun’][21 22 12 35]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BeautifulSoup – Scraping List from HTML

19 Oct, 2021
Prerequisite: 
Requests
BeautifulSoup
Python can be employed to scrap information from a web page. It can also be used to retrieve data provided within a specific tag, this article how list elements can be scraped from HTML.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import module
Get HTML Code using requests module
Find all list tag using find_all() method.
Iterate through all list tag and get text using text property
Example 1: Scraping List from HTML Code
Python3
# Import Required Modulesfrom bs4 import BeautifulSoupimport requests # HTML Codehtml_content = """<ul>  <li>Coffee</li>  <li>Tea</li>  <li>Milk</li></ul>""" # Parse the html contentsoup = BeautifulSoup(html_content, "lxml") # Find all li tagdatas = soup.find_all("li") # Iterate through all li tagsfor data in datas:    # Get text from each tag    print(data.text) print(f"Total {len(datas)} li tag found")
Output:
Coffee
Tea
Milk
Total 3 li tag found
Example 2: Scraping List from Web URL
Python3
# Import Required Modulesfrom bs4 import BeautifulSoupimport requests # HTML Codehtml_content = """<ul>  <li>Coffee</li>  <li>Tea</li>  <li>Milk</li></ul>""" # Parse the html contentsoup = BeautifulSoup(html_content, "lxml") # Find all li tagdatas = soup.find_all("li") # Iterate through all li tagsfor data in datas:    # Get text from each tag    print(data.text) print(f"Total {len(datas)} li tag found")
Output:
adnanirshad158
Picked
Python BeautifulSoup
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Use of min() and max() in Python

In this article, we will be learning about min and max functions included in the Python Standard Library. It accepts infinite no of parameters according to the usage
max( arg1,arg2,arg3,...........)
Return Value − Maximum of all the arguments
Errors & Exceptions: Here error is raised only in the scenario where the arguments are not of the same type. Error is encountered while comparing them.
Let’s see what all ways we can implement the max() function first.
 Live Demo
# Getting maximum element from a set of arguments passed
print("Maximum value among the arguments passed is:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Maximum value among the arguments passed is:"+str(max('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Maximum element of the list is:"+str(max(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Maximum element of the tuple is:"+str(max(l)))
Maximum value among the arguments passed is:7
Maximum value among the arguments passed is:z
Maximum element of the list is:45
Maximum element of the tuple is:91
Here it is clearly observed that by the use of max function we can directly get the maximum values among the arguments without any comparison operations.
Similarly, we can implement the min() function here
 Live Demo
# Getting maximum element from a set of arguments passed
print("Minimum value among the arguments passed is:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Minimum value among the arguments passed is:"+str(min('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Minimum element of the list is:"+str(min(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Minimum element of the tuple is:"+str(min(l)))
Minimum value among the arguments passed is:1
Minimum value among the arguments passed is:a
Minimum element of the list is:1
Minimum element of the tuple is:1
By using built-in functions like max() & min() we can directly obtain the
corresponding maximum and minimum values without the actual implementation of
the logic to make the comparison happen
In this article, we learnt the implementation of max and min function included in the Standard Python Library.
Data Structures | Queue | Question 11 - GeeksforGeeks

06 Sep, 2019
Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are(A) Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT(B) Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR(C) Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT(D) Full: (FRONT+1) mod n == REAR, empty: REAR == FRONTAnswer: (A)Explanation:
Suppose we start filling the queue.

Let the maxQueueSize ( Capacity of the Queue) is 4.
So the size of the array which is used to implement 
this circular queue is 5, which is n.

In the beginning when the queue is empty, FRONT and REAR 
point to 0 index in the array.

REAR represents insertion at the REAR index.
FRONT represents deletion from the FRONT index.

enqueue("a"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 1)
enqueue("b"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 2)
enqueue("c"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 3)
enqueue("d"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 4)

Now the queue size is 4 which is equal to the maxQueueSize. 
Hence overflow condition is reached.

Now, we can check for the conditions.

When Queue Full :

( REAR+1)%n = (4+1)%5 = 0

FRONT is also 0.

Hence ( REAR + 1 ) %n is equal to FRONT.

When Queue Empty :

REAR was equal to FRONT when empty ( because in the starting 
before filling the queue FRONT = REAR = 0 )

Hence Option A is correct. 
Quiz of this Question
Akanksha_Rai
Data Structures
Data Structures-Queue
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Introduction to Data Structures | 10 most commonly used Data Structures
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Data Structures | Stack | Question 6
Bit manipulation | Swap Endianness of a number
Advantages of vector over array in C++
Data Structures | Stack | Question 4
How to pop the first element from a C# List?

To pop the first element in the list, use the RemoveAt() method. It eliminates the element from the position you want to remove the element.
Set the list
List<string> myList = new List<string>() {
   "Operating System",
   "Computer Networks",
   "Compiler Design"
};
Now pop the first element using RemoveAt(0)
myList.RemoveAt(0);
Let us see the complete example.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> myList = new List<string>() {
         "Operating System",
         "Computer Networks",
         "Compiler Design"
      };

      Console.Write("Initial list...");
      foreach (string list in myList) {
         Console.WriteLine(list);
      }

      Console.Write("Removing first element from the list...");
      myList.RemoveAt(0);

      foreach (string list in myList) {
         Console.WriteLine(list);
      }
   }
}
Initial list...
Operating System
Computer Networks
Compiler Design
Removing first element from the list...
Computer Networks
Compiler Design
What is difference between self and __init__ methods in python Class?



The word 'self' is used to represent the instance of a class. By using the "self" keyword we access the attributes and methods of the class in python.
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
Find out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unit
class Rectangle:
   def __init__(self, length, breadth, unit_cost=0):
       self.length = length
       self.breadth = breadth
       self.unit_cost = unit_cost
   def get_area(self):
       return self.length * self.breadth
   def calculate_cost(self):
       area = self.get_area()
       return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
This gives the output
Area of Rectangle: 19200 sq units
Cost of rectangular field: Rs.38400000
C++ Program to Find the Length of a String

A string is a one dimensional character array that is terminated by a null character. The length of a string is the number of characters in the string before the null character.
For example.
char str[] = “The sky is blue”;
Number of characters in the above string = 15
A program to find the length of a string is given as follows.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   char str[] = "Apple";
   int count = 0;
   while (str[count] != '\0')
   count++;
   cout<<"The string is "<<str<<endl;
   cout <<"The length of the string is "<<count<<endl;
   return 0;
}
The string is Apple
The length of the string is 5
In the above program, the count variable is incremented in a while loop until the null character is reached in the string. Finally the count variable holds the length of the string. This is given as follows.
while (str[count] != '\0')
count++;
After the length of the string is obtained, it is displayed on screen. This is demonstrated by the following code snippet.
cout<<"The string is "<<str<<endl;
cout<<"The length of the string is "<<count<<endl;
The length of the string can also be found by using the strlen() function. This is demonstrated in the following program.
 Live Demo
#include<iostream>
#include<string.h>
using namespace std;
int main() {
   char str[] = "Grapes are green";
   int count = 0;
   cout<<"The string is "<<str<<endl;
   cout <<"The length of the string is "<<strlen(str);
   return 0;
}
The string is Grapes are green
The length of the string is 16
Set iterator() method in Java with Examples

31 Dec, 2018
The java.util.Set.iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.
Syntax:
Iterator iterate_value = Set.iterator();

Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the set and returns the values(iterators).
Below program illustrate the java.util.Set.iterator() method:
// Java code to illustrate iterator()  import java.util.*;  public class SetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<String> set = new HashSet<String>();          // Use add() method to add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the Set        System.out.println("Set: " + set);          // Creating an iterator        Iterator value = set.iterator();          // Displaying the values after iterating through the iterator        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
Set: [4, Geeks, Welcome, To]
The iterator values are: 
4
Geeks
Welcome
To

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#iterator()
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Introduction to Java
Constructors in Java
Multithreading in Java
Python OpenCV – destroyAllWindows() Function

29 Jun, 2022
Python Opencv destroyAllWindows() function allows users to destroy or close all windows at any time after exiting the script. If you have multiple windows open at the same time and you want to close then you would use this function. It doesn’t take any parameters and doesn’t return anything. It is similar to destroyWindow() function but this function only destroys a specific window unlike destroyAllWindows().
In the Python script given below, we have created two windows named ‘P’ and ‘Q’ respectively that displayed an image of “gfg_logo.png” using the cv2.imshow() function that is supposed to display window ‘P’ first on the screen but before calling the waitKey() function to delay the closing of windows, we will destroy only the window named ‘P’ with destroyWindow(‘P’) function by passing the window name ‘P’ as its argument. We will see that the window ‘Q’ is only displayed on the screen which will close only when the user closes it.
Python
# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagescv2.imshow('P', img)cv2.imshow('Q', img) # Destroying the window named P before# calling the waitKey() functioncv2.destroyWindow('P') # using the wait key function to delay the# closing of windows till any key is pressedcv2.waitKey(0)
Output:
In this case, instead of calling destroyWindow() to delete or close a particular window, we will use destroyAllWindows() to destroy all windows on the screen here we have called this function before waitKey(0), so the images will not at all displayed on the screen. DestroyAllWindows() is just a good coding practice. 
Python
# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagescv2.imshow('P', img)cv2.imshow('Q', img) # Destroying All the windowscv2.destroyAllWindows() # using the wait key function to delay# the closing of windows till any key is pressedcv2.waitKey(0)
Output:
sheetal18june
Picked
Python-OpenCV
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Catching and Creating Exceptions

12 Jun, 2019
Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code.Because of this, if one catches all exceptions, it is absolutely critical to log or reports the actual reason for the exception somewhere (e.g., log file, error message printed to screen, etc.).
Problem – Code that catches all the exceptions
try:    ...except Exception as e:    ...    # Important     log('Reason:', e)
This will catch all exceptions save SystemExit, KeyboardInterrupt, and GeneratorExit.
Code #2 : Considering the example.
def parse_int(s):    try:        n = int(v)    except Exception:        print("Couldn't parse")
Code #3 : Using the above function
print (parse_int('n / a'), "\n")  print (parse_int('42'))
Output :
Couldn't parse

Couldn't parse

At this point, the question arises how it doesn’t work. Now if the function had been written as:
Code #4 :
def parse_int(s):    try:        n = int(v)    except Exception as e:        print("Couldn't parse")        print('Reason:', e)
In this case, the following output will be received, which indicates that a programming mistake has been made.
parse_int('42')
Output :
Couldn't parse
Reason: global name 'v' is not defined

 Problem – To wrap lower-level exceptions with custom ones that have more meaning in the context of the application (one is working on).
To create new exceptions just define them as classes that inherit from Exception (or one of the other existing exception types if it makes more sense).
Code #5 : Defining some custom exceptions
class NetworkError(Exception):    passclass HostnameError(NetworkError):    passclass TimeoutError(NetworkError):    passclass ProtocolError(NetworkError):    pass
Code #6 : Using these exceptions in the normal way.
try:    msg = s.recv()except TimeoutError as e:    ...except ProtocolError as e:    ...
Custom exception classes should almost always inherit from the built-in Exception class, or inherit from some locally defined base exception that itself inherits from Exception.
BaseException is reserved for system-exiting exceptions, such as KeyboardInterrupt or SystemExit, and other exceptions that should signal the application to exit. Therefore, catching these exceptions is not the intended use case.
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python __import__() function

As we write python programs we need various other modules to leverage their functions, classes etc. in our current program. We can import those modules at the runtime using the import function. Though you can also import named modules at the beginning of the code, you may need the module temporarily for only few lines of code or you want to make the copy of an object from the module and modify and use it.
The syntax of the __import__() function is −
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Where
name - the name of the module you want to import
globals and locals - determines how to interpret name
fromlist - objects or submodules that should be imported by name
level - specifies whether to use absolute or relative imports
In the below example we import the DateTime module and dcreate custom objects with values as needed in the program.
 Live Demo
dttime = __import__('datetime', globals(), locals(), [], 0)
print(dttime.datetime.now())
# Make a copy of dttime
x = dttime.datetime.now()
# Get your custom results
print(x.strftime("%d-%B"))

Running the above code gives us the following result −
2021-01-12 07:38:54.903330
12-January
The use of __import__ is discouraged and you can import the entire module at the beginning of the code for greater efficiency.