code-rag-bench/online-tutorials huggingface dataset:
How to Export Pandas DataFrame to CSV | by Barney H. | Towards Data Science

The easiest way to do this :
df.to_csv('file_name.csv')
If you want to export without the index, simply add index=False;
df.to_csv('file_name.csv', index=False)
If you getUnicodeEncodeError , simply add encoding='utf-8' ;
df.to_csv('file_name.csv', encoding='utf-8')
Pandas DataFrames create an excel data structure with labeled axes (rows and columns). To define one DataFrame, you need at least the rows of data and columns name (header).
Here is an example of pandas DataFrame:
Pandas DataFrame is Excel-like Data
Code to generate DataFrame:
Pandas DataFrame to_csv() function exports the DataFrame to CSV format. If a file argument is provided, the output will be the CSV file. Otherwise, the return value is a CSV format like string.
Here are some options:
path_or_buf: A string path to the file or a StringIO
dt.to_csv('file_name.csv’) # relative positiondt.to_csv('C:/Users/abc/Desktop/file_name.csv')
sep: Specify a custom delimiter for the CSV output, the default is a comma.
dt.to_csv('file_name.csv',sep='\t') # Use Tab to seperate data
na_rep: A string representation of a missing value like NaN. The default value is ‘’.
dt.to_csv('file_name.csv',na_rep='Unkown') # missing value save as Unknown
float_format: Format string for floating-point numbers.
dt.to_csv('file_name.csv',float_format='%.2f') # rounded to two decimals
header: Whether to export the column names. The default value is True.
dt.to_csv('file_name.csv',header=False)
columns: Columns to write. The default value is None, and every column will export to CSV format. If set, only columns will be exported.
dt.to_csv('file_name.csv',columns=['name'])
index: Whether to write the row index number. The default value is True.
dt.to_csv('file_name.csv',index=False)
Common scenarios of writing to CSV files
The syntax of DataFrame to_csv() is:
DataFrame.to_csv(  self,   path_or_buf,   sep: str = ',',   na_rep: str = '',   float_format: Union[str, NoneType] = None,   columns: Union[Sequence[Union[Hashable, NoneType]], NoneType] =    None,   header: Union[bool, List[str]] = True,   index: bool = True,   index_label: Union[bool, str,   Sequence[Union[Hashable, NoneType]], NoneType] = None,   mode: str = 'w',   encoding: Union[str, NoneType] = None,   compression: Union[str, Mapping[str, str], NoneType] = 'infer',    quoting: Union[int, NoneType] = None,   quotechar: str = '"',   line_terminator: Union[str, NoneType] = None,   chunksize: Union[int, NoneType] = None,   date_format: Union[str, NoneType] = None,   doublequote: bool = True,   escapechar: Union[str, NoneType] = None,   decimal: Union[str, NoneType] = '.')
Difference between Statement and PreparedStatement - GeeksforGeeks

04 Apr, 2022
1. Statement : It is used for accessing your database. Statement interface cannot accept parameters and useful when you are using static SQL statements at runtime. If you want to run SQL query only once then this interface is preferred over PreparedStatement. 
Example – 
//Creating The Statement Object  
Statement GFG = con.createStatement();
  
//Executing The Statement  
GFG.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME VARCHAR)"); 
2. PreparedStatement : It is used when you want to use SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.  
Example –  
//Creating the PreparedStatement object 
PreparedStatement GFG = con.prepareStatement("update STUDENT set NAME = ? where ID = ?");
  
//Setting values to place holders  
//Assigns "RAM" to first place holder
GFG.setString(1, "RAM");   
          
//Assigns "512" to second place holder
GFG.setInt(2, 512);     
 
//Executing PreparedStatement
GFG.executeUpdate(); 
Difference between Statement and PreparedStatement :  
ifyj4htwjrys0k10yy0va9od1lm1lmzid0pmunyy
vidhya2014n
sarthakchafle
DBMS-SQL
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Stack vs Heap Memory Allocation
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Differences between JDK, JRE and JVM
Differences between Procedural and Object Oriented Programming
Difference between DDL and DML in DBMS
Difference between Primary Key and Foreign Key
Differences between IPv4 and IPv6
KnockoutJS - HTML Binding

HTML binding causes the associated DOM element to display the HTML specified by the parameter. This is very useful if you want to generate HTML markup dynamically.
html: <binding-value>

KnockoutJS sets DOM element's content to the parameter value provided. This functionality is also available in JQuery. If JQuery is not available, then KO is used to achieve this.
KnockoutJS sets DOM element's content to the parameter value provided. This functionality is also available in JQuery. If JQuery is not available, then KO is used to achieve this.
If the parameter is observable, then elements value is updated as and when the underlying observable is changed. Element is processed only once, if no observable is used.
If the parameter is observable, then elements value is updated as and when the underlying observable is changed. Element is processed only once, if no observable is used.
Let us take a look ath the following example which demonstrates the use of html binding.
<!DOCTYPE html>
   <head>
      <title>KnockoutJS Html binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <p><span data-bind="html: welcomeMessgae "></span></p>
      
      <script>
         function AppViewModel() {
            this.welcomeMessgae = ko.observable();
            this.welcomeMessgae ("<strong>Welcome to TutorialsPoint !!! For free online tutorials and courses click <a href = 'https://tutorialspoint.com/'>here</a>.</strong>");
         }
         
         ko.applyBindings(new AppViewModel());
      </script>
      
   </body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above code in html-bind.htm file.
Save the above code in html-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Welcome to TutorialsPoint !!! For free online tutorials and courses click here.

    38 Lectures 
     2 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Ruby | Array bsearch() operation - GeeksforGeeks

08 Jan, 2020
Array#bsearch() : bsearch() is an Array class method which finds a value from the array that meets with the given condition. It’s complexity is O(log n) where n is the array size. This method can work in both the modes – find-minimum and find-any mode.
Syntax:  Array.bsearch()

Parameter: 
- Arrays to search elements. 
- condition block

Return:  Array element that satisfy the given condition

Code #1 : Example for bsearch() method
# Ruby code for bsearch() method   # declaring arraya = [1, 2, 3, 4]   # declaring arrayb = [111.11, 2.5, 4.3, 2.224]  # array elements that meets the conditionputs "search : #{a.bsearch {|x| x >=4 }}\n\n"  puts "search : #{b.bsearch {|x| x >=3 }}\n\n"  puts "search : #{a.bsearch {|x| x >=2 }}\n\n"  puts "search : #{b.bsearch {|x| x >=2 }}\n\n"
Output :
search : 4

search : 4.3

search : 2

search : 111.11

Code #2 : Example for bsearch() method
# Ruby code for bsearch() method   # declaring arraya = [1, 2, 3, 4]   # declaring arrayb = [111.11, 2.5, 4.3, 2.224]  # array elements that meets the conditionputs "search : #{a.bsearch {|x| 1 - x / 4  }}\n\n"  puts "search : #{b.bsearch {|x| 2*x > 1 }}\n\n"
Output :
search : 4

search : 111.11

Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby For Beginners
React Native - Switch

In this chapter, we will explain the Switch component in a couple of steps.
We will use the HomeContainer component for logic, but we need to create the presentational component.
Let us now create a new file: SwitchExample.js.
We are passing value from the state and functions for toggling switch items to SwitchExample component. Toggle functions will be used for updating the state.
import React, { Component } from 'react'
import { View } from 'react-native'
import SwitchExample from './switch_example.js'

export default class HomeContainer extends Component {
   constructor() {
      super();
      this.state = {
         switch1Value: false,
      }
   }
   toggleSwitch1 = (value) => {
      this.setState({switch1Value: value})
      console.log('Switch 1 is: ' + value)
   }
   render() {
      return (
         <View>
            <SwitchExample
            toggleSwitch1 = {this.toggleSwitch1}
            switch1Value = {this.state.switch1Value}/>
         </View>
      );
   }
}
Switch component takes two props. The onValueChange prop will trigger our toggle functions after a user presses the switch. The value prop is bound to the state of the HomeContainer component.
import React, { Component } from 'react'
import { View, Switch, StyleSheet }

from 'react-native'

export default SwitchExample = (props) => {
   return (
      <View style = {styles.container}>
         <Switch
         onValueChange = {props.toggleSwitch1}
         value = {props.switch1Value}/>
      </View>
   )
}
const styles = StyleSheet.create ({
   container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 100
   }
})
If we press the switch, the state will be updated. You can check values in the console.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Bootstrap .btn-block class

To create a button using the .btn-block class, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>The following are block level buttons:</p>
      <button type = "button" class = "btn btn-primary btn-lg btn-block">
         Block level Primary button
      </button>
      <button type = "button" class = "btn btn-default btn-lg btn-block">
         Block level button
      </button>
   </body>
</html>
Python – itertools.repeat()

19 Feb, 2020
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Note: For more information, refer to Python Itertools
itertools.repeat()falls under the category of infinite iterators. In repeat() we give the data and give the number, how many times the data will be repeated. If we will not specify the number, it will repeat infinite times. In repeat(), the memory space is not created for every variable. Rather it creates only one variable and repeats the same variable.
Syntax: repeat(val, num)
Parameters:val: The value to be printed.num: If the optional keyword num is mentioned, then it repeatedly prints the passed value num number of times, otherwise prints the passed value infinite number of times.
Example 1:
# Python code to demonstrate the working of    # repeat()              import itertools           # using repeat() to repeatedly print number   print ("Printing the numbers repeatedly : ")   print (list(itertools.repeat(25, 4)))
Output:
Printing the numbers repeatedly : 
[25, 25, 25, 25]

Example 2:
# Python code to demonstrate the working of    # repeat()    import itertools  # using repeat() to repeatedly print string print(list(map(str.upper,                itertools.repeat('geeksforgeeks', 3))))
Output:
['GEEKSFORGEEKS', 'GEEKSFORGEEKS', 'GEEKSFORGEEKS']

Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SELECT a FLOAT with given precision in MySQL

You can use ROUND() function.
The syntax is as follows
SELECT ROUND(yourColumnName,yourPrecisionIntegerValue) from yourTableName;
To understand the concept, let us create a table. The query to create a table is as follows
mysql> create table givenPrecisionDemo
   -> (
   -> Amount float
   -> );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into givenPrecisionDemo(Amount) values(45.678);
Query OK, 1 row affected (0.12 sec)
mysql> insert into givenPrecisionDemo(Amount) values(123.456);
Query OK, 1 row affected (0.15 sec)
mysql> insert into givenPrecisionDemo(Amount) values(245.890);
Query OK, 1 row affected (0.20 sec)
mysql> insert into givenPrecisionDemo(Amount) values(980.678);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from givenPrecisionDemo;
The following is the output
+---------+
| Amount  |
+---------+
| 45.678  |
| 123.456 |
| 245.89  |
| 980.678 |
+---------+
4 rows in set (0.00 sec)
Here is the query to SELECT a FLOAT with given precision
mysql> SELECT ROUND(Amount,2) from givenPrecisionDemo;
The following is the output
+-----------------+
| ROUND(Amount,2) |
+-----------------+
| 45.68           |
| 123.46          |
| 245.89          |
| 980.68          |
+-----------------+
4 rows in set (0.00 sec)
OCR of Handwritten digits | OpenCV - GeeksforGeeks

26 Mar, 2020
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.
Data Used
This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.
Below is the implementation.
import numpy as npimport cv2         # Read the imageimage = cv2.imread('digits.png')  # gray scale conversiongray_img = cv2.cvtColor(image,                        cv2.COLOR_BGR2GRAY)  # We will divide the image# into 5000 small dimensions # of size 20x20divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))  # Convert into Numpy array# of size (50,100,20,20)NP_array = np.array(divisions)   # Preparing train_data# and test_data.# Size will be (2500,20x20)train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)  # Size will be (2500,20x20)test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)  # Create 10 different labels # for each type of digitk = np.arange(10)train_labels = np.repeat(k,250)[:,np.newaxis]test_labels = np.repeat(k,250)[:,np.newaxis]   # Initiate kNN classifierknn = cv2.ml.KNearest_create()  # perform training of dataknn.train(train_data,          cv2.ml.ROW_SAMPLE,           train_labels)   # obtain the output from the# classifier by specifying the# number of neighbors.ret, output ,neighbours,distance = knn.findNearest(test_data, k = 3)   # Check the performance and# accuracy of the classifier.# Compare the output with test_labels# to find out how many are wrong.matched = output==test_labelscorrect_OP = np.count_nonzero(matched)   #Calculate the accuracy.accuracy = (correct_OP*100.0)/(output.size)   # Display accuracy.print(accuracy)
Output
91.64
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to declare an empty string array in C#?

In C#, you can use strings as an array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class.
To declare an empty string.
string[] arr = new string[] {}; // empty string
Now let us see what will happen when we will print this empty string.
 Live Demo
using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         string[] arr = new string[] {}; // empty string

         string res = String.Join(" ", arr);
   
         // let us now print the empty string
         Console.WriteLine("This won't print any message since its an empty string {0}", res);
      }
   }
}
This won't print any message since its an empty string
How to use the ValidateSet Attribute in PowerShell function?

The ValidateSet attribute in PowerShell function is to validate the values entered from the set which
means, it allows only specific values from the set. To understand better consider the below example, we
have an array and we need to check if entered values are among array or not then we will use the below
code.
Function PetAnimalsCheck {
   param(
      [String]$Animal
   )
   $Animals = "Cow","Dog","Cat","Horse","Camel","Elephant"
   if($Animals -contains $Animal) {
      Write-Output "Animal is in the list of Pet Animals"
   } else {
      Write-Output "Animal is not Pet Animal"
   }
}
PS C:\> PetAnimalsCheck -Animal Dog
Animal is in the list of Pet Animals
PS C:\> PetAnimalsCheck -Animal Tiger
Animal is not Pet Animal
If we replace the above commands with the ValidateSet attribute, code will be of few lines.
Function PetAnimalsCheck {
   param(
      [ValidateSet("Cow","Dog","Cat","Horse","Camel","Elephant",ErrorMessage="Ani
      mal Name is not among list")]
      [String]$Animal
   )
   Write-Output "Animal is Pet Animal"
}
PS C:\> PetAnimalsCheck -Animal Tiger
PetAnimalsCheck: Cannot validate argument on parameter 'Animal'. Animal Name is not among list
PS C:\> PetAnimalsCheck -Animal Cat
Animal is Pet Animal
If you need the set to Case sensitive, use the IgnoreCase value.
Function PetAnimalsCheck {
   param(
      [ValidatepathExi]
      [ValidateSet("Cow","Dog","Cat","Horse","Camel","Elephant",ErrorMessage="Ani
      mal Name is not among list or case sensitive", IgnoreCase=$false)]
      [String]$Animal
   )
   Write-Output "Animal is Pet Animal"
}
PS C:\> PetAnimalsCheck -Animal cat
PetAnimalsCheck: Cannot validate argument on parameter 'Animal'. Animal Name is not among list or case sensitive
PS C:\> PetAnimalsCheck -Animal Cat
Animal is Pet Animal
Java â String lastIndexOf() Method

This method returns the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the character does not occur before that point.
Here is the syntax of this method −
int lastIndexOf(int ch)

Here is the detail of parameters −
ch − a character.
ch − a character.
This method returns the index.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      System.out.print("Found Last Index :" );
      System.out.println(Str.lastIndexOf( 'o' ));
   }
}
This will produce the following result −
Found Last Index :27


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to solve diamond problem using default methods in Java

Inheritance is a relation between two classes where one class inherits the properties of the other class. This relation can be defined using the extends keyword as −
public class A extends B{}
public class A extends B{
The class which inherits the properties is known as sub class or, child class and the class whose properties are inherited is super class or, parent class.
In inheritance a copy of super class members is created in the sub class object. Therefore, using the sub class object you can access the members of the both classes.
Multiple inheritance is where one class inherits the properties of multiple classes. In other words, in multiple inheritance we can have one child class and n number of parent classes. Java does not support multiple inheritance (with classes).
For instance, let us assume that Java does support multiple inheritance.
And if we have an abstract class named Sample with an abstract method demo().
Then if two other classes in the same package extends this class and try to implement its abstract method, demo().
Then, as per the basic rule of inheritance, a copy of both demo() methods should be created in the subclass object which leaves the subclass with two methods with same prototype (name and arguments).
Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call. This issue is known as diamond problem in Java.
You can achieve multiple inheritance in Java, using the default methods (Java8) and interfaces.
From Java8 on wards default methods are introduced in an interface. Unlike other abstract methods these are the methods of an interface with a default implementation. If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface.
You can have same default methods (same name and signature) in two different interfaces and, from a class you can implement these two interfaces.
If you do so, you must override the default method from the class explicitly specifying the default method along with its interface name.
Live Demo
interface MyInterface1{  
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{  
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}  
public class InterfaceExample implements MyInterface1, MyInterface2{
   public void display() {
      MyInterface1.super.display();
      //or,
      MyInterface2.super.display();
   }      
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}
display method of MyInterface1
display method of MyInterface2
How to concatenate more than 2 fields with SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function. The syntax is as follows. Let us first see using CONCAT().
SELECT CONCAT(yourColumnName1,'/',yourColumnName2, '/',yourColumnName3, '/',......N) AS anyVariableName FROM yourTableName;
The syntax is as follows:
SELECT CONCAT_WS(‘/’,yourColumnName1,yourColumnName2,.....N) AS anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table MoreThan2ColumnConcat
   -> (
   -> Id int,
   -> Name varchar(20),
   -> Age int,
   -> Marks int
   -> );
Query OK, 0 rows affected (2.59 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into MoreThan2ColumnConcat values(1,'John',24,89);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MoreThan2ColumnConcat values(11,'Larry',25,90);
Query OK, 1 row affected (0.21 sec)
mysql> insert into MoreThan2ColumnConcat values(15,'Mike',26,79);
Query OK, 1 row affected (0.13 sec)
mysql> insert into MoreThan2ColumnConcat values(16,'Sam',21,99);
Query OK, 1 row affected (0.14 sec)
Now you can display all records from the table using select statement. The query is as follows:
mysql> select *from MoreThan2ColumnConcat;
The following is the output:
+------+-------+------+-------+
| Id   | Name  | Age  | Marks |
+------+-------+------+-------+
|    1 | John  |   24 |    89 |
|   11 | Larry |   25 |    90 |
|   15 | Mike  |   26 |    79 |
|   16 | Sam   |   21 |    99 |
+------+-------+------+-------+
4 rows in set (0.00 sec)
Here is the query to concatenate more than two fields with CONCAT().
mysql> select concat(Id,'/',Name, '/',Age, '/',Marks) as ConcatMoreFields from MoreThan2ColumnConcat;
The following is the output:
+------------------+
| ConcatMoreFields |
+------------------+
| 1/John/24/89     |
| 11/Larry/25/90   |
| 15/Mike/26/79    |
| 16/Sam/21/99     |
+------------------+
4 rows in set (0.00 sec)
Let us see the query to concatenate more than two fields using CONCAT_WS().
mysql> select concat_ws('/',Id,Name,Age,Marks) as ConcatMoreFields from MoreThan2ColumnConcat;
The following is the output:
+------------------+
| ConcatMoreFields |
+------------------+
| 1/John/24/89     |
| 11/Larry/25/90   |
| 15/Mike/26/79    |
| 16/Sam/21/99     |
+------------------+
4 rows in set (0.00 sec)
PriorityQueue offer() Method in Java

10 Dec, 2018
The java.util.PriorityQueue.offer() method is used to insert a particular element into the Priority Queue. It acts similar to the add() method of Priority Queue.
Syntax:
Priority_Queue.offer(Object element)
Parameters: The parameter element is of the type PriorityQueue and refers to the element to be inserted into the Queue.
Return Value: The method returns True if the value is successfully inserted into the queue.
Exceptions: The method can throw two types of exceptions:
NullPointerException: If the element to be inserted is NULL.
ClassCastException: If an element to be inserted is of a different type that cannot be compared to the existing elements of the Queue.
Below programs illustrate the java.util.PriorityQueue.offer() methodProgram 1:
// Java code to illustrate offer()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<String> queue = new PriorityQueue<String>();          // Use add() method to add elements into the Queue        queue.add("Welcome");        queue.add("To");        queue.add("Geeks");        queue.add("4");        queue.add("Geeks");          // Displaying the PriorityQueue        System.out.println("Initial PriorityQueue: " + queue);          // Inserting using offer()        queue.offer("The");        queue.offer("Priority");        queue.offer("Class");          // Displaying th final Queue        System.out.println("Priority queue after Insertion: " + queue);    }}
Initial PriorityQueue: [4, Geeks, To, Welcome, Geeks]
Priority queue after Insertion: [4, Class, Priority, Geeks, Geeks, To, The, Welcome]

Program 2:
// Java code to illustrate offer()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();          // Use add() method to add elements into the Queue        queue.add(10);        queue.add(15);        queue.add(30);        queue.add(20);        queue.add(5);          // Displaying the PriorityQueue        System.out.println("Initial PriorityQueue: " + queue);          // Inserting using offer()        queue.offer(100);        queue.offer(120);        queue.offer(150);          // Displaying th final Queue        System.out.println("Priority queue after Insertion: " + queue);    }}
Initial PriorityQueue: [5, 10, 30, 20, 15]
Priority queue after Insertion: [5, 10, 30, 20, 15, 100, 120, 150]

Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Initialize an ArrayList in Java
How to compare numbers in Python?

You can use relational operators in python to compare numbers(both float and int) in python. These operators compare the values on either side of them and decide the relation among them. Assume variable a holds 10 and variable b holds 20, then
You can use this as follows −
a = 10
b = 20
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
This will give the output −
False
True
False
True
False
True
Sankey Charts with Multiple levels

Following is an example of a SanKey Chart with multiple levels.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a SanKey Chart with multiple levels.
We've used Sankey class to show a Sankey chart with multiple levels.
Sankey chart = new Sankey();

HelloWorld.java
package com.tutorialspoint.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

import com.googlecode.gwt.charts.client.ChartLoader;
import com.googlecode.gwt.charts.client.ChartPackage;
import com.googlecode.gwt.charts.client.ColumnType;
import com.googlecode.gwt.charts.client.DataTable;
import com.googlecode.gwt.charts.client.sankey.Sankey;

public class HelloWorld implements EntryPoint {
   private Sankey chart;

   private void initialize() {
      ChartLoader chartLoader = new ChartLoader(ChartPackage.SANKEY);
      chartLoader.loadApi(new Runnable() {
         public void run() {
            // Create and attach the chart
            chart = new Sankey();
            RootPanel.get().add(chart);
            draw();
         }
      });
   }
   private void draw() {
      // Prepare the data
      DataTable data = DataTable.create();
      data.addColumn(ColumnType.STRING, "From");
      data.addColumn(ColumnType.STRING, "To");
      data.addColumn(ColumnType.NUMBER, "Weight");

      data.addRow("Brazil","Portugal",5);
      data.addRow("Brazil","France",1 );
      data.addRow("Brazil","Spain",1 );
      data.addRow("Brazil","England",1 );
      data.addRow("Canada","Portugal",1 );
      data.addRow("Canada","France",5 );
      data.addRow("Canada","England",1 );
      data.addRow("Mexico","Portugal",1 );
      data.addRow("Mexico","France",1 );
      data.addRow("Mexico","Spain",5 );
      data.addRow("Mexico","England",1 );
      data.addRow("USA","Portugal",1 );
      data.addRow("USA","France",1 );
      data.addRow("USA","Spain",1 );
      data.addRow("USA","England",5);     
      data.addRow("Portugal","Angola", 2 );
      data.addRow("Portugal","Senegal", 1 );
      data.addRow("Portugal", "Morocco", 1 );
      data.addRow("Portugal","South Africa", 3 );

      // Draw the chart
      chart.draw(data);
      chart.setWidth("400px");
      chart.setHeight("400px");
   }
   public void onModuleLoad() {
      initialize();
   }
}
Verify the result.
wall command in Linux with Examples

27 May, 2019
wall command in Linux system is used to write a message to all users. This command displays a message, or the contents of a file, or otherwise its standard input, on the terminals of all currently logged in users. The lines which will be longer than 79 characters, wrapped by this command. Short lines are whitespace padded to have 79 characters. A carriage return and newline at the end of each line is put by wall command always. Only the superuser can write on the terminals of users who have chosen to deny messages or are using a program which automatically denies messages. Reading from a file is refused when the invoker is not superuser and the program is suid(set-user-ID) or sgid(set-group-ID).
Syntax:
wall [-n] [-t timeout] [message | file]

Options:
wall -n: This option will suppress the banner.wall -n
wall -n
wall -t: This option will abandon the write attempt to the terminals after timeout seconds. This timeout needs to be a positive integer. The by default value is 300 seconds, which is a legacy from the time when peoples ran terminals over modem lines.Example:wall -t 30
Example:
wall -t 30
wall -V : This option display version information and exit.wall -V
wall -V
wall -h : This option will display help message and exit.wall -h
wall -h
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
TCP Server-Client implementation in C
Tail command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
How to style with SASS/SCSS in React ?

16 Feb, 2021
Introduction: We can use SASS in React using a package called node-sass. Using node-sass we can just create sass files and use them as the normal CSS files in our React application and node-sass will take care of compiling sass files.
Prerequisite: Introduction to SASS
Modules: To compile sass code, node-sass can be used.
Setting up environment and execution:
Step 1: Create React App command
npx create-react-app foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Step 3: Install required modules using the following command:
npm install node-sass
Step 4: Create a sass file as shown below:
Step 5: Following will be the code in sass syntax.
Filename- App.scss:
CSS
.gfg {  background-color: green;  padding: 5px;  padding-left: 15px;    h1 {    color: white;    font-family: sans-serif;  }}
Step 6: Following will be the code in the App.js file.
Filename: App.js
Javascript
import React, { Component }  from 'react';  import './App.scss';  class App extends Component {    render() {    return (      <div className="gfg">        <h1>Geeks for Geeks</h1>      </div>    );  }    }  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Note: If there is a compiling issue downgrade node-sass as follows:
npm install node-sass@4.14.1
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
React-Questions
Technical Scripter 2020
CSS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Form validation using jQuery
How to Change the Position of Scrollbar using CSS ?
What is the difference between SCSS and SASS ?
Build a Survey Form using HTML and CSS
HTML Course | Structure of an HTML Document
How to create a table with fixed header and scrollable body ?
How to include a font .ttf using CSS ?
How to Dynamically Add/Remove Table Rows using jQuery ?
SAP ABAP - Strings

Strings, which are widely used in ABAP programming, are a sequence of characters.
We use data type C variables for holding alphanumeric characters, with a minimum of 1 character and a maximum of 65,535 characters. By default, these are aligned to the left.
The following declaration and initialization creates a string consisting of the word 'Hello'. The size of the string is exactly the number of characters in the word 'Hello'.
Data my_Char(5) VALUE 'Hello'.
Following program is an example of creating strings.
REPORT YT_SEP_15. 
DATA my_Char(5) VALUE 'Hello'. 
Write my_Char.
The above code produces the following output −
Hello

In order to find the length of character strings, we can use STRLEN statement. The STRLEN () function returns the number of characters contained in the string.
REPORT YT_SEP_15. 
DATA: title_1(10) VALUE 'Tutorials',
      length_1 TYPE I. 
	
length_1 = STRLEN( title_1 ). 
Write: / 'The Length of the Title is:', length_1.
The above code produces the following output −
The Length of the Title is: 9 

ABAP supports a wide range of statements that manipulate strings.
CONCATENATE
Two strings are joined to form a third string.
CONDENSE
This statement deletes the space characters.
STRLEN
Used to find the length of a field.
REPLACE
Used to make replacements in characters.
SEARCH
To run searches in character strings.
SHIFT
Used to move the contents of a string left or right.
SPLIT
Used to split the contents of a field into two or more fields.
The following example makes use of some of the above mentioned statements −
REPORT YT_SEP_15. 
DATA: title_1(10) VALUE 'Tutorials', 
      title_2(10) VALUE 'Point',
      spaced_title(30) VALUE 'Tutorials  Point  Limited',
      sep,
      dest1(30),
      dest2(30).
	
CONCATENATE title_1 title_2 INTO dest1. 
Write: / 'Concatenation:', dest1. 

CONCATENATE title_1 title_2 INTO dest2 SEPARATED BY sep. 
Write: / 'Concatenation with Space:', dest2. 

CONDENSE spaced_title.
Write: / 'Condense with Gaps:', spaced_title. 

CONDENSE spaced_title NO-GAPS. 
Write: / 'Condense with No Gaps:', spaced_title.
The above code produces the following output −
Concatenation: TutorialsPoint 
Concatenation with Space: Tutorials Point 
Condense with Gaps: Tutorials Point Limited 
Condense with No Gaps: TutorialsPointLimited

Note −
In case of Concatenation, the ‘sep’ inserts a space in between the fields.
In case of Concatenation, the ‘sep’ inserts a space in between the fields.
The CONDENSE statement removes blank spaces between the fields, but leaving only 1 character’s space.
The CONDENSE statement removes blank spaces between the fields, but leaving only 1 character’s space.
‘NO-GAPS’ is an optional addition to the CONDENSE statement that removes all spaces.
‘NO-GAPS’ is an optional addition to the CONDENSE statement that removes all spaces.
Python bit functions on int (bit_length, to_bytes and from_bytes)

20 Aug, 2020
The int type implements the numbers.Integral abstract base class.
1. int.bit_length()Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros.
Code to demonstrate
num = 7print(num.bit_length())  num = -7print(num.bit_length())
3
3

2. int.to_bytes(length, byteorder, *, signed=False)Return an array of bytes representing an integer.If byteorder is “big”, the most significant byte is at the beginning of the byte array. If byteorder is “little”, the most significant byte is at the end of the byte array. The signed argument determines whether two’s complement is used to represent the integer.
# Returns byte representation of 1024 in a# big endian machine.print((1024).to_bytes(2, byteorder ='big'))
b'\x04\x00'

3. int.from_bytes(bytes, byteorder, *, signed=False)Returns the integer represented by the given array of bytes.
# Returns integer value of '\x00\x10' in big endian machine.print(int.from_bytes(b'\x00\x10', byteorder ='big'))
16

mohitg593
Python-Built-in-functions
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
C / C++ Program for Subset Sum | Backtracking-4

11 Dec, 2018
Subset sum problem is to find subset of elements that are selected from a given set whose sum adds up to a given number K. We are considering the set contains non-negative values. It is assumed that the input set is unique (no duplicates are presented).
C/C++
#include <stdio.h>#include <stdlib.h>  #define ARRAYSIZE(a) (sizeof(a)) / (sizeof(a[0]))  static int total_nodes;// prints subset foundvoid printSubset(int A[], int size){    for (int i = 0; i < size; i++) {        printf("%*d", 5, A[i]);    }      printf("n");}  // inputs// s            - set vector// t            - tuplet vector// s_size       - set size// t_size       - tuplet size so far// sum          - sum so far// ite          - nodes count// target_sum   - sum to be foundvoid subset_sum(int s[], int t[],                int s_size, int t_size,                int sum, int ite,                int const target_sum){    total_nodes++;    if (target_sum == sum) {        // We found subset        printSubset(t, t_size);        // Exclude previously added item and consider next candidate        subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);        return;    }    else {        // generate nodes along the breadth        for (int i = ite; i < s_size; i++) {            t[t_size] = s[i];            // consider next level node (along depth)            subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);        }    }}  // Wrapper to print subsets that sum to target_sum// input is weights vector and target_sumvoid generateSubsets(int s[], int size, int target_sum){    int* tuplet_vector = (int*)malloc(size * sizeof(int));      subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);      free(tuplet_vector);}  int main(){    int weights[] = { 10, 7, 5, 18, 12, 20, 15 };    int size = ARRAYSIZE(weights);      generateSubsets(weights, size, 35);    printf("Nodes generated %dn", total_nodes);    return 0;}
10    7   18n   10    5   20n    5   18   12n   20   15n   20nNodes generated 126n

Please refer complete article on Subset Sum | Backtracking-4 for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
C Program to Swap two Numbers
Producer Consumer Problem in C
How to Append a Character to a String in C
Program to find Prime Numbers Between given Interval
C program to sort an array in ascending order
Set, Clear and Toggle a given bit of a number in C
Diet Plan Performance in Python

Suppose a dieter consumes calories[i], this indicates the calories on the i-th day. If we have an integer k, for every consecutive sequence of k days that is (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), they find T. The T is the total calories consumed during that sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]): But there are some conditions;
If T < lower bound, they performed poorly on their diet so lose 1 point;
If T > upper bound, they performed well on their diet so gain 1 point;
Otherwise, they performed normally. So points are the same.
At first, the dieter has zero points. We have to find the total number of points the dieter has gained.
If the array is [6,5,0,0] and k = 2 and lower := 1 and upper := 5, then the output will be 0. C[0] + C[1] > upper, so increase one point, lower <= C[1] + C[2] <= upper so no change, after that C[2] + C[3] < lower, so decrease one point, so the output will be 0.
To solve this, we will follow these steps −
temp := 0
for i in range 0 to ktemp := temp + C[k]
temp := temp + C[k]
right := k – 1, and left := 0, and points := 0
while right < length of C, doif temp < lower, then decrease points by 1, if temp > upper, then increase points by 1temp := temp – C[left]increase left and right by 1if right >= length of C, then come out from the looptemp := temp + C[right]
if temp < lower, then decrease points by 1, if temp > upper, then increase points by 1
temp := temp – C[left]
increase left and right by 1
if right >= length of C, then come out from the loop
temp := temp + C[right]
return points
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def dietPlanPerformance(self, c, k, l, u):
      temp = 0
      for i in range(k):
         temp += c[i]
      right = k-1
      left = 0
      points = 0
      while right < len(c):
         if temp<l:
            points-=1
         elif temp>u:
            points+=1
         temp -=c[left]
         left+=1
         right+=1
         if(right >= len(c)):
            break
         temp+=c[right]
      return points
ob1 = Solution()
print(ob1.dietPlanPerformance([6,5,0,0],2,1,5))
[6,5,0,0]
2
1
5
0
What is the difference between CHAR and VARCHAR in MySQL?

CHAR and VARCHAR are both ASCII character data types and almost same but they are different at the stage of storing and retrieving the data from the database. Following are some important differences between CHAR and VARCHAR in MySQL −
mysql>create table emp(name CHAR(20));
Query OK, 0 rows affected (0.25
mysql>create table emp1(name VARCHAR(20));
Query OK, 0 rows affected (0.21
Check if a number is Palindrome in PL/SQL - GeeksforGeeks

16 May, 2018
Given an integer, write a function that returns true if the given number is palindrome, else false. For example, 12321 is palindrome, but 1451 is not palindrome.
Let the given number be num. A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false.
Examples:
Input : 12221
Output : true

Input : 12345
Output : false

Below is the required implementation:
declare  -- declare variable n, m, temp -- and temp of datatype number    n number;    m number;    temp number:=0;    rem number;   begin    n:=5432112345;    m:=n;          -- while loop with condition till n>0    while n>0    loop        rem:=mod(n,10);        temp:=(temp*10)+rem;        n:=trunc(n/10);    end loop; -- end of while loop here          if m = temp    then        dbms_output.put_line('true');    else        dbms_output.put_line('false');    end if;end;/  -- Program End
Output:
true
palindrome
SQL-PL/SQL
Misc
Misc
Misc
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Association Rule
Software Engineering | Prototyping Model
Java Math min() method with Examples
Set add() method in Java with Examples
OOPs | Object Oriented Design
Distributed Database System
Advantages and Disadvantages of OOP
Consensus Algorithms in Blockchain
Find maximum (or minimum) sum of a subarray of size k
Applications of Computer Graphics
Virtual Function in C++

In this tutorial, we will be discussing a program to understand virtual functions in C++.
Virtual function is the member function defined in the base class and can further be defined in the child class as well. While calling the derived class, the overwritten function will be called.
 Live Demo
#include <iostream>
using namespace std;
class base {
   public:
   virtual void print(){
      cout << "print base class" << endl;
   }
   void show(){
      cout << "show base class" << endl;
   }
};
class derived : public base {
   public:
   void print(){
      cout << "print derived class" << endl;
   }
   void show(){
      cout << "show derived class" << endl;
   }
};
int main(){
   base* bptr;
   derived d;
   bptr = &d;
   //calling virtual function
   bptr->print();
   //calling non-virtual function
   bptr->show();
}
print derived class
show base class